diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/README.md b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/README.md new file mode 100644 index 0000000000000000000000000000000000000000..de6e008316337d2f3eddf9346fc5b8502ae1c732 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/README.md @@ -0,0 +1,120 @@ +# Testing mixed int8 quantization + +![HFxbitsandbytes.png](https://cdn-uploads.huggingface.co/production/uploads/1660567705337-62441d1d9fdefb55a0b7d12c.png) + +The following is the recipe on how to effectively debug `bitsandbytes` integration on Hugging Face `transformers`. + +## Library requirements + ++ `transformers>=4.22.0` ++ `accelerate>=0.12.0` ++ `bitsandbytes>=0.31.5`. +## Hardware requirements + +The following instructions are tested with 2 NVIDIA-Tesla T4 GPUs. To run successfully `bitsandbytes` you would need a 8-bit core tensor supported GPU. Note that Turing, Ampere or newer architectures - e.g. T4, RTX20s RTX30s, A40-A100, A6000 should be supported. + +## Virtual envs + +```bash +conda create --name int8-testing python==3.8 +pip install bitsandbytes>=0.31.5 +pip install accelerate>=0.12.0 +pip install transformers>=4.23.0 +``` +if `transformers>=4.23.0` is not released yet, then use: +```bash +pip install git+https://github.com/huggingface/transformers.git +``` + +## Troubleshooting + +A list of common errors: + +### Torch does not correctly do the operations on GPU + +First check that: + +```py +import torch + +vec = torch.randn(1, 2, 3).to(0) +``` + +Works without any error. If not, install torch using `conda` like: + +```bash +conda create --name int8-testing python==3.8 +conda install pytorch torchvision torchaudio cudatoolkit=11.6 -c pytorch -c conda-forge +pip install bitsandbytes>=0.31.5 +pip install accelerate>=0.12.0 +pip install transformers>=4.23.0 +``` +For the latest pytorch instructions please see [this](https://pytorch.org/get-started/locally/) + +and the snippet above should work. + +### ` bitsandbytes operations are not supported under CPU!` + +This happens when some Linear weights are set to the CPU when using `accelerate`. Please check carefully `model.hf_device_map` and make sure that there is no `Linear` module that is assigned to CPU. It is fine to have the last module (usually the Lm_head) set on CPU. + +### `To use the type as a Parameter, please correct the detach() semantics defined by __torch_dispatch__() implementation.` + +Use the latest version of `accelerate` with a command such as: `pip install -U accelerate` and the problem should be solved. + +### `Parameter has no attribute .CB` + +Same solution as above. + +### `RuntimeError: CUDA error: an illegal memory access was encountered ... consider passing CUDA_LAUNCH_BLOCKING=1` + +Run your script by prepending `CUDA_LAUNCH_BLOCKING=1` and you should observe an error as described in the next section. + +### `CUDA illegal memory error: an illegal memory access at line...`: + +Check the CUDA versions with: +```bash +nvcc --version +``` +and confirm it is the same version as the one detected by `bitsandbytes`. If not, run: +```bash +ls -l $CONDA_PREFIX/lib/libcudart.so +``` +or +```bash +ls -l $LD_LIBRARY_PATH +``` +Check if `libcudart.so` has a correct symlink that is set. Sometimes `nvcc` detects the correct CUDA version but `bitsandbytes` doesn't. You have to make sure that the symlink that is set for the file `libcudart.so` is redirected to the correct CUDA file. + +Here is an example of a badly configured CUDA installation: + +`nvcc --version` gives: + +![Screenshot 2022-08-15 at 15.12.23.png](https://cdn-uploads.huggingface.co/production/uploads/1660569220888-62441d1d9fdefb55a0b7d12c.png) + +which means that the detected CUDA version is 11.3 but `bitsandbytes` outputs: + +![image.png](https://cdn-uploads.huggingface.co/production/uploads/1660569284243-62441d1d9fdefb55a0b7d12c.png) + +First check: + +```bash +echo $LD_LIBRARY_PATH +``` + +If this contains multiple paths separated by `:`. Then you have to make sure that the correct CUDA version is set. By doing: + +```bash +ls -l $path/libcudart.so +``` + +On each path (`$path`) separated by `:`. +If not, simply run +```bash +ls -l $LD_LIBRARY_PATH/libcudart.so +``` + +and you can see + +![Screenshot 2022-08-15 at 15.12.33.png](https://cdn-uploads.huggingface.co/production/uploads/1660569176504-62441d1d9fdefb55a0b7d12c.png) + +If you see that the file is linked to the wrong CUDA version (here 10.2), find the correct location for `libcudart.so` (`find --name libcudart.so`) and replace the environment variable `LD_LIBRARY_PATH` with the one containing the correct `libcudart.so` file. \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_4bit.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_4bit.py new file mode 100644 index 0000000000000000000000000000000000000000..b49fd43f1793f99ee1e33dd7b372b1ba51d8cea5 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_4bit.py @@ -0,0 +1,870 @@ +# Copyright 2022 The HuggingFace Team 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 clone 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. +import gc +import importlib.metadata +import tempfile +import unittest + +import pytest +from packaging import version + +from transformers import ( + AutoConfig, + AutoModel, + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoTokenizer, + BitsAndBytesConfig, + pipeline, + set_seed, +) +from transformers.models.opt.modeling_opt import OPTAttention +from transformers.testing_utils import ( + apply_skip_if_not_implemented, + backend_empty_cache, + backend_torch_accelerator_module, + is_bitsandbytes_available, + is_torch_available, + require_accelerate, + require_bitsandbytes, + require_torch, + require_torch_gpu_if_bnb_not_multi_backend_enabled, + require_torch_multi_accelerator, + slow, + torch_device, +) + + +def get_some_linear_layer(model): + if model.config.model_type == "gpt2": + return model.transformer.h[0].mlp.c_fc + elif model.config.model_type == "opt": + try: + return model.decoder.layers[0].fc1 + except AttributeError: + # for AutoModelforCausalLM + return model.model.decoder.layers[0].fc1 + elif model.config.model_type == "llama": + return model.model.layers[0].mlp.gate_proj + else: + return model.transformer.h[0].mlp.dense_4h_to_h + + +if is_torch_available(): + import torch + import torch.nn as nn + + class LoRALayer(nn.Module): + """Wraps a linear layer with LoRA-like adapter - Used for testing purposes only""" + + def __init__(self, module: nn.Module, rank: int): + super().__init__() + self.module = module + self.adapter = nn.Sequential( + nn.Linear(module.in_features, rank, bias=False), + nn.Linear(rank, module.out_features, bias=False), + ) + small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5 + nn.init.normal_(self.adapter[0].weight, std=small_std) + nn.init.zeros_(self.adapter[1].weight) + self.adapter.to(module.weight.device) + + def forward(self, input, *args, **kwargs): + return self.module(input, *args, **kwargs) + self.adapter(input) + + +if is_bitsandbytes_available(): + import bitsandbytes as bnb + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu_if_bnb_not_multi_backend_enabled +@slow +class Base4bitTest(unittest.TestCase): + # We keep the constants inside the init function and model loading inside setUp function + + # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) + # Therefore here we use only bloom-1b3 to test our module + model_name = "bigscience/bloom-1b7" + + # Constant values + EXPECTED_RELATIVE_DIFFERENCE = ( + 2.109659552692574 # This was obtained on a RTX Titan so the number might slightly change + ) + + input_text = "Hello my name is" + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I") + EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n") + EXPECTED_OUTPUTS.add("Hello my name is John Doe, I am a student at the University") + EXPECTED_OUTPUTS.add("Hello my name is John and I am 25 years old.") + EXPECTED_OUTPUTS.add("Hello my name is John and I am a student at the University of") + # Expected values on Intel XPU and NV A100 + EXPECTED_OUTPUTS.add("Hello my name is Alina. I have been working as a professional") + MAX_NEW_TOKENS = 10 + + def setUp(self): + # Models and tokenizer + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + +@apply_skip_if_not_implemented +class Bnb4BitTest(Base4bitTest): + def setUp(self): + super().setUp() + + # Models and tokenizer + self.model_fp16 = AutoModelForCausalLM.from_pretrained( + self.model_name, torch_dtype=torch.float16, device_map="auto" + ) + self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.model_fp16 + del self.model_4bit + + gc.collect() + backend_empty_cache(torch_device) + + def test_quantization_num_parameters(self): + r""" + Test if the number of returned parameters is correct + + See: https://github.com/huggingface/transformers/issues/25978 + """ + num_params_4bit = self.model_4bit.num_parameters() + num_params_fp16 = self.model_fp16.num_parameters() + + self.assertEqual(num_params_4bit, num_params_fp16) + + def test_quantization_config_json_serialization(self): + r""" + A simple test to check if the quantization config is correctly serialized and deserialized + """ + config = self.model_4bit.config + + self.assertTrue(hasattr(config, "quantization_config")) + + _ = config.to_dict() + _ = config.to_diff_dict() + + _ = config.to_json_string() + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from bitsandbytes.nn import Params4bit + + mem_fp16 = self.model_fp16.get_memory_footprint() + mem_4bit = self.model_4bit.get_memory_footprint() + + self.assertAlmostEqual(mem_fp16 / mem_4bit, self.EXPECTED_RELATIVE_DIFFERENCE, delta=1e-5) + linear = get_some_linear_layer(self.model_4bit) + self.assertTrue(linear.weight.__class__ == Params4bit) + + def test_original_dtype(self): + r""" + A simple test to check if the model successfully stores the original dtype + """ + self.assertTrue(hasattr(self.model_4bit.config, "_pre_quantization_dtype")) + self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype")) + self.assertTrue(self.model_4bit.config._pre_quantization_dtype == torch.float16) + + def test_linear_are_4bit(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from transformers import T5PreTrainedModel + + self.model_fp16.get_memory_footprint() + self.model_4bit.get_memory_footprint() + + for name, module in self.model_4bit.named_modules(): + if isinstance(module, torch.nn.Linear): + if name not in ["lm_head"] + T5PreTrainedModel._keep_in_fp32_modules: + # 4-bit parameters are packed in uint8 variables + self.assertTrue(module.weight.dtype == torch.uint8) + + def test_rwkv_4bit(self): + r""" + A simple test to check if 4-bit RWKV inference works as expected. + """ + model_id = "RWKV/rwkv-4-169m-pile" + + quantization_config = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_use_double_quant=True) + + model = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config) + tok = AutoTokenizer.from_pretrained(model_id) + + text = "Hello my name is" + input_ids = tok.encode(text, return_tensors="pt").to(torch_device) + + _ = model.generate(input_ids, max_new_tokens=30) + + def test_generate_quality(self): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = self.model_4bit.generate( + input_ids=encoded_input["input_ids"].to(self.model_4bit.device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality_config(self): + r""" + Test that loading the model with the config is equivalent + """ + bnb_config = BitsAndBytesConfig() + bnb_config.load_in_4bit = True + + model_4bit_from_config = AutoModelForCausalLM.from_pretrained( + self.model_name, quantization_config=bnb_config, device_map="auto" + ) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_4bit_from_config.generate( + input_ids=encoded_input["input_ids"].to(model_4bit_from_config.device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality_dequantize(self): + r""" + Test that loading the model and unquantize it produce correct results + """ + bnb_config = BitsAndBytesConfig(load_in_4bit=True) + + model_4bit = AutoModelForCausalLM.from_pretrained( + self.model_name, quantization_config=bnb_config, device_map="auto" + ) + + model_4bit.dequantize() + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_4bit.generate( + input_ids=encoded_input["input_ids"].to(model_4bit.device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_clear_quantization_trace(self): + r""" + Test that dequantizing the model won't leave any attribute relative to quantization in the model's configuration + """ + bnb_config = BitsAndBytesConfig(load_in_4bit=True) + model_4bit = AutoModelForCausalLM.from_pretrained( + self.model_name, quantization_config=bnb_config, device_map="auto" + ) + model_4bit.dequantize() + + self.assertFalse(hasattr(model_4bit, "hf_quantizer")) + self.assertFalse(hasattr(model_4bit.config, "quantization_config")) + self.assertFalse(hasattr(model_4bit.config, "_pre_quantization_dtype")) + self.assertFalse(hasattr(model_4bit, "quantization_method")) + self.assertFalse(model_4bit.is_quantized) + + def test_to_device_dequantized(self): + r""" + Test that dequantizing the model won't prevent converting it to a different dtype + """ + bnb_config = BitsAndBytesConfig(load_in_4bit=True) + model_4bit = AutoModelForCausalLM.from_pretrained( + self.model_name, quantization_config=bnb_config, device_map="auto" + ) + model_4bit.dequantize() + model_4bit.to(dtype=torch.float16) + + def test_device_assignment(self): + if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.2"): + self.skipTest(reason="This test requires bitsandbytes >= 0.43.2") + + mem_before = self.model_4bit.get_memory_footprint() + + # Move to CPU + self.model_4bit.to("cpu") + self.assertEqual(self.model_4bit.device.type, "cpu") + self.assertAlmostEqual(self.model_4bit.get_memory_footprint(), mem_before) + + if torch_device in ["cuda", "xpu"]: + # Move back to CUDA device + self.model_4bit.to(torch_device) + self.assertEqual(self.model_4bit.device.type, torch_device) + self.assertAlmostEqual(self.model_4bit.get_memory_footprint(), mem_before) + + def test_device_and_dtype_assignment(self): + r""" + Test whether attempting to change the device or cast the dtype of a model + after converting it to 4-bit precision will raise an appropriate error. + The test ensures that such operations are prohibited on 4-bit models + to prevent invalid conversions. + """ + + # Moving with `to` or `cuda` is not supported with versions < 0.43.2. + if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.43.2"): + with self.assertRaises(ValueError): + # Tries with `str` + self.model_4bit.to("cpu") + + with self.assertRaises(ValueError): + # Tries with a `device` + self.model_4bit.to(torch.device("cuda:0")) + + with self.assertRaises(ValueError): + # Tries with `cuda` + self.model_4bit.cuda() + + with self.assertRaises(ValueError): + # Tries with a `dtype` + self.model_4bit.to(torch.float16) + + with self.assertRaises(ValueError): + # Tries to cast the 4-bit model to float32 using `float()` + self.model_4bit.float() + + with self.assertRaises(ValueError): + # Tries to cast the 4-bit model to float16 using `half()` + self.model_4bit.half() + + # Test if we did not break anything + self.model_4bit.to(torch.device(torch_device)) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + self.model_fp16 = self.model_fp16.to(torch.float32) + _ = self.model_fp16.generate( + input_ids=encoded_input["input_ids"].to(self.model_fp16.device), max_new_tokens=10 + ) + + if torch_device in ["cuda", "xpu"]: + # Check that this does not throw an error + _ = self.model_fp16.to(torch_device) + + # Check this does not throw an error + _ = self.model_fp16.to("cpu") + + # Check this does not throw an error + _ = self.model_fp16.half() + + # Check this does not throw an error + _ = self.model_fp16.float() + + def test_fp32_4bit_conversion(self): + r""" + Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + """ + model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small", load_in_4bit=True, device_map="auto") + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32) + + def test_bnb_4bit_wrong_config(self): + r""" + Test whether creating a bnb config with unsupported values leads to errors. + """ + with self.assertRaises(ValueError): + _ = BitsAndBytesConfig(load_in_4bit=True, bnb_4bit_quant_storage="add") + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu_if_bnb_not_multi_backend_enabled +@slow +@apply_skip_if_not_implemented +class Bnb4BitT5Test(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.model_name = "google-t5/t5-small" + cls.dense_act_model_name = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.input_text = "Translate in German: Hello, my dog is cute" + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + gc.collect() + backend_empty_cache(torch_device) + + def test_inference_without_keep_in_fp32(self): + r""" + Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + from transformers import T5ForConditionalGeneration + + modules = T5ForConditionalGeneration._keep_in_fp32_modules + T5ForConditionalGeneration._keep_in_fp32_modules = None + + # test with `google-t5/t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_4bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + T5ForConditionalGeneration._keep_in_fp32_modules = modules + + def test_inference_with_keep_in_fp32(self): + r""" + Test whether it is possible to mix both `4bit` and `fp32` weights when using `keep_in_fp32_modules` correctly. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + from transformers import T5ForConditionalGeneration + + # test with `google-t5/t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + + # there was a bug with decoders - this test checks that it is fixed + self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear4bit)) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_4bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + + +@apply_skip_if_not_implemented +class Classes4BitModelTest(Base4bitTest): + def setUp(self): + super().setUp() + # model_name + self.model_name = "bigscience/bloom-560m" + self.seq_to_seq_name = "google-t5/t5-small" + + # Different types of model + + self.base_model = AutoModel.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + # Sequence classification model + self.sequence_model = AutoModelForSequenceClassification.from_pretrained( + self.model_name, load_in_4bit=True, device_map="auto" + ) + # CausalLM model + self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True, device_map="auto") + # Seq2seq model + self.seq_to_seq_model = AutoModelForSeq2SeqLM.from_pretrained( + self.seq_to_seq_name, load_in_4bit=True, device_map="auto" + ) + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.base_model + del self.sequence_model + del self.model_4bit + del self.seq_to_seq_model + + gc.collect() + backend_empty_cache(torch_device) + + def test_correct_head_class(self): + r""" + A simple test to check if the last modules for some classes (AutoModelForCausalLM or SequenceClassification) + are kept in their native class. + """ + from bitsandbytes.nn import Params4bit + + self.assertTrue(self.base_model.h[-1].mlp.dense_4h_to_h.weight.__class__ == Params4bit) + + # Other heads should be nn.Parameter + self.assertTrue(self.model_4bit.lm_head.weight.__class__ == torch.nn.Parameter) + self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) + self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) + + +@apply_skip_if_not_implemented +class Pipeline4BitTest(Base4bitTest): + def setUp(self): + super().setUp() + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + if hasattr(self, "pipe"): + del self.pipe + + gc.collect() + backend_empty_cache(torch_device) + + def test_pipeline(self): + r""" + The aim of this test is to verify that the mixed 4bit is compatible with `pipeline` from transformers. Since + we used pipeline for inference speed benchmarking we want to make sure that this feature does not break anything + on pipeline. + """ + # self._clear_cuda_cache() + self.pipe = pipeline( + "text-generation", + model=self.model_name, + model_kwargs={ + "device_map": "auto", + "load_in_4bit": True, + # float16 isn't supported on CPU, use bfloat16 instead + "torch_dtype": torch.bfloat16 if torch_device == "cpu" else torch.float16, + }, + max_new_tokens=self.MAX_NEW_TOKENS, + ) + + # Avoid sampling different outputs + set_seed(42) + # Real second forward pass + pipeline_output = self.pipe(self.input_text) + self.assertIn(pipeline_output[0]["generated_text"], self.EXPECTED_OUTPUTS) + + +@require_torch_multi_accelerator +@apply_skip_if_not_implemented +class Bnb4bitTestMultiAccelerator(Base4bitTest): + def setUp(self): + super().setUp() + + def test_multi_accelerator_loading(self): + r""" + This tests that the model has been loaded and can be used correctly on a multi-accelerator setup. + Let's just try to load a model on 2 accelerators and see if it works. The model we test has ~2GB of total, 3GB should suffice + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": 0, + "lm_head": 0, + "transformer.h.0": 0, + "transformer.h.1": 0, + "transformer.h.2": 0, + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 0, + "transformer.h.10": 1, + "transformer.h.11": 1, + "transformer.h.12": 1, + "transformer.h.13": 1, + "transformer.h.14": 1, + "transformer.h.15": 1, + "transformer.h.16": 1, + "transformer.h.17": 0, + "transformer.h.18": 0, + "transformer.h.19": 0, + "transformer.h.20": 0, + "transformer.h.21": 0, + "transformer.h.22": 0, + "transformer.h.23": 1, + "transformer.ln_f": 0, + } + + model_parallel = AutoModelForCausalLM.from_pretrained( + self.model_name, load_in_4bit=True, device_map=device_map + ) + + # Check correct device map + self.assertEqual(set(model_parallel.hf_device_map.values()), {0, 1}) + + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Second real batch + output_parallel = model_parallel.generate( + input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10 + ) + self.assertIn(self.tokenizer.decode(output_parallel[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + +@apply_skip_if_not_implemented +class Bnb4BitTestTraining(Base4bitTest): + def setUp(self): + self.model_name = "facebook/opt-350m" + super().setUp() + + def test_training(self): + if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.0"): + self.skipTest(reason="This test requires bitsandbytes >= 0.37.0") + + # Step 1: freeze all parameters + model = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True) + + if torch_device in ["cuda", "xpu"]: + self.assertEqual( + set(model.hf_device_map.values()), {backend_torch_accelerator_module(torch_device).current_device()} + ) + else: + self.assertTrue(all(param.device.type == "cpu" for param in model.parameters())) + + for param in model.parameters(): + param.requires_grad = False # freeze the model - train adapters later + if param.ndim == 1: + # cast the small parameters (e.g. layernorm) to fp32 for stability + param.data = param.data.to(torch.float32) + + # Step 2: add adapters + for _, module in model.named_modules(): + if isinstance(module, OPTAttention): + module.q_proj = LoRALayer(module.q_proj, rank=16) + module.k_proj = LoRALayer(module.k_proj, rank=16) + module.v_proj = LoRALayer(module.v_proj, rank=16) + + # Step 3: dummy batch + batch = self.tokenizer("Test batch ", return_tensors="pt").to(torch_device) + + # Step 4: Check if the gradient is not None + with torch.autocast(torch_device): + out = model.forward(**batch) + out.logits.norm().backward() + + for module in model.modules(): + if isinstance(module, LoRALayer): + self.assertTrue(module.adapter[1].weight.grad is not None) + self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) + elif isinstance(module, nn.Embedding): + self.assertTrue(module.weight.grad is None) + + +@apply_skip_if_not_implemented +class Bnb4BitGPT2Test(Bnb4BitTest): + model_name = "openai-community/gpt2-xl" + EXPECTED_RELATIVE_DIFFERENCE = 3.3191854854152187 + + +@apply_skip_if_not_implemented +class Bnb4BitLlamaTest(Bnb4BitTest): + model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" + EXPECTED_RELATIVE_DIFFERENCE = 2.9461410686392764 + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu_if_bnb_not_multi_backend_enabled +@slow +@apply_skip_if_not_implemented +class BaseSerializationTest(unittest.TestCase): + model_name = "facebook/opt-125m" + input_text = "Mars colonists' favorite meals are" + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + + def test_serialization(self, quant_type="nf4", double_quant=True, safe_serialization=True): + r""" + Test whether it is possible to serialize a model in 4-bit. Uses most typical params as default. + See ExtendedSerializationTest class for more params combinations. + """ + + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + self.quantization_config = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_quant_type=quant_type, + bnb_4bit_use_double_quant=double_quant, + bnb_4bit_compute_dtype=torch.bfloat16, + ) + model_0 = AutoModelForCausalLM.from_pretrained( + self.model_name, + quantization_config=self.quantization_config, + device_map=torch_device, + ) + + with tempfile.TemporaryDirectory() as tmpdirname: + model_0.save_pretrained(tmpdirname, safe_serialization=safe_serialization) + + config = AutoConfig.from_pretrained(tmpdirname) + self.assertTrue(hasattr(config, "quantization_config")) + + model_1 = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=torch_device) + + # checking quantized linear module weight + linear = get_some_linear_layer(model_1) + self.assertTrue(linear.weight.__class__ == bnb.nn.Params4bit) + self.assertTrue(hasattr(linear.weight, "quant_state")) + self.assertTrue(linear.weight.quant_state.__class__ == bnb.functional.QuantState) + + # checking memory footpring + self.assertAlmostEqual(model_0.get_memory_footprint() / model_1.get_memory_footprint(), 1, places=2) + + # Matching all parameters and their quant_state items: + d0 = dict(model_0.named_parameters()) + d1 = dict(model_1.named_parameters()) + self.assertTrue(d0.keys() == d1.keys()) + + for k in d0: + self.assertTrue(d0[k].shape == d1[k].shape) + self.assertTrue(d0[k].device.type == d1[k].device.type) + self.assertTrue(d0[k].device == d1[k].device) + self.assertTrue(d0[k].dtype == d1[k].dtype) + self.assertTrue(torch.equal(d0[k], d1[k].to(d0[k].device))) + + if isinstance(d0[k], bnb.nn.modules.Params4bit): + for v0, v1 in zip( + d0[k].quant_state.as_dict().values(), + d1[k].quant_state.as_dict().values(), + ): + if isinstance(v0, torch.Tensor): + # The absmax will not be saved in the quant_state when using NF4 in CPU + if v0.numel() != 0: + self.assertTrue(torch.equal(v0, v1.to(v0.device))) + else: + self.assertTrue(v0 == v1) + + # comparing forward() outputs + encoded_input = tokenizer(self.input_text, return_tensors="pt").to(torch_device) + out_0 = model_0(**encoded_input) + out_1 = model_1(**encoded_input) + torch.testing.assert_close(out_0["logits"], out_1["logits"], rtol=0.05, atol=0.05) + + # comparing generate() outputs + encoded_input = tokenizer(self.input_text, return_tensors="pt").to(torch_device) + output_sequences_0 = model_0.generate(**encoded_input, max_new_tokens=10) + output_sequences_1 = model_1.generate(**encoded_input, max_new_tokens=10) + + def _decode(token): + return tokenizer.decode(token, skip_special_tokens=True) + + self.assertEqual( + [_decode(x) for x in output_sequences_0], + [_decode(x) for x in output_sequences_1], + ) + + +@apply_skip_if_not_implemented +class ExtendedSerializationTest(BaseSerializationTest): + """ + tests more combinations of parameters + """ + + def test_nf4_single_unsafe(self): + self.test_serialization(quant_type="nf4", double_quant=False, safe_serialization=False) + + def test_nf4_single_safe(self): + self.test_serialization(quant_type="nf4", double_quant=False, safe_serialization=True) + + def test_nf4_double_unsafe(self): + self.test_serialization(quant_type="nf4", double_quant=True, safe_serialization=False) + + # nf4 double safetensors quantization is tested in test_serialization() method from the parent class + + def test_fp4_single_unsafe(self): + self.test_serialization(quant_type="fp4", double_quant=False, safe_serialization=False) + + def test_fp4_single_safe(self): + self.test_serialization(quant_type="fp4", double_quant=False, safe_serialization=True) + + def test_fp4_double_unsafe(self): + self.test_serialization(quant_type="fp4", double_quant=True, safe_serialization=False) + + def test_fp4_double_safe(self): + self.test_serialization(quant_type="fp4", double_quant=True, safe_serialization=True) + + +class BloomSerializationTest(BaseSerializationTest): + """ + default BaseSerializationTest config tested with Bloom family model + """ + + model_name = "bigscience/bloom-560m" + + +class GPTSerializationTest(BaseSerializationTest): + """ + default BaseSerializationTest config tested with GPT family model + """ + + model_name = "openai-community/gpt2-xl" + + +class LlamaSerializationTest(BaseSerializationTest): + """ + default BaseSerializationTest config tested with Llama family model + """ + + model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" + + +@require_bitsandbytes +@require_accelerate +@require_torch_gpu_if_bnb_not_multi_backend_enabled +@slow +@apply_skip_if_not_implemented +class Bnb4BitTestBasicConfigTest(unittest.TestCase): + def test_load_in_4_and_8_bit_fails(self): + with self.assertRaisesRegex(ValueError, "load_in_4bit and load_in_8bit are both True"): + AutoModelForCausalLM.from_pretrained("facebook/opt-125m", load_in_4bit=True, load_in_8bit=True) + + def test_set_load_in_8_bit(self): + quantization_config = BitsAndBytesConfig(load_in_4bit=True) + with self.assertRaisesRegex(ValueError, "load_in_4bit and load_in_8bit are both True"): + quantization_config.load_in_8bit = True + + +@require_bitsandbytes +@require_accelerate +@require_torch_gpu_if_bnb_not_multi_backend_enabled +@slow +@apply_skip_if_not_implemented +class Bnb4bitCompile(unittest.TestCase): + model_name = "hf-internal-testing/tiny-random-LlamaForCausalLM" + input_text = "Hello my name is" + + def setUp(self): + # Models and tokenizer + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + self.model_4bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_4bit=True) + + @pytest.mark.torch_compile_test + def test_generate_compile(self): + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # if nothing is set, compile will be disabled for bnb + self.model_4bit.generate( + input_ids=encoded_input["input_ids"].to(self.model_4bit.device), + max_new_tokens=10, + cache_implementation="static", + ) + with self.assertRaises(Exception): + # overwrite property + object.__setattr__(self.model_4bit.hf_quantizer, "is_compileable", True) + self.model_4bit.generate( + input_ids=encoded_input["input_ids"].to(self.model_4bit.device), + max_new_tokens=10, + cache_implementation="static", + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_mixed_int8.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_mixed_int8.py new file mode 100644 index 0000000000000000000000000000000000000000..8a3bcb84af334a89395ea811cb7f5b9b0e95f306 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/bnb/test_mixed_int8.py @@ -0,0 +1,1017 @@ +# Copyright 2022 The HuggingFace Team 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 clone 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. +import gc +import importlib.metadata +import tempfile +import unittest + +import pytest +from packaging import version + +from transformers import ( + AutoConfig, + AutoModel, + AutoModelForCausalLM, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoTokenizer, + BitsAndBytesConfig, + pipeline, + set_seed, +) +from transformers.models.opt.modeling_opt import OPTAttention +from transformers.testing_utils import ( + apply_skip_if_not_implemented, + backend_empty_cache, + backend_torch_accelerator_module, + is_accelerate_available, + is_bitsandbytes_available, + is_torch_available, + require_accelerate, + require_bitsandbytes, + require_torch, + require_torch_gpu_if_bnb_not_multi_backend_enabled, + require_torch_multi_accelerator, + slow, + torch_device, +) + + +def get_some_linear_layer(model): + if model.config.model_type == "gpt2": + return model.transformer.h[0].mlp.c_fc + elif model.config.model_type == "llama": + return model.model.layers[0].mlp.gate_proj + return model.transformer.h[0].mlp.dense_4h_to_h + + +if is_accelerate_available(): + from accelerate import PartialState + from accelerate.logging import get_logger + + logger = get_logger(__name__) + _ = PartialState() + +if is_torch_available(): + import torch + import torch.nn as nn + + class LoRALayer(nn.Module): + """Wraps a linear layer with LoRA-like adapter - Used for testing purposes only""" + + def __init__(self, module: nn.Module, rank: int, dtype: torch.dtype): + super().__init__() + self.module = module + self.adapter = nn.Sequential( + nn.Linear(module.in_features, rank, bias=False, dtype=dtype), + nn.Linear(rank, module.out_features, bias=False, dtype=dtype), + ) + small_std = (2.0 / (5 * min(module.in_features, module.out_features))) ** 0.5 + nn.init.normal_(self.adapter[0].weight, std=small_std) + nn.init.zeros_(self.adapter[1].weight) + self.adapter.to(module.weight.device) + + def forward(self, input, *args, **kwargs): + return self.module(input, *args, **kwargs) + self.adapter(input) + + +if is_bitsandbytes_available(): + import bitsandbytes as bnb + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu_if_bnb_not_multi_backend_enabled +@slow +class BaseMixedInt8Test(unittest.TestCase): + # We keep the constants inside the init function and model loading inside setUp function + + # We need to test on relatively large models (aka >1b parameters otherwise the quantiztion may not work as expected) + # Therefore here we use only bloom-1b3 to test our module + model_name = "bigscience/bloom-1b7" + + # Constant values + EXPECTED_RELATIVE_DIFFERENCE = ( + 1.540025 # This was obtained on a Quadro RTX 8000 so the number might slightly change + ) + + input_text = "Hello my name is" + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of the family.\n") + # Expected values on a A10 + EXPECTED_OUTPUTS.add("Hello my name is John.\nI am a friend of your father.\n") + MAX_NEW_TOKENS = 10 + # Expected values with offload + EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer based in") + # Expected values on Intel XPU and NV A100 + EXPECTED_OUTPUTS.add("Hello my name is Alina. I have been working as a professional") + + def setUp(self): + # Models and tokenizer + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + +@apply_skip_if_not_implemented +class MixedInt8Test(BaseMixedInt8Test): + def setUp(self): + super().setUp() + + # Models and tokenizer + self.model_fp16 = AutoModelForCausalLM.from_pretrained( + self.model_name, torch_dtype=torch.float16, device_map="auto" + ) + self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.model_fp16 + del self.model_8bit + + gc.collect() + backend_empty_cache(torch_device) + + def test_get_keys_to_not_convert(self): + r""" + Test the `get_keys_to_not_convert` function. + """ + from accelerate import init_empty_weights + + from transformers import AutoModelForMaskedLM, Blip2ForConditionalGeneration, MptForCausalLM, OPTForCausalLM + from transformers.integrations.bitsandbytes import get_keys_to_not_convert + + model_id = "mosaicml/mpt-7b" + config = AutoConfig.from_pretrained(model_id, revision="72e5f594ce36f9cabfa2a9fd8f58b491eb467ee7") + with init_empty_weights(): + model = MptForCausalLM(config) + # The order of the keys does not matter, so we sort them before comparing, same for the other tests. + self.assertEqual(get_keys_to_not_convert(model).sort(), ["lm_head", "transformer.wte"].sort()) + + model_id = "Salesforce/blip2-opt-2.7b" + config = AutoConfig.from_pretrained(model_id, revision="1ef7f63a8f0a144c13fdca8103eb7b4691c74cec") + with init_empty_weights(): + model = Blip2ForConditionalGeneration(config) + self.assertEqual( + get_keys_to_not_convert(model).sort(), + ["language_model.lm_head", "language_model.model.decoder.embed_tokens"].sort(), + ) + + model_id = "facebook/opt-350m" + config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") + with init_empty_weights(): + model = OPTForCausalLM(config) + self.assertEqual(get_keys_to_not_convert(model).sort(), ["lm_head", "model.decoder.embed_tokens"].sort()) + + model_id = "FacebookAI/roberta-large" + config = AutoConfig.from_pretrained(model_id, revision="716877d372b884cad6d419d828bac6c85b3b18d9") + with init_empty_weights(): + model = AutoModelForMaskedLM.from_config(config) + self.assertEqual( + get_keys_to_not_convert(model).sort(), + ["'roberta.embeddings.word_embeddings', 'lm_head', 'lm_head.decoder"].sort(), + ) + + def test_quantization_config_json_serialization(self): + r""" + A simple test to check if the quantization config is correctly serialized and deserialized + """ + config = self.model_8bit.config + + self.assertTrue(hasattr(config, "quantization_config")) + + _ = config.to_dict() + _ = config.to_diff_dict() + + _ = config.to_json_string() + + def test_original_dtype(self): + r""" + A simple test to check if the model successfully stores the original dtype + """ + self.assertTrue(hasattr(self.model_8bit.config, "_pre_quantization_dtype")) + self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype")) + self.assertTrue(self.model_8bit.config._pre_quantization_dtype == torch.float16) + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from bitsandbytes.nn import Int8Params + + mem_fp16 = self.model_fp16.get_memory_footprint() + mem_8bit = self.model_8bit.get_memory_footprint() + + self.assertAlmostEqual(mem_fp16 / mem_8bit, self.EXPECTED_RELATIVE_DIFFERENCE, delta=1e-5) + self.assertTrue(get_some_linear_layer(self.model_8bit).weight.__class__ == Int8Params) + + def test_linear_are_8bit(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model and the class type of the linear layers of the converted models + """ + from transformers import T5PreTrainedModel + + self.model_fp16.get_memory_footprint() + self.model_8bit.get_memory_footprint() + + for name, module in self.model_8bit.named_modules(): + if isinstance(module, torch.nn.Linear): + if name not in ["lm_head"] + T5PreTrainedModel._keep_in_fp32_modules: + self.assertTrue(module.weight.dtype == torch.int8) + + def test_llm_skip(self): + r""" + A simple test to check if `llm_int8_skip_modules` works as expected + """ + + quantization_config = BitsAndBytesConfig(load_in_8bit=True, llm_int8_skip_modules=["classifier"]) + seq_classification_model = AutoModelForSequenceClassification.from_pretrained( + "FacebookAI/roberta-large-mnli", quantization_config=quantization_config + ) + self.assertTrue(seq_classification_model.roberta.encoder.layer[0].output.dense.weight.dtype == torch.int8) + self.assertTrue( + isinstance(seq_classification_model.roberta.encoder.layer[0].output.dense, bnb.nn.Linear8bitLt) + ) + + self.assertTrue(isinstance(seq_classification_model.classifier.dense, nn.Linear)) + self.assertTrue(seq_classification_model.classifier.dense.weight.dtype != torch.int8) + self.assertTrue(isinstance(seq_classification_model.classifier.out_proj, nn.Linear)) + self.assertTrue(seq_classification_model.classifier.out_proj != torch.int8) + + def test_generate_quality(self): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = self.model_8bit.generate( + input_ids=encoded_input["input_ids"].to(self.model_8bit.device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality_config(self): + r""" + Test that loading the model with the config is equivalent + """ + bnb_config = BitsAndBytesConfig() + bnb_config.load_in_8bit = True + + model_8bit_from_config = AutoModelForCausalLM.from_pretrained( + self.model_name, quantization_config=bnb_config, device_map="auto" + ) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_8bit_from_config.generate( + input_ids=encoded_input["input_ids"].to(model_8bit_from_config.device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality_dequantize(self): + r""" + Test that loading the model and dequantizing it produce correct results + """ + bnb_config = BitsAndBytesConfig(load_in_8bit=True) + + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, quantization_config=bnb_config, device_map="auto" + ) + + model_8bit.dequantize() + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_8bit.generate( + input_ids=encoded_input["input_ids"].to(model_8bit.device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_raise_if_config_and_load_in_8bit(self): + r""" + Test that loading the model with the config and `load_in_8bit` raises an error + """ + bnb_config = BitsAndBytesConfig() + + with self.assertRaises(ValueError): + _ = AutoModelForCausalLM.from_pretrained( + self.model_name, + quantization_config=bnb_config, + load_in_8bit=True, + device_map="auto", + llm_int8_enable_fp32_cpu_offload=True, + ) + + def test_device_and_dtype_assignment(self): + r""" + Test whether attempting to change the device or cast the dtype of a model + after converting it to 8-bit precision will raise an appropriate error. + The test ensures that such operations are prohibited on 8-bit models + to prevent invalid conversions. + """ + with self.assertRaises(ValueError): + # Tries with `str` + self.model_8bit.to("cpu") + + with self.assertRaises(ValueError): + # Tries with a `dtype`` + self.model_8bit.to(torch.float16) + + with self.assertRaises(ValueError): + # Tries with a `device` + self.model_8bit.to(torch.device(torch_device)) + + with self.assertRaises(ValueError): + # Tries to cast the 8-bit model to float32 using `float()` + self.model_8bit.float() + + with self.assertRaises(ValueError): + # Tries to cast the 4-bit model to float16 using `half()` + self.model_8bit.half() + + # Test if we did not break anything + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + self.model_fp16 = self.model_fp16.to(torch.float32) + _ = self.model_fp16.generate( + input_ids=encoded_input["input_ids"].to(self.model_fp16.device), max_new_tokens=10 + ) + + # Check this does not throw an error + _ = self.model_fp16.to("cpu") + + # Check this does not throw an error + _ = self.model_fp16.half() + + # Check this does not throw an error + _ = self.model_fp16.float() + + def test_fp32_int8_conversion(self): + r""" + Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly. + """ + model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small", load_in_8bit=True, device_map="auto") + self.assertTrue(model.decoder.block[0].layer[2].DenseReluDense.wo.weight.dtype == torch.float32) + + def test_int8_serialization(self): + r""" + Test whether it is possible to serialize a model in 8-bit. + """ + from bitsandbytes.nn import Int8Params + + with tempfile.TemporaryDirectory() as tmpdirname: + self.model_8bit.save_pretrained(tmpdirname) + + # check that the file `quantization_config` is present + config = AutoConfig.from_pretrained(tmpdirname) + self.assertTrue(hasattr(config, "quantization_config")) + + model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, load_in_8bit=True, device_map="auto") + + linear = get_some_linear_layer(model_from_saved) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_from_saved.generate( + input_ids=encoded_input["input_ids"].to(model_from_saved.device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_int8_serialization_regression(self): + r""" + Test whether it is possible to serialize a model in 8-bit - using not safetensors + """ + from bitsandbytes.nn import Int8Params + + with tempfile.TemporaryDirectory() as tmpdirname: + self.model_8bit.save_pretrained(tmpdirname, safe_serialization=False) + + # check that the file `quantization_config` is present + config = AutoConfig.from_pretrained(tmpdirname) + self.assertTrue(hasattr(config, "quantization_config")) + + model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, load_in_8bit=True, device_map="auto") + + linear = get_some_linear_layer(model_from_saved) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_from_saved.generate( + input_ids=encoded_input["input_ids"].to(model_from_saved.device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_int8_serialization_sharded(self): + r""" + Test whether it is possible to serialize a model in 8-bit - sharded version. + """ + from bitsandbytes.nn import Int8Params + + with tempfile.TemporaryDirectory() as tmpdirname: + self.model_8bit.save_pretrained(tmpdirname, max_shard_size="200MB") + + # check that the file `quantization_config` is present + config = AutoConfig.from_pretrained(tmpdirname) + self.assertTrue(hasattr(config, "quantization_config")) + + model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname) + + linear = get_some_linear_layer(model_from_saved) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model_from_saved.generate( + input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10 + ) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_int8_from_pretrained(self): + r""" + Test whether loading a 8bit model from the Hub works as expected + """ + from bitsandbytes.nn import Int8Params + + model_id = "ybelkada/bloom-1b7-8bit" + + model = AutoModelForCausalLM.from_pretrained(model_id) + + linear = get_some_linear_layer(model) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu_if_bnb_not_multi_backend_enabled +@slow +class MixedInt8T5Test(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.model_name = "google-t5/t5-small" + cls.dense_act_model_name = "google/flan-t5-small" # flan-t5 uses dense-act instead of dense-relu-dense + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.input_text = "Translate in German: Hello, my dog is cute" + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + gc.collect() + backend_empty_cache(torch_device) + + def test_inference_without_keep_in_fp32(self): + r""" + Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + from transformers import T5ForConditionalGeneration + + modules = T5ForConditionalGeneration._keep_in_fp32_modules + T5ForConditionalGeneration._keep_in_fp32_modules = None + + # test with `google-t5/t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_8bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + T5ForConditionalGeneration._keep_in_fp32_modules = modules + + def test_inference_with_keep_in_fp32(self): + r""" + Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + + from transformers import T5ForConditionalGeneration + + # test with `google-t5/t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + + # there was a bug with decoders - this test checks that it is fixed + self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear8bitLt)) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_8bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + + def test_inference_with_keep_in_fp32_serialized(self): + r""" + Test whether it is possible to mix both `int8` and `fp32` weights when using `keep_in_fp32_modules` correctly on + a serialized model. + `flan-t5-small` uses `T5DenseGatedActDense` whereas `google-t5/t5-small` uses `T5DenseReluDense`. We need to test + both cases. + """ + + from transformers import T5ForConditionalGeneration + + # test with `google-t5/t5-small` + model = T5ForConditionalGeneration.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + model = T5ForConditionalGeneration.from_pretrained(tmp_dir) + + # there was a bug with decoders - this test checks that it is fixed + self.assertTrue(isinstance(model.decoder.block[0].layer[0].SelfAttention.q, bnb.nn.Linear8bitLt)) + + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + + # test with `flan-t5-small` + model = T5ForConditionalGeneration.from_pretrained( + self.dense_act_model_name, load_in_8bit=True, device_map="auto" + ) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt").to(model.device) + _ = model.generate(**encoded_input) + + +class MixedInt8ModelClassesTest(BaseMixedInt8Test): + def setUp(self): + super().setUp() + # model_name + self.model_name = "bigscience/bloom-560m" + self.seq_to_seq_name = "google-t5/t5-small" + + # Different types of model + + self.base_model = AutoModel.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + # Sequence classification model + self.sequence_model = AutoModelForSequenceClassification.from_pretrained( + self.model_name, load_in_8bit=True, device_map="auto" + ) + # CausalLM model + self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True, device_map="auto") + # Seq2seq model + self.seq_to_seq_model = AutoModelForSeq2SeqLM.from_pretrained( + self.seq_to_seq_name, load_in_8bit=True, device_map="auto" + ) + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + del self.base_model + del self.sequence_model + del self.model_8bit + del self.seq_to_seq_model + + gc.collect() + backend_empty_cache(torch_device) + + def test_correct_head_class(self): + r""" + A simple test to check if the last modules for some classes (AutoModelForCausalLM or SequenceClassification) + are kept in their native class. + """ + from bitsandbytes.nn import Int8Params + + # last param of a base model should be a linear8bit module + self.assertTrue(self.base_model.h[-1].mlp.dense_4h_to_h.weight.__class__ == Int8Params) + + # Other heads should be nn.Parameter + self.assertTrue(self.model_8bit.lm_head.weight.__class__ == torch.nn.Parameter) + self.assertTrue(self.sequence_model.score.weight.__class__ == torch.nn.Parameter) + self.assertTrue(self.seq_to_seq_model.lm_head.weight.__class__ == torch.nn.Parameter) + + +@apply_skip_if_not_implemented +class MixedInt8TestPipeline(BaseMixedInt8Test): + def setUp(self): + super().setUp() + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the GPU memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + if hasattr(self, "pipe"): + del self.pipe + + gc.collect() + backend_empty_cache(torch_device) + + def test_pipeline(self): + r""" + The aim of this test is to verify that the mixed int8 is compatible with `pipeline` from transformers. Since + we used pipeline for inference speed benchmarking we want to make sure that this feature does not break anything + on pipeline. + """ + # self._clear_cuda_cache() + self.pipe = pipeline( + "text-generation", + model=self.model_name, + model_kwargs={"device_map": "auto", "load_in_8bit": True}, + max_new_tokens=self.MAX_NEW_TOKENS, + ) + + # Avoid sampling different outputs + set_seed(42) + # Real second forward pass + pipeline_output = self.pipe(self.input_text) + self.assertIn(pipeline_output[0]["generated_text"], self.EXPECTED_OUTPUTS) + + +@require_torch_multi_accelerator +@apply_skip_if_not_implemented +class MixedInt8TestMultiGpu(BaseMixedInt8Test): + def setUp(self): + super().setUp() + + def test_multi_gpu_loading(self): + r""" + This tests that the model has been loaded and can be used correctly on a multi-GPU setup. + Let's just try to load a model on 2 GPUs and see if it works. The model we test has ~2GB of total, 3GB should suffice + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": 0, + "lm_head": 0, + "transformer.h.0": 0, + "transformer.h.1": 0, + "transformer.h.2": 0, + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 0, + "transformer.h.10": 1, + "transformer.h.11": 1, + "transformer.h.12": 1, + "transformer.h.13": 1, + "transformer.h.14": 1, + "transformer.h.15": 1, + "transformer.h.16": 1, + "transformer.h.17": 0, + "transformer.h.18": 0, + "transformer.h.19": 0, + "transformer.h.20": 0, + "transformer.h.21": 0, + "transformer.h.22": 0, + "transformer.h.23": 1, + "transformer.ln_f": 0, + } + + model_parallel = AutoModelForCausalLM.from_pretrained( + self.model_name, load_in_8bit=True, device_map=device_map + ) + + # Check correct device map + self.assertEqual(set(model_parallel.hf_device_map.values()), {0, 1}) + + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Second real batch + output_parallel = model_parallel.generate( + input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10 + ) + self.assertIn(self.tokenizer.decode(output_parallel[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + +@require_torch_multi_accelerator +@apply_skip_if_not_implemented +class MixedInt8TestCpuGpu(BaseMixedInt8Test): + def setUp(self): + super().setUp() + + def check_inference_correctness(self, model): + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_parallel = model.generate(input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10) + + # Get the generation + output_text = self.tokenizer.decode(output_parallel[0], skip_special_tokens=True) + self.assertIn(output_text, self.EXPECTED_OUTPUTS) + + def test_cpu_accelerator_loading_random_device_map(self): + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a random `device_map`. + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": 0, + "lm_head": 0, + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": 0, + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 1, + "transformer.h.10": 0, + "transformer.h.11": 1, + "transformer.h.12": 0, + "transformer.h.13": 0, + "transformer.h.14": 1, + "transformer.h.15": 0, + "transformer.h.16": 0, + "transformer.h.17": 1, + "transformer.h.18": 1, + "transformer.h.19": 0, + "transformer.h.20": 1, + "transformer.h.21": 1, + "transformer.h.22": 0, + "transformer.h.23": 0, + "transformer.ln_f": 1, + } + + bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True, load_in_8bit=True) + + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=device_map, + quantization_config=bnb_config, + ) + + # Check that the model has been correctly set on device 0, 1, and `cpu`. + self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu"}) + + self.check_inference_correctness(model_8bit) + + def test_cpu_accelerator_loading_custom_device_map(self): + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + This time the device map is more organized than the test above and uses the abstraction + `transformer.h` to encapsulate all the decoder layers. + """ + device_map = { + "transformer.word_embeddings": "cpu", + "transformer.word_embeddings_layernorm": "cpu", + "lm_head": "cpu", + "transformer.h": 0, + "transformer.ln_f": 1, + } + bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True, load_in_8bit=True) + + # Load model + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=device_map, + quantization_config=bnb_config, + ) + + # Check that the model has been correctly set on device 0, 1, and `cpu`. + self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu"}) + + self.check_inference_correctness(model_8bit) + + def test_cpu_accelerator_disk_loading_custom_device_map(self): + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + This time we also add `disk` on the device_map. + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": "cpu", + "lm_head": 0, + "transformer.h": 1, + "transformer.ln_f": "disk", + } + bnb_config = BitsAndBytesConfig(llm_int8_enable_fp32_cpu_offload=True, load_in_8bit=True) + with tempfile.TemporaryDirectory() as tmpdirname: + # Load model + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=device_map, + quantization_config=bnb_config, + offload_folder=tmpdirname, + ) + + # Check that the model has been correctly set on device 0, 1, and `cpu`. + self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu", "disk"}) + + self.check_inference_correctness(model_8bit) + + def test_cpu_accelerator_disk_loading_custom_device_map_kwargs(self): + r""" + A test to check is dispatching a model on cpu & gpu works correctly using a custom `device_map`. + This time we also add `disk` on the device_map - using the kwargs directly instead of the quantization config + """ + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": "cpu", + "lm_head": 0, + "transformer.h": 1, + "transformer.ln_f": "disk", + } + with tempfile.TemporaryDirectory() as tmpdirname: + # Load model + model_8bit = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=device_map, + load_in_8bit=True, + llm_int8_enable_fp32_cpu_offload=True, + offload_folder=tmpdirname, + ) + + # Check that the model has been correctly set on device 0, 1, and `cpu`. + self.assertEqual(set(model_8bit.hf_device_map.values()), {0, 1, "cpu", "disk"}) + + self.check_inference_correctness(model_8bit) + + +@apply_skip_if_not_implemented +class MixedInt8TestTraining(BaseMixedInt8Test): + def setUp(self): + self.model_name = "facebook/opt-350m" + super().setUp() + + def test_training(self): + if version.parse(importlib.metadata.version("bitsandbytes")) < version.parse("0.37.0"): + self.skipTest(reason="This test requires bitsandbytes>=0.37.0") + + # Step 1: freeze all parameters + model = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True) + model.train() + + if torch_device in ["cuda", "xpu"]: + self.assertEqual( + set(model.hf_device_map.values()), {backend_torch_accelerator_module(torch_device).current_device()} + ) + else: + self.assertTrue(all(param.device.type == "cpu" for param in model.parameters())) + + for param in model.parameters(): + param.requires_grad = False # freeze the model - train adapters later + # cast all non INT8 parameters to fp32 + if param.dtype in (torch.float16, torch.bfloat16) and param.__class__.__name__ != "Params4bit": + param.data = param.data.to(torch.float32) + + # Step 2: add adapters + for _, module in model.named_modules(): + if isinstance(module, OPTAttention): + module.q_proj = LoRALayer(module.q_proj, rank=16, dtype=model.dtype) + module.k_proj = LoRALayer(module.k_proj, rank=16, dtype=model.dtype) + module.v_proj = LoRALayer(module.v_proj, rank=16, dtype=model.dtype) + + # Step 3: dummy batch + batch = self.tokenizer("Test batch ", return_tensors="pt").to(torch_device) + + # Step 4: Check if the gradient is not None + with torch.autocast(torch_device): + out = model.forward(**batch) + out.logits.norm().backward() + + for module in model.modules(): + if isinstance(module, LoRALayer): + self.assertTrue(module.adapter[1].weight.grad is not None) + self.assertTrue(module.adapter[1].weight.grad.norm().item() > 0) + elif isinstance(module, nn.Embedding): + self.assertTrue(module.weight.grad is None) + + +@apply_skip_if_not_implemented +class MixedInt8GPT2Test(MixedInt8Test): + model_name = "openai-community/gpt2-xl" + EXPECTED_RELATIVE_DIFFERENCE = 1.8720077507258357 + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Hello my name is John Doe, and I'm a big fan of") + EXPECTED_OUTPUTS.add("Hello my name is John Doe, and I'm a fan of the") + # Expected values on a A10 + EXPECTED_OUTPUTS.add("Hello my name is John Doe, and I am a member of the") + # Expected values on Intel CPU + EXPECTED_OUTPUTS.add("Hello my name is John Doe. I am a man. I am") + EXPECTED_OUTPUTS.add("Hello my name is John, and I'm a writer. I'm") + + def test_int8_from_pretrained(self): + r""" + Test whether loading a 8bit model from the Hub works as expected + """ + from bitsandbytes.nn import Int8Params + + model_id = "ybelkada/gpt2-xl-8bit" + + model = AutoModelForCausalLM.from_pretrained(model_id) + + linear = get_some_linear_layer(model) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + +class MixedInt8LlamaTest(MixedInt8Test): + model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" + EXPECTED_RELATIVE_DIFFERENCE = 1.7869331026479096 + EXPECTED_OUTPUTS = set() + + # Expected on Intel XPU + EXPECTED_OUTPUTS.add("Hello my name is John Smith and I am a software engineer. I") + + # Expected on NVIDIA T4 + EXPECTED_OUTPUTS.add("Hello my name is John and I am a software engineer. I have") + + def test_int8_from_pretrained(self): + r""" + Test whether loading a 8bit model from the Hub works as expected + """ + from bitsandbytes.nn import Int8Params + + model_id = "Jiqing/TinyLlama-1.1B-Chat-v1.0-bnb-8bit" + + model = AutoModelForCausalLM.from_pretrained(model_id) + + linear = get_some_linear_layer(model) + self.assertTrue(linear.weight.__class__ == Int8Params) + self.assertTrue(hasattr(linear.weight, "SCB")) + + # generate + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(torch_device), max_new_tokens=10) + + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + +@require_bitsandbytes +@require_accelerate +@require_torch +@require_torch_gpu_if_bnb_not_multi_backend_enabled +@slow +@apply_skip_if_not_implemented +class Bnb8bitCompile(unittest.TestCase): + model_name = "hf-internal-testing/tiny-random-LlamaForCausalLM" + input_text = "Hello my name is" + + def setUp(self): + # Models and tokenizer + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + self.model_8bit = AutoModelForCausalLM.from_pretrained(self.model_name, load_in_8bit=True) + + @pytest.mark.torch_compile_test + def test_generate_compile(self): + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # if nothing is set, compile will be disabled for bnb + self.model_8bit.generate( + input_ids=encoded_input["input_ids"].to(self.model_8bit.device), + max_new_tokens=10, + cache_implementation="static", + ) + + with self.assertRaises(Exception): + object.__setattr__(self.model_8bit.hf_quantizer, "is_compileable", True) + self.model_8bit.generate( + input_ids=encoded_input["input_ids"].to(self.model_8bit.device), + max_new_tokens=10, + cache_implementation="static", + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_models.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_models.py new file mode 100644 index 0000000000000000000000000000000000000000..f956f0c08c1e3de74cc80d43092b360a9259f1ee --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_models.py @@ -0,0 +1,232 @@ +import gc +import unittest +import warnings + +from transformers import AutoModelForCausalLM, AutoTokenizer +from transformers.testing_utils import backend_empty_cache, require_compressed_tensors, require_torch, torch_device +from transformers.utils import is_torch_available +from transformers.utils.quantization_config import CompressedTensorsConfig + + +if is_torch_available(): + import torch + + +@require_compressed_tensors +@require_torch +class StackCompressedModelTest(unittest.TestCase): + # Define stubs as class attributes + compressed_uncompressed_model_stubs = [ + ( + "nm-testing/llama2.c-stories42M-gsm8k-quantized-only-compressed", + "nm-testing/llama2.c-stories42M-gsm8k-quantized-only-uncompressed", + ), + ( + "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-compressed", + "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-uncompressed", + ), + ( + "nm-testing/llama2.c-stories42M-gsm8k-stacked-compressed", + "nm-testing/llama2.c-stories42M-gsm8k-stacked-uncompressed", + ), + ] + # Flatten the list for tests that require a single list of stubs. + model_stubs = [stub for pair in compressed_uncompressed_model_stubs for stub in pair] + + # For the outputs matching test, use the sparse-only pair. + sparse_compressed_model = "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-compressed" + sparse_uncompressed_model = "nm-testing/llama2.c-stories42M-gsm8k-sparse-only-uncompressed" + + prompt = "Paris is the capital of which country?" + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_compressed_uncompressed_model_shapes(self): + """ + Verify that the weights of an uncompressed model and its decompressed compressed counterpart match. + Note: Weights for sparsely compressed models may differ due to packing. + """ + + def _has_nested_attr(obj, attr_path): + attrs = attr_path.split(".") + for attr in attrs: + if not hasattr(obj, attr): + return None + obj = getattr(obj, attr) + return obj + + from compressed_tensors.quantization.utils import iter_named_leaf_modules + + for compressed_model, uncompressed_model in self.compressed_uncompressed_model_stubs: + with self.subTest(compressed_model=compressed_model, uncompressed_model=uncompressed_model): + uncompressed = AutoModelForCausalLM.from_pretrained( + uncompressed_model, + device_map="auto", + torch_dtype="auto", + quantization_config=CompressedTensorsConfig(run_compressed=False), + ) + compressed_decompressed = AutoModelForCausalLM.from_pretrained( + compressed_model, + device_map="auto", + torch_dtype="auto", + quantization_config=CompressedTensorsConfig(run_compressed=False), + ) + + for name, submodule in iter_named_leaf_modules(uncompressed): + comp_decomp_obj = _has_nested_attr(compressed_decompressed, name) + if comp_decomp_obj is not None and hasattr(submodule, "weight"): + if "sparse-only" in uncompressed_model: + self.assertTrue( + torch.equal(submodule.weight, comp_decomp_obj.weight), + f"Weight mismatch for module '{name}' in sparse-only model.", + ) + else: + self.assertTrue( + torch.allclose(submodule.weight, comp_decomp_obj.weight, atol=0.2), + f"Weight mismatch for module '{name}' in quantized-only or stacked model.", + ) + + def test_outputs_match(self): + """ + Ensure that the generated outputs match between the uncompressed model + and its decompressed compressed counterpart. + """ + tokenizer = AutoTokenizer.from_pretrained(self.sparse_uncompressed_model) + input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids + + uncompressed = AutoModelForCausalLM.from_pretrained( + self.sparse_uncompressed_model, + device_map="auto", + torch_dtype="auto", + quantization_config=CompressedTensorsConfig(run_compressed=False), + ) + + output_uncompressed = uncompressed.generate(input_ids.to(uncompressed.device), max_new_tokens=100) + + decompressed = AutoModelForCausalLM.from_pretrained( + self.sparse_compressed_model, + device_map="auto", + torch_dtype="auto", + quantization_config=CompressedTensorsConfig(run_compressed=False), + ) + output_decompressed = decompressed.generate(input_ids.to(decompressed.device), max_new_tokens=100) + + self.assertEqual( + tokenizer.decode(output_uncompressed[0]), + tokenizer.decode(output_decompressed[0]), + "Generated outputs do not match between compressed and uncompressed models.", + ) + + def test_no_warnings_for_all_models(self): + """ + Confirm that loading any model using compressed tensors does not trigger + warnings about missing or unexpected keys. + """ + for model_stub in self.model_stubs: + with self.subTest(model_stub=model_stub): + with warnings.catch_warnings(record=True) as caught_warnings: + warnings.simplefilter("always") + AutoModelForCausalLM.from_pretrained( + model_stub, + device_map="auto", + torch_dtype="auto", + quantization_config=CompressedTensorsConfig(run_compressed=False), + ) + for warning in caught_warnings: + self.assertNotIn( + "missing keys", + str(warning.message).lower(), + f"'missing keys' found in warnings for model {model_stub}", + ) + self.assertNotIn( + "unexpected keys", + str(warning.message).lower(), + f"'unexpected keys' found in warnings for model {model_stub}", + ) + + +@require_compressed_tensors +@require_torch +class RunCompressedTest(unittest.TestCase): + tinyllama_w4a16 = "nm-testing/tinyllama-w4a16-compressed-hf-quantizer" + tinyllama_w8a8 = "nm-testing/tinyllama-w8a8-compressed-hf-quantizer" + + prompt = "Paris is the capital of which country?" + + stubs = [tinyllama_w4a16, tinyllama_w8a8] + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_default_run_compressed__True(self): + from compressed_tensors.linear.compressed_linear import CompressedLinear + from compressed_tensors.quantization.utils import iter_named_leaf_modules + + for stub in self.stubs: + model = AutoModelForCausalLM.from_pretrained( + stub, + ) + compressed_linear_counts = 0 + + for _, submodule in iter_named_leaf_modules( + model, + ): + if isinstance(submodule, CompressedLinear): + compressed_linear_counts += 1 + + # some linear models are not compressed - ex. lm_head + assert compressed_linear_counts > 0 + + def test_default_run_compressed__False(self): + from compressed_tensors.linear.compressed_linear import CompressedLinear + from compressed_tensors.quantization.utils import iter_named_leaf_modules + + from transformers.utils.quantization_config import CompressedTensorsConfig + + quantization_config = CompressedTensorsConfig(run_compressed=False) + + for stub in self.stubs: + model = AutoModelForCausalLM.from_pretrained( + stub, + quantization_config=quantization_config, + ) + compressed_linear_counts = 0 + + for _, submodule in iter_named_leaf_modules( + model, + ): + if isinstance(submodule, CompressedLinear): + compressed_linear_counts += 1 + + # No modules should be CompressedLinear + assert compressed_linear_counts == 0 + + def test_run_compressed_outputs_match(self): + """Check that run_compressed=True/False output are the same""" + + from transformers import AutoTokenizer + from transformers.utils.quantization_config import CompressedTensorsConfig + + quantization_config = CompressedTensorsConfig(run_compressed=False) + + for stub in self.stubs: + tokenizer = AutoTokenizer.from_pretrained(stub) + input_ids = tokenizer(self.prompt, return_tensors="pt").input_ids + + model_run_compressed__True = AutoModelForCausalLM.from_pretrained( + stub, + ) + output_rc_true = model_run_compressed__True.generate(input_ids, max_new_tokens=100) + + model_run_compressed__False = AutoModelForCausalLM.from_pretrained( + stub, + quantization_config=quantization_config, + ) + output_rc_false = model_run_compressed__False.generate(input_ids, max_new_tokens=100) + + assert tokenizer.decode(output_rc_true[0]) == tokenizer.decode(output_rc_false[0]) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_tensors.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_tensors.py new file mode 100644 index 0000000000000000000000000000000000000000..d44e560fff0dccf48defa2cec4108f97199b0949 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/compressed_tensors_integration/test_compressed_tensors.py @@ -0,0 +1,87 @@ +import gc +import unittest + +from transformers import AutoModelForCausalLM, AutoTokenizer, CompressedTensorsConfig +from transformers.testing_utils import backend_empty_cache, require_compressed_tensors, require_torch, torch_device +from transformers.utils import is_torch_available + + +if is_torch_available(): + import torch + + +@require_compressed_tensors +@require_torch +class CompressedTensorsTest(unittest.TestCase): + tinyllama_w8a16 = "nm-testing/tinyllama-w8a16-dense-hf-quantizer" + tinyllama_w4a16 = "nm-testing/tinyllama-w4a16-compressed-hf-quantizer" + tinyllama_w8a8 = "nm-testing/tinyllama-w8a8-compressed-hf-quantizer" + llama3_8b_fp8 = "nm-testing/Meta-Llama-3-8B-Instruct-fp8-hf_compat" + + prompt = "Paris is the capital of which country?" + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_config_args(self): + with self.assertRaises(ValueError): + # passing quant scheme directly is not allowed + CompressedTensorsConfig(config_groups={"weights": {"num_bits": 8}}) + CompressedTensorsConfig( + config_groups={"FP8": ["Linear"]}, + ignore=["lm_head"], + quantization_status="frozen", + sparsity_config={"format": "dense"}, + ) + + def test_config_to_from_dict(self): + config = CompressedTensorsConfig(config_groups={"FP8": ["Linear"]}, sparsity_config={"format": "dense"}) + config_dict = config.to_dict() + config_from_dict = CompressedTensorsConfig.from_dict(config_dict) + + from compressed_tensors import QuantizationConfig, SparsityCompressionConfig + + self.assertIsInstance(config_from_dict.quantization_config, QuantizationConfig) + self.assertIsInstance(config_from_dict.sparsity_config, SparsityCompressionConfig) + + def test_tinyllama_w8a8(self): + expected_out = " Paris is the capital of which country?\n\n 1. Paris is the capital of which country?\n\n 1. Paris is the capital of which country?\n\n 1. Paris is the capital of which country?\n\n" + self._test_quantized_model(self.tinyllama_w8a8, expected_out) + + def test_tinyllama_w4a16(self): + expected_out = " Paris is the capital of which country?\nAnswer: Paris is the capital of France.\nQuestion: Which country is the capital of which city?\nAnswer: The capital of the city of New York is New York.\nQuestion: Which" + self._test_quantized_model(self.tinyllama_w4a16, expected_out) + + def test_tinyllama_w8a16(self): + expected_out = " Paris is the capital of which country?\nA. France\nB. Germany\nC. Spain\nD. Italy\nE. Switzerland\nQ10. Which of the following is not a country in the European Union?\nA." + self._test_quantized_model(self.tinyllama_w8a16, expected_out) + + def test_llama_8b_fp8(self): + expected_out = "<|begin_of_text|>Paris is the capital of which country? France\nWhat is the name of the famous museum in Paris that is home to the Mona Lisa? The Louvre\nWhat is the name of the famous bridge in Paris that is often associated with the city" + self._test_quantized_model(self.llama3_8b_fp8, expected_out) + + def _test_quantized_model(self, model_name: str, expected_output: str): + """Carry out generation""" + quantized_model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto") + tokenizer = AutoTokenizer.from_pretrained(model_name) + device = quantized_model.device + self.assertIsNotNone( + quantized_model.config.quantization_config, + "quantization_config should not be None", + ) + self.assertTrue( + any( + key + for key, tensor in quantized_model.state_dict().items() + if "scale" in key and not torch.all(tensor == 1.0) + ), + "quantized model should load a non-trivial scale into the state dict", + ) + inputs = tokenizer(self.prompt, return_tensors="pt").to(device) + generated_ids = quantized_model.generate(**inputs, max_length=50, do_sample=False) + outputs = tokenizer.batch_decode(generated_ids) + + self.assertIsNotNone(outputs) + self.assertEqual(outputs[0], expected_output) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/test_eetq.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/test_eetq.py new file mode 100644 index 0000000000000000000000000000000000000000..1bd1fbe45c1e7f6c8bc985e71061f58a1632c0d6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/eetq_integration/test_eetq.py @@ -0,0 +1,171 @@ +# 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. + +import gc +import tempfile +import unittest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, EetqConfig, OPTForCausalLM +from transformers.testing_utils import ( + backend_empty_cache, + require_accelerate, + require_eetq, + require_torch_gpu, + require_torch_multi_gpu, + slow, + torch_device, +) +from transformers.utils import is_accelerate_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_accelerate_available(): + from accelerate import init_empty_weights + + +@require_torch_gpu +class EetqConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object + """ + quantization_config = EetqConfig() + config_to_dict = quantization_config.to_dict() + + for key in config_to_dict: + self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) + + def test_from_dict(self): + """ + Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict + """ + dict = {"modules_to_not_convert": ["lm_head.weight"], "quant_method": "eetq", "weights": "int8"} + quantization_config = EetqConfig.from_dict(dict) + + self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) + self.assertEqual(dict["quant_method"], quantization_config.quant_method) + self.assertEqual(dict["weights"], quantization_config.weights) + + +@slow +@require_torch_gpu +@require_eetq +@require_accelerate +class EetqTest(unittest.TestCase): + model_name = "facebook/opt-350m" + + input_text = "What are we having for dinner?" + max_new_tokens = 9 + + EXPECTED_OUTPUT = "What are we having for dinner?\nI'm having a steak and a salad" + + device_map = "cuda" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + quantization_config = EetqConfig(weights="int8") + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, device_map=cls.device_map, quantization_config=quantization_config + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_quantized_model_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly + """ + from eetq import EetqLinear + + from transformers.integrations import replace_with_eetq_linear + + model_id = "facebook/opt-350m" + config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") + quantization_config = EetqConfig(weights="int8") + + with init_empty_weights(): + model = OPTForCausalLM(config) + + nb_linears = 0 + for module in model.modules(): + if isinstance(module, torch.nn.Linear): + nb_linears += 1 + + model = replace_with_eetq_linear(model, quantization_config=quantization_config) + nb_eetq_linear = 0 + for module in model.modules(): + if isinstance(module, EetqLinear): + nb_eetq_linear += 1 + + self.assertEqual(nb_linears - 1, nb_eetq_linear) + + # Try with `modules_to_not_convert` + with init_empty_weights(): + model = OPTForCausalLM(config) + quantization_config = EetqConfig(modules_to_not_convert=["fc1"]) + model = replace_with_eetq_linear(model, quantization_config=quantization_config) + nb_eetq_linear = 0 + for module in model.modules(): + if isinstance(module, EetqLinear): + nb_eetq_linear += 1 + # 25 corresponds to the lm_head along with 24 fc1 layers. + self.assertEqual(nb_linears - 25, nb_eetq_linear) + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_quantized_model_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly with multiple GPUs + set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + quantization_config = EetqConfig() + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, device_map="auto", quantization_config=quantization_config + ) + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..e31bd9adf51a456a853f1940d4ab933022fe4e63 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py @@ -0,0 +1,301 @@ +# 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. + +import gc +import tempfile +import unittest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FbgemmFp8Config, OPTForCausalLM +from transformers.testing_utils import ( + backend_empty_cache, + require_accelerate, + require_fbgemm_gpu, + require_read_token, + require_torch_gpu, + require_torch_multi_gpu, + slow, + torch_device, +) +from transformers.utils import is_accelerate_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_accelerate_available(): + from accelerate import init_empty_weights + + +@require_torch_gpu +class FbgemmFp8ConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object + """ + quantization_config = FbgemmFp8Config() + config_to_dict = quantization_config.to_dict() + + for key in config_to_dict: + self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) + + def test_from_dict(self): + """ + Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict + """ + dict = {"modules_to_not_convert": ["lm_head.weight"], "quant_method": "fbgemm_fp8"} + quantization_config = FbgemmFp8Config.from_dict(dict) + + self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) + self.assertEqual(dict["quant_method"], quantization_config.quant_method) + + +@slow +@require_torch_gpu +@require_fbgemm_gpu +@require_accelerate +@require_read_token +class FbgemmFp8Test(unittest.TestCase): + model_name = "meta-llama/Meta-Llama-3-8B" + + input_text = "What are we having for dinner?" + max_new_tokens = 9 + + EXPECTED_OUTPUT = "What are we having for dinner?\nI'm having a steak and a salad" + + device_map = "cuda" + + offload_device_map = { + "model.embed_tokens": 0, + "model.layers.0": 0, + "model.layers.1": 0, + "model.layers.2": 0, + "model.layers.3": 0, + "model.layers.4": 0, + "model.layers.5": 0, + "model.layers.6": 0, + "model.layers.7": 0, + "model.layers.8": 0, + "model.layers.9": 0, + "model.layers.10": 0, + "model.layers.11": 0, + "model.layers.12": 0, + "model.layers.13": 0, + "model.layers.14": 0, + "model.layers.15": 0, + "model.layers.16": "cpu", + "model.layers.17": "cpu", + "model.layers.18": "cpu", + "model.layers.19": "cpu", + "model.layers.20": "disk", + "model.layers.21": "disk", + "model.layers.22": "disk", + "model.layers.23": "disk", + "model.layers.24": "disk", + "model.layers.25": "disk", + "model.layers.26": "disk", + "model.layers.27": "disk", + "model.layers.28": "disk", + "model.layers.29": "disk", + "model.layers.30": "disk", + "model.layers.31": "disk", + "model.norm": "disk", + "lm_head": "disk", + } + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + quantization_config = FbgemmFp8Config() + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, device_map=cls.device_map, quantization_config=quantization_config + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_quantized_model_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly + """ + + from transformers.integrations import FbgemmFp8Linear, replace_with_fbgemm_fp8_linear + + model_id = "facebook/opt-350m" + config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") + quantization_config = FbgemmFp8Config() + + with init_empty_weights(): + model = OPTForCausalLM(config) + + nb_linears = 0 + for module in model.modules(): + if isinstance(module, torch.nn.Linear): + nb_linears += 1 + + model = replace_with_fbgemm_fp8_linear(model, quantization_config=quantization_config) + nb_fbgemm_linear = 0 + for module in model.modules(): + if isinstance(module, FbgemmFp8Linear): + nb_fbgemm_linear += 1 + + self.assertEqual(nb_linears - 1, nb_fbgemm_linear) + + with init_empty_weights(): + model = OPTForCausalLM(config) + quantization_config = FbgemmFp8Config(modules_to_not_convert=["fc1"]) + model = replace_with_fbgemm_fp8_linear(model, quantization_config=quantization_config) + nb_fbgemm_linear = 0 + for module in model.modules(): + if isinstance(module, FbgemmFp8Linear): + nb_fbgemm_linear += 1 + + self.assertEqual(nb_linears - 25, nb_fbgemm_linear) + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_change_loading_attributes(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + quantization_config = FbgemmFp8Config(activation_scale_ub=1000.0) + + model = AutoModelForCausalLM.from_pretrained( + tmpdirname, device_map=self.device_map, quantization_config=quantization_config + ) + + self.assertEqual(model.model.layers[1].mlp.down_proj.input_scale_ub.item(), 1000.0) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_quantized_model_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly with multiple GPUs + set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + quantization_config = FbgemmFp8Config() + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, device_map="auto", quantization_config=quantization_config + ) + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_quantized_model_offload(self): + """ + Simple test that checks if the quantized model returns an error when loading with cpu/disk offloaded + """ + quantization_config = FbgemmFp8Config() + + with self.assertRaisesRegex( + ValueError, "You are attempting to load an FP8 model with a device_map that contains a CPU or disk device." + ): + AutoModelForCausalLM.from_pretrained( + self.model_name, device_map=self.offload_device_map, quantization_config=quantization_config + ) + + def test_save_pretrained_offload(self): + """ + Simple test that checks if the saved quantized model is working properly cpu/disk offload + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + quantized_model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.offload_device_map) + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_save_pretrained_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto") + self.assertTrue(set(model.hf_device_map.values()) == {0, 1}) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + +@require_torch_gpu +@require_accelerate +@require_fbgemm_gpu +class FbgemmFp8LinearTest(unittest.TestCase): + def test_linear_preserves_shape(self): + """ + Test that FbgemmFp8Linear preserves shape when in_features == out_features. + """ + from transformers.integrations import FbgemmFp8Linear + + with init_empty_weights(include_buffers=True): + linear = FbgemmFp8Linear(1024, 1024, True) + x = torch.rand((17, 23, 1024)) + + x_ = linear(x) + self.assertEqual(x_.shape, x.shape) + + def test_linear_with_diff_feature_size_preserves_shape(self): + """ + Test that FbgemmFp8Linear generates the correct shape when in_features != out_features. + """ + from transformers.integrations import FbgemmFp8Linear + + with init_empty_weights(include_buffers=True): + linear = FbgemmFp8Linear(1024, 2048, True) + x = torch.rand((17, 23, 1024)) + + x_ = linear(x) + self.assertEqual(x_.shape, (17, 23, 2048)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/finegrained_fp8/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/finegrained_fp8/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/finegrained_fp8/test_fp8.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/finegrained_fp8/test_fp8.py new file mode 100644 index 0000000000000000000000000000000000000000..5622ab252fed8ec7c52ddda0a28e41d7fa35f635 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/finegrained_fp8/test_fp8.py @@ -0,0 +1,287 @@ +# Copyright 2025 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. + +import gc +import tempfile +import unittest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, FineGrainedFP8Config, OPTForCausalLM +from transformers.testing_utils import ( + backend_empty_cache, + get_device_properties, + require_accelerate, + require_read_token, + require_torch_accelerator, + require_torch_multi_accelerator, + slow, + torch_device, +) +from transformers.utils import is_accelerate_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_accelerate_available(): + from accelerate import init_empty_weights + + +@require_torch_accelerator +class FineGrainedFP8ConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object + """ + quantization_config = FineGrainedFP8Config() + config_to_dict = quantization_config.to_dict() + + for key in config_to_dict: + self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) + + def test_from_dict(self): + """ + Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict + """ + dict = {"modules_to_not_convert": ["lm_head.weight"], "quant_method": "fp8"} + quantization_config = FineGrainedFP8Config.from_dict(dict) + + self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) + self.assertEqual(dict["quant_method"], quantization_config.quant_method) + + +@slow +@require_accelerate +@require_read_token +@require_torch_accelerator +class FP8QuantizerTest(unittest.TestCase): + model_name = "meta-llama/Llama-3.2-1B" + input_text = "Once upon a time" + max_new_tokens = 10 + EXPECTED_OUTPUT = "Once upon a time, there was a man who was very rich." + device_map = torch_device + offload_device_map = { + "model.embed_tokens": 0, + "model.layers.0": 0, + "model.layers.1": 0, + "model.layers.2": 0, + "model.layers.3": 0, + "model.layers.4": 0, + "model.layers.5": 0, + "model.layers.6": 0, + "model.layers.7": "cpu", + "model.layers.8": "cpu", + "model.layers.9": "cpu", + "model.layers.10": "cpu", + "model.layers.11": "cpu", + "model.layers.12": "cpu", + "model.layers.13": "cpu", + "model.layers.14": "cpu", + "model.layers.15": "cpu", + "model.rotary_emb": "disk", + "model.norm": "disk", + "lm_head": 0, + } + + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.quantization_config = FineGrainedFP8Config() + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, device_map=cls.device_map, quantization_config=cls.quantization_config + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_quantized_model_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly + """ + + from transformers.integrations import FP8Linear, replace_with_fp8_linear + + model_id = "facebook/opt-350m" + config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") + quantization_config = FineGrainedFP8Config() + + with init_empty_weights(): + model = OPTForCausalLM(config) + + nb_linears = 0 + for module in model.modules(): + if isinstance(module, torch.nn.Linear): + nb_linears += 1 + + model = replace_with_fp8_linear(model, quantization_config=quantization_config) + nb_fp8_linear = 0 + for module in model.modules(): + if isinstance(module, FP8Linear): + nb_fp8_linear += 1 + + self.assertEqual(nb_linears - 1, nb_fp8_linear) + + with init_empty_weights(): + model = OPTForCausalLM(config) + quantization_config = FineGrainedFP8Config(modules_to_not_convert=["fc1"]) + model = replace_with_fp8_linear(model, quantization_config=quantization_config) + nb_fp8_linear = 0 + for module in model.modules(): + if isinstance(module, FP8Linear): + nb_fp8_linear += 1 + + self.assertEqual(nb_linears - 25, nb_fp8_linear) + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) + output_tokens = self.tokenizer.decode(output[0], skip_special_tokens=True) + self.assertEqual(output_tokens, self.EXPECTED_OUTPUT) + + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_weight_and_weight_scale_inv(self): + """ + Simple test that checks if the weight and weight_scale_inv are working properly + """ + weight = self.quantized_model.model.layers[0].self_attn.q_proj.weight + weight_scale_inv = self.quantized_model.model.layers[0].self_attn.q_proj.weight_scale_inv + self.assertEqual(weight.dtype, torch.float8_e4m3fn) + self.assertEqual(weight_scale_inv.dtype, torch.float32) + self.assertEqual(weight.shape, (weight_scale_inv.shape[0] * 128, weight_scale_inv.shape[1] * 128)) + + def test_block_size(self): + """ + Simple test that checks if the block size is working properly + """ + self.assertEqual(self.quantized_model.config.quantization_config.weight_block_size, (128, 128)) + quantization_config = FineGrainedFP8Config(weight_block_size=(32, 32)) + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, device_map=self.device_map, quantization_config=quantization_config + ) + self.assertEqual(quantized_model.config.quantization_config.weight_block_size, (32, 32)) + + @require_torch_multi_accelerator + def test_quantized_model_multi_accelerator(self): + """ + Simple test that checks if the quantized model is working properly with multiple accelerators + set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs; or set ZE_AFFINITY_MASK=0,1 if you + have more than 2 XPUs. + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map) + quantization_config = FineGrainedFP8Config() + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, device_map="auto", quantization_config=quantization_config + ) + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_accelerator + def test_save_pretrained_multi_accelerators(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto") + self.assertTrue(set(model.hf_device_map.values()) == {0, 1}) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_quantized_model_offload(self): + """ + Simple test that checks if the quantized model returns an error when loading with cpu/disk offloaded + """ + with self.assertRaisesRegex( + ValueError, "You are attempting to load an FP8 model with a device_map that contains a cpu/disk device." + ): + AutoModelForCausalLM.from_pretrained( + self.model_name, device_map=self.offload_device_map, quantization_config=self.quantization_config + ) + + def test_save_pretrained_offload(self): + """ + Simple test that checks if the saved quantized model is working properly cpu/disk offload + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device_map) + + quantized_model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.offload_device_map) + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + +@require_torch_accelerator +class FP8LinearTest(unittest.TestCase): + device = torch_device + + @unittest.skipIf( + get_device_properties()[0] == "cuda" and get_device_properties()[1] < 9, + "Skipping FP8LinearTest because it is not supported on GPU with capability < 9.0", + ) + def test_linear_preserves_shape(self): + """ + Test that FP8Linear preserves shape when in_features == out_features. + """ + from transformers.integrations import FP8Linear + + linear = FP8Linear(256, 256, block_size=(128, 128), device=self.device) + x = torch.rand((1, 5, 256)).to(self.device) + + x_ = linear(x) + self.assertEqual(x_.shape, x.shape) + + @unittest.skipIf( + get_device_properties()[0] == "cuda" and get_device_properties()[1] < 9, + "Skipping FP8LinearTest because it is not supported on GPU with capability < 9.0", + ) + def test_linear_with_diff_feature_size_preserves_shape(self): + """ + Test that FP8Linear generates the correct shape when in_features != out_features. + """ + from transformers.integrations import FP8Linear + + linear = FP8Linear(128, 256, block_size=(128, 128), device=self.device) + x = torch.rand((1, 5, 128)).to(self.device) + + x_ = linear(x) + self.assertEqual(x_.shape, (1, 5, 256)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/test_fp_quant.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/test_fp_quant.py new file mode 100644 index 0000000000000000000000000000000000000000..2bb60f5a2dc3576b937012288e796cde4d1b60de --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/fp_quant_integration/test_fp_quant.py @@ -0,0 +1,227 @@ +# Copyright 2025 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. + +import gc +import tempfile +import unittest + +from transformers import AutoModelForCausalLM, AutoTokenizer, FPQuantConfig +from transformers.testing_utils import ( + backend_empty_cache, + require_accelerate, + require_fp_quant, + require_qutlass, + require_torch_gpu, + require_torch_multi_gpu, + slow, + torch_device, +) + + +@require_torch_gpu +class FPQuantConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object + """ + quantization_config = FPQuantConfig() + config_to_dict = quantization_config.to_dict() + + for key in config_to_dict: + self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) + + def test_from_dict(self): + """ + Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict + """ + dict = {"modules_to_not_convert": ["embed_tokens", "lm_head"], "quant_method": "fp_quant"} + quantization_config = FPQuantConfig.from_dict(dict) + + self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) + self.assertEqual(dict["quant_method"], quantization_config.quant_method) + + +@slow +@require_torch_gpu +@require_fp_quant +@require_qutlass +@require_accelerate +class FPQuantTest(unittest.TestCase): + model_name = "unsloth/Llama-3.2-1B" + + input_text = "1 2 3 4" + max_new_tokens = 4 + + EXPECTED_OUTPUT = "1 2 3 4 5 6" + + device_map = "cuda" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + quantization_config = FPQuantConfig(pseudoquantization=False) + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, device_map=cls.device_map, quantization_config=quantization_config + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_quantized_model_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly with multiple GPUs + set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + quantization_config = FPQuantConfig() + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, device_map="auto", quantization_config=quantization_config + ) + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_save_pretrained_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto") + self.assertTrue(set(model.hf_device_map.values()) == {0, 1}) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + +@slow +@require_torch_gpu +@require_fp_quant +@require_accelerate +class FPQuantPseudoquantTest(unittest.TestCase): + model_name = "unsloth/Llama-3.2-1B" + + input_text = "1 2 3 4" + max_new_tokens = 4 + + EXPECTED_OUTPUT = "1 2 3 4 5 6" + + device_map = "cuda" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + quantization_config = FPQuantConfig(pseudoquantization=True) + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, device_map=cls.device_map, quantization_config=quantization_config + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_quantized_model_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly with multiple GPUs + set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + quantization_config = FPQuantConfig(pseudoquantization=True) + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, device_map="auto", quantization_config=quantization_config + ) + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_save_pretrained_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto") + self.assertTrue(set(model.hf_device_map.values()) == {0, 1}) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/ggml/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/ggml/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/ggml/test_ggml.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/ggml/test_ggml.py new file mode 100644 index 0000000000000000000000000000000000000000..408ab47a629627a47612cfbe0282c62cdfac473b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/ggml/test_ggml.py @@ -0,0 +1,991 @@ +# 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. +import tempfile +import unittest + +from parameterized import parameterized + +from transformers import AddedToken, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer +from transformers.testing_utils import ( + require_gguf, + require_read_token, + require_torch_accelerator, + slow, + torch_device, +) +from transformers.utils import is_gguf_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_gguf_available(): + from gguf import GGMLQuantizationType as QuantType + + +@require_gguf +@require_torch_accelerator +@slow +class GgufQuantizationTests(unittest.TestCase): + """ + Test cases for weights dequantization with GGUF models. + Note: The quantization names should keep aligned with `GGMLQuantizationType` in gguf-py: + https://github.com/ggerganov/llama.cpp/blob/4b0c638b9a68f577cb2066b638c9f622d91ee661/gguf-py/gguf/constants.py#L1545-L1576 + So quantization like Q4_K_M or Q4_K_S shouldn't be added to this tests. + """ + + example_text = "Hello" + + def run_gguf_model(self, gguf_model_id: str, gguf_filename: str, expected_text: str): + tokenizer = AutoTokenizer.from_pretrained(gguf_model_id, gguf_file=gguf_filename) + model = AutoModelForCausalLM.from_pretrained(gguf_model_id, gguf_file=gguf_filename).to(torch_device) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), expected_text) + + @parameterized.expand( + [ + # standard quants + ("Q4_0", "Hello, World!\n\nStep 3: Add"), + ("Q5_0", "Hello, World!\n\n5. Use a library"), + ("Q8_0", "Hello, World!\n\n5. Use a library"), + ], + ) + def test_standard_quants(self, quant_type: str, expected_text: str): + gguf_model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF" + filename_format = "tinyllama-1.1b-chat-v1.0.{quant_type}.gguf" + gguf_filename = filename_format.format(quant_type=quant_type) + self.run_gguf_model(gguf_model_id, gguf_filename, expected_text) + + # k-quants + @parameterized.expand( + [ + ("Q2_K", "Hello, I'm a 22 year old female"), + ("Q3_K", "Hello\n\nI am trying to create a simple program that"), + ("Q4_K", "Hello\n\nI am trying to create a simple program that"), + ("Q5_K", "Helloveda is a 1999 Indian"), + ("Q6_K", "Hello\n\nI am trying to create a simple program that"), + ], + ) + def test_k_quants(self, quant_type: str, expected_text: str): + gguf_model_id = "legraphista/Qwen2.5-0.5B-Instruct-IMat-GGUF" + filename_format = "Qwen2.5-0.5B-Instruct.{quant_type}.gguf" + gguf_filename = filename_format.format(quant_type=quant_type) + self.run_gguf_model(gguf_model_id, gguf_filename, expected_text) + + @parameterized.expand( + [ + # i-matrix + ("IQ1_S", "Hello, I'm a friend of mine, I"), + ("IQ1_M", "Hello, I am interested in purching a copy of"), + ("IQ2_XXS", "Hello, I'm a software engineer. I'"), + ("IQ2_XS", "Hello World!\n\n```\n<|user|"), + ("IQ2_S", "Hello World!\n\n```\n<|user|"), + ("IQ3_XXS", "Hello, I am interested in your product. Can you"), + ("IQ4_XS", "Hello, world!\n\n5. Using a loop"), + ("IQ3_S", "Hello, World!\n\n5. Python:\n"), + ("IQ4_NL", "Hello, world!\n\n5. Using a loop"), + ], + ) + def test_imatrix_quants(self, quant_type: str, expected_text: str): + gguf_model_id = "duyntnet/TinyLlama-1.1B-Chat-v1.0-imatrix-GGUF" + filename_format = "TinyLlama-1.1B-Chat-v1.0-{quant_type}.gguf" + gguf_filename = filename_format.format(quant_type=quant_type) + self.run_gguf_model(gguf_model_id, gguf_filename, expected_text) + + +@require_gguf +@require_torch_accelerator +@slow +class GgufIntegrationTests(unittest.TestCase): + """ + Test cases for basic interoperability with GGUF models: + - Tokenization + - Model dtype casting and serialization + """ + + example_text = "Hello" + original_model_id = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" + gguf_model_id = "TheBloke/TinyLlama-1.1B-Chat-v1.0-GGUF" + gguf_filename = "tinyllama-1.1b-chat-v1.0.{quant_type}.gguf" + + def test_tokenization_xnli(self): + import tqdm + from datasets import load_dataset + + q8_0_gguf_model_id = self.gguf_filename.format(quant_type=QuantType.Q8_0.name) + gguf_tokenizer = AutoTokenizer.from_pretrained(self.gguf_model_id, gguf_file=q8_0_gguf_model_id) + original_tokenizer = AutoTokenizer.from_pretrained(self.original_model_id) + + dataset = load_dataset("google/code_x_glue_ct_code_to_text", "go") + for item in tqdm.tqdm(dataset["validation"]): + string = item["code"] + encoded1 = gguf_tokenizer.encode(string) + encoded2 = original_tokenizer.encode(string) + + self.assertEqual(encoded1, encoded2) + + decoded1 = gguf_tokenizer.decode(encoded1, skip_special_tokens=True) + decoded2 = original_tokenizer.decode(encoded2, skip_special_tokens=True) + + self.assertEqual(decoded1, decoded2) + + dataset = load_dataset("facebook/xnli", "all_languages") + + for i, item in enumerate(tqdm.tqdm(dataset["train"].select(range(100)))): + for string in item["premise"].values(): + encoded1 = gguf_tokenizer.encode(string) + encoded2 = original_tokenizer.encode(string) + + self.assertEqual(encoded1, encoded2) + + decoded1 = gguf_tokenizer.decode(encoded1, skip_special_tokens=True) + decoded2 = original_tokenizer.decode(encoded2, skip_special_tokens=True) + + self.assertEqual(decoded1, decoded2) + + # With special tokens + gguf_tokenizer = AutoTokenizer.from_pretrained(self.gguf_model_id, gguf_file=q8_0_gguf_model_id) + original_tokenizer = AutoTokenizer.from_pretrained(self.original_model_id) + + gguf_tokenizer.add_special_tokens( + {"additional_special_tokens": [AddedToken("", rstrip=False, lstrip=False)]} + ) + original_tokenizer.add_special_tokens( + {"additional_special_tokens": [AddedToken("", rstrip=False, lstrip=False)]} + ) + + text = "Hello . Hello" + + encoded1 = gguf_tokenizer.encode(text) + encoded2 = original_tokenizer.encode(text) + + self.assertEqual(encoded1, encoded2) + + decoded1 = gguf_tokenizer.decode(encoded1, skip_special_tokens=True) + decoded2 = original_tokenizer.decode(encoded2, skip_special_tokens=True) + + self.assertEqual(decoded1, decoded2) + + def test_q2_k_serialization(self): + q2_k_gguf_model_id = self.gguf_filename.format(quant_type=QuantType.Q2_K.name) + EXPECTED_TEXT = "Hello, World!\n\n[10:0" + + tokenizer = AutoTokenizer.from_pretrained(self.gguf_model_id, gguf_file=q2_k_gguf_model_id) + model = AutoModelForCausalLM.from_pretrained(self.gguf_model_id, gguf_file=q2_k_gguf_model_id).to(torch_device) + + orig_text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + orig_out = model.generate(**orig_text, max_new_tokens=10) + self.assertEqual(tokenizer.decode(orig_out[0], skip_special_tokens=True), EXPECTED_TEXT) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + tokenizer.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname).to(torch_device) + tokenizer = AutoTokenizer.from_pretrained(tmpdirname) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_q6_k_fp16(self): + q6_k_gguf_model_id = self.gguf_filename.format(quant_type=QuantType.Q6_K.name) + + tokenizer = AutoTokenizer.from_pretrained(self.gguf_model_id, gguf_file=q6_k_gguf_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.gguf_model_id, gguf_file=q6_k_gguf_model_id, torch_dtype=torch.float16 + ).to(torch_device) + + self.assertTrue(model.lm_head.weight.dtype == torch.float16) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, World!\n\nStep 3: Add" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_gguf_errors_disk_offload(self): + from collections import OrderedDict + + q2_k_gguf_model_id = self.gguf_filename.format(quant_type=QuantType.Q2_K.name) + with self.assertRaises(RuntimeError): + AutoModelForCausalLM.from_pretrained( + self.gguf_model_id, + device_map=OrderedDict( + [ + ("model.embed_tokens", "cpu"), + ("lm_head", "cpu"), + ("model.layers.0", "cpu"), + ("model.layers.1", "cpu"), + ("model.layers.2", "cpu"), + ("model.layers.3", "cpu"), + ("model.layers.4", "cpu"), + ("model.layers.5", "cpu"), + ("model.layers.6", "cpu"), + ("model.layers.7", "cpu"), + ("model.layers.8", "cpu"), + ("model.layers.9", "cpu"), + ("model.layers.10", "disk"), + ("model.layers.11", "disk"), + ("model.layers.12", "disk"), + ("model.layers.13", "disk"), + ("model.layers.14", "disk"), + ("model.layers.15", "disk"), + ("model.layers.16", "disk"), + ("model.layers.17", "disk"), + ("model.layers.18", "disk"), + ("model.layers.19", "disk"), + ("model.layers.20", "disk"), + ("model.layers.21", "disk"), + ("model.layers.22", "disk"), + ("model.norm", "disk"), + ("model.rotary_emb", "disk"), + ] + ), + gguf_file=q2_k_gguf_model_id, + offload_folder="offload", + offload_state_dict=True, + ) + + +@require_gguf +@require_torch_accelerator +@slow +class GgufModelTests(unittest.TestCase): + mistral_model_id = "TheBloke/Mistral-7B-Instruct-v0.2-GGUF" + qwen2_model_id = "Qwen/Qwen1.5-0.5B-Chat-GGUF" + qwen2moe_model_id = "gdax/Qwen1.5-MoE-A2.7B_gguf" + qwen2moe_original_model_id = "Qwen/Qwen1.5-MoE-A2.7B" + llama3_model_id = "NousResearch/Meta-Llama-3-8B-GGUF" + tinyllama_model_id = "PenutChen/TinyLlama-1.1B-Chat-v1.0-GGUF" + phi3_model_id = "microsoft/Phi-3-mini-4k-instruct-gguf" + bloom_model_id = "afrideva/bloom-560m-GGUF" + original_bloom_model_id = "bigscience/bloom-560m" + falcon7b_model_id_q2 = "xaviviro/falcon-7b-quantized-gguf" + falcon7b_model_id_fp16 = "medmekk/falcon-7b-gguf" + falcon40b_model_id = "maddes8cht/tiiuae-falcon-40b-gguf" + original_flacon7b_model_id = "tiiuae/falcon-7b" + t5_model_id = "repetitio/flan-t5-small" + original_t5_model_id = "google/flan-t5-small" + stablelm_model_id = "afrideva/stablelm-3b-4e1t-GGUF" + stablelm2_model_id = "afrideva/stablelm-2-1_6b-GGUF" + original_stablelm2_model_id = "stabilityai/stablelm-2-1_6b" + gpt2_model_id = "mradermacher/gpt2-GGUF" + gpt2_original_model_id = "openai-community/gpt2" + gpt2_xl_model_id = "RichardErkhov/openai-community_-_gpt2-xl-gguf" + starcoder2_model_id = "QuantFactory/starcoder2-3b-GGUF" + starcoder2_fp16_model_id = "brittlewis12/starcoder2-3b-GGUF" + starcoder2_original_model_id = "bigcode/starcoder2-3b" + mamba_original_model_id = "state-spaces/mamba-2.8b-hf" + mamba_model_id = "jpodivin/mamba-2.8b-hf-GGUF" + nemotron_original_model_id = "nvidia/Nemotron-Mini-4B-Instruct" + nemotron_model_id = "bartowski/Nemotron-Mini-4B-Instruct-GGUF" + original_gemma2_model_id = "google/gemma-2-2b-it" + gemma2_model_id = "bartowski/gemma-2-2b-it-GGUF" + original_gemma3_text_model_id = "google/gemma-3-1b-it" + original_gemma3_vision_model_id = "google/gemma-3-4b-it" + gemma3_qat_model_id = "google/gemma-3-1b-it-qat-q4_0-gguf" + gemma3_text_model_id = "unsloth/gemma-3-1b-it-GGUF" + gemma3_vision_model_id = "unsloth/gemma-3-4b-it-GGUF" + qwen3_model_id = "Qwen/Qwen3-0.6B-GGUF" + qwen3moe_model_id = "Qwen/Qwen3-30B-A3B-GGUF" + + q4_0_phi3_model_id = "Phi-3-mini-4k-instruct-q4.gguf" + q4_0_mistral_model_id = "mistral-7b-instruct-v0.2.Q4_0.gguf" + q4_0_qwen2_model_id = "qwen1_5-0_5b-chat-q4_0.gguf" + q8_qwen2moe_model_id = "Qwen1.5-MoE-A2.7B_Q8_0.gguf" + q4_llama3_model_id = "Meta-Llama-3-8B-Q4_K_M.gguf" + fp16_bloom_model_id = "bloom-560m.fp16.gguf" + q4_k_m_stablelm_model_id = "stablelm-3b-4e1t.q4_k_m.gguf" + fp16_stablelm2_model_id = "stablelm-2-1_6b.fp16.gguf" + q8_bloom_model_id = "bloom-560m.q8_0.gguf" + f16_tinyllama_model_id = "TinyLlama-1.1B-Chat-v1.0.FP16.gguf" + q2_k_falcon7b_model_id = "falcon-7b-q2_k.gguf" + fp16_falcon7b_model_id = "falcon-7b-fp16.gguf" + q2_k_falcon40b_model_id = "tiiuae-falcon-40b-Q2_K.gguf" + fp16_t5_model_id = "flan-t5-small-f16.gguf" + q8_0_t5_model_id = "flan-t5-small-q8_0.gguf" + fp16_qwen2moe_model_id = "Qwen1.5-MoE-A2.7B.gguf" + fp16_gpt2_model_id = "gpt2.f16.gguf" + q8_gpt2_model_id = "gpt2.Q8_0.gguf" + q6_k_gpt2_xl_model_id = "gpt2-xl.Q6_K.gguf" + q6_k_starcoder2_model_id = "starcoder2-3b.Q6_K.gguf" + fp16_starcoder2_gguf_model_id = "starcoder2-3b.fp16.gguf" + q6_k_mamba_model_id = "ggml-model-Q6_K.gguf" + fp16_mamba_model_id = "ggml-model-f16.gguf" + q6_k_nemotron_model_id = "Nemotron-Mini-4B-Instruct-Q6_K.gguf" + fp16_nemotron_model_id = "Nemotron-Mini-4B-Instruct-f16.gguf" + q3_k_gemma2_model_id = "gemma-2-2b-it-Q3_K_L.gguf" + q8_0_gemma2_model_id = "gemma-2-2b-it-Q8_0.gguf" + fp32_gemma2_model_id = "gemma-2-2b-it-f32.gguf" + q4_0_gemma3_qat_model_id = "gemma-3-1b-it-q4_0.gguf" + bf16_gemma3_text_model_id = "gemma-3-1b-it-BF16.gguf" + bf16_gemma3_vision_model_id = "gemma-3-4b-it-BF16.gguf" + q8_0_qwen3_model_id = "Qwen3-0.6B-Q8_0.gguf" + q4_k_m_qwen3moe_model_id = "Qwen3-30B-A3B-Q4_K_M.gguf" + + example_text = "Hello" + + def test_mistral_q4_0(self): + tokenizer = AutoTokenizer.from_pretrained(self.mistral_model_id, gguf_file=self.q4_0_mistral_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.mistral_model_id, + gguf_file=self.q4_0_mistral_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello,\n\nI'm trying to create a" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_qwen2_q4_0(self): + tokenizer = AutoTokenizer.from_pretrained(self.qwen2_model_id, gguf_file=self.q4_0_qwen2_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.qwen2_model_id, + gguf_file=self.q4_0_qwen2_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello.jsoup\n\nI am a beginner" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_qwen2moe_q8(self): + tokenizer = AutoTokenizer.from_pretrained(self.qwen2moe_model_id, gguf_file=self.q8_qwen2moe_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.qwen2moe_model_id, + gguf_file=self.q8_qwen2moe_model_id, + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt") + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I am a 20 year old male" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_qwen2moe_weights_conversion_fp16(self): + quantized_model = AutoModelForCausalLM.from_pretrained( + self.qwen2moe_model_id, + gguf_file=self.fp16_qwen2moe_model_id, + torch_dtype=torch.float16, + ) + original_model = AutoModelForCausalLM.from_pretrained( + self.qwen2moe_original_model_id, + torch_dtype=torch.float16, + ) + + quantized_state_dict = quantized_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in quantized_state_dict: + self.assertTrue(original_params.shape == quantized_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, quantized_state_dict[layer_name]) + + def test_phi3_q4_0(self): + tokenizer = AutoTokenizer.from_pretrained(self.phi3_model_id, gguf_file=self.q4_0_phi3_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.phi3_model_id, gguf_file=self.q4_0_phi3_model_id, device_map="auto", torch_dtype=torch.float16 + ) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I've been reading about the impact of" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_llama3_q4_0_tokenizer(self): + tokenizer = AutoTokenizer.from_pretrained(self.llama3_model_id, gguf_file=self.q4_llama3_model_id) + with tempfile.TemporaryDirectory() as tmpdirname: + tokenizer.save_pretrained(tmpdirname) + tokenizer = AutoTokenizer.from_pretrained(tmpdirname) + special_sentence = "สวัสดี" + predicted_text = tokenizer.decode(tokenizer.encode(special_sentence, return_tensors="pt")[0]) + self.assertEqual(predicted_text, "<|begin_of_text|>" + special_sentence) + + def test_llama3_q4_0(self): + tokenizer = AutoTokenizer.from_pretrained(self.llama3_model_id, gguf_file=self.q4_llama3_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.llama3_model_id, + gguf_file=self.q4_llama3_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I am interested in [The Park]\nThe" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_bloom_fp16(self): + tokenizer = AutoTokenizer.from_pretrained(self.bloom_model_id, gguf_file=self.fp16_bloom_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.bloom_model_id, + gguf_file=self.fp16_bloom_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I just want to say that I am very" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_bloom_q8_0(self): + tokenizer = AutoTokenizer.from_pretrained(self.bloom_model_id, gguf_file=self.q8_bloom_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.bloom_model_id, + gguf_file=self.q8_bloom_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I just want to say that I am just" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_bloom_weights_conversion_fp16(self): + quantized_model = AutoModelForCausalLM.from_pretrained( + self.bloom_model_id, + gguf_file=self.fp16_bloom_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + original_model = AutoModelForCausalLM.from_pretrained( + self.original_bloom_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + quantized_state_dict = quantized_model.state_dict() + original_state_dict = original_model.state_dict() + + for (quantized_name, quantized_param), (original_name, original_param) in zip( + quantized_state_dict.items(), original_state_dict.items() + ): + if ( + "self_attention.query_key_value" in quantized_name + and "self_attention.query_key_value" in original_name + ): + self.assertTrue(quantized_param.shape == original_param.shape) + torch.testing.assert_close(quantized_param, original_param) + + def test_t5_f16(self): + tokenizer = AutoTokenizer.from_pretrained(self.t5_model_id, gguf_file=self.fp16_t5_model_id) + model = AutoModelForSeq2SeqLM.from_pretrained( + self.t5_model_id, gguf_file=self.fp16_t5_model_id, device_map="auto", torch_dtype=torch.float16 + ) + + T5_EXAMPLE_TEXT = "translate English to German: How old are you?" + + text = tokenizer(T5_EXAMPLE_TEXT, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Wie ich er?" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_t5_q8_0(self): + tokenizer = AutoTokenizer.from_pretrained(self.t5_model_id, gguf_file=self.q8_0_t5_model_id) + model = AutoModelForSeq2SeqLM.from_pretrained( + self.t5_model_id, gguf_file=self.q8_0_t5_model_id, device_map="auto", torch_dtype=torch.float16 + ) + + T5_EXAMPLE_TEXT = "translate English to German: How old are you?" + + text = tokenizer(T5_EXAMPLE_TEXT, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Wie ich er?" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_t5_weights_conversion_fp16(self): + quantized_model = AutoModelForSeq2SeqLM.from_pretrained( + self.t5_model_id, + gguf_file=self.fp16_t5_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + original_model = AutoModelForSeq2SeqLM.from_pretrained( + self.original_t5_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + quantized_state_dict = quantized_model.state_dict() + original_state_dict = original_model.state_dict() + + for (quantized_name, quantized_param), (original_name, original_param) in zip( + quantized_state_dict.items(), original_state_dict.items() + ): + self.assertTrue(quantized_param.shape == original_param.shape) + torch.testing.assert_close(quantized_param, original_param, rtol=5e-04, atol=5e-04) + + def test_gpt2_q8(self): + tokenizer = AutoTokenizer.from_pretrained(self.gpt2_model_id, gguf_file=self.q8_gpt2_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.gpt2_model_id, + gguf_file=self.q8_gpt2_model_id, + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt") + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I'm sorry. I'm sorry. I" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_gpt2_weights_conversion_fp16(self): + quantized_model = AutoModelForCausalLM.from_pretrained( + self.gpt2_model_id, + gguf_file=self.fp16_gpt2_model_id, + torch_dtype=torch.float16, + ) + original_model = AutoModelForCausalLM.from_pretrained( + self.gpt2_original_model_id, + torch_dtype=torch.float16, + ) + + quantized_state_dict = quantized_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in quantized_state_dict: + self.assertTrue(original_params.shape == quantized_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, quantized_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + def test_gpt2_xl_Q6_K(self): + tokenizer = AutoTokenizer.from_pretrained(self.gpt2_xl_model_id, gguf_file=self.q6_k_gpt2_xl_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.gpt2_xl_model_id, + gguf_file=self.q6_k_gpt2_xl_model_id, + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt") + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I'm a newbie to the world of" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + @unittest.skip(reason="Heavy memory") + def test_falcon40b_q2_k(self): + tokenizer = AutoTokenizer.from_pretrained(self.falcon40b_model_id, gguf_file=self.q2_k_falcon40b_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.falcon40b_model_id, + gguf_file=self.q2_k_falcon40b_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello All,\nI am new to this forum." + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_falcon7b_q2_k(self): + tokenizer = AutoTokenizer.from_pretrained(self.falcon7b_model_id_q2, gguf_file=self.q2_k_falcon7b_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.falcon7b_model_id_q2, + gguf_file=self.q2_k_falcon7b_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt")["input_ids"].to(torch_device) + out = model.generate(text, max_new_tokens=16) + + EXPECTED_TEXT = "Hello All,\nI am new to this forum.\nI am using the " + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + @unittest.skip("The test causes a torch.OutOfMemoryError on the CI but it passes with enough memory") + def test_falcon7b_weights_conversion_fp16(self): + quantized_model = AutoModelForCausalLM.from_pretrained( + self.falcon7b_model_id_fp16, + gguf_file=self.fp16_falcon7b_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + original_model = AutoModelForCausalLM.from_pretrained( + self.original_flacon7b_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + quantized_state_dict = quantized_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in quantized_state_dict: + self.assertTrue(original_params.shape == quantized_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, quantized_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + def test_stablelm_q4_k_m(self): + model = AutoModelForCausalLM.from_pretrained( + self.stablelm_model_id, + gguf_file=self.q4_k_m_stablelm_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.stablelm_model_id, gguf_file=self.q4_k_m_stablelm_model_id) + text = tokenizer(self.example_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello-\nI am trying to create a new user" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_stablelm_fp16(self): + original_model = AutoModelForCausalLM.from_pretrained( + self.original_stablelm2_model_id, + torch_dtype=torch.float16, + ) + + converted_model = AutoModelForCausalLM.from_pretrained( + self.stablelm2_model_id, + gguf_file=self.fp16_stablelm2_model_id, + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.stablelm2_model_id, gguf_file=self.fp16_stablelm2_model_id) + text = tokenizer(self.example_text, return_tensors="pt") + original_out = original_model.generate(**text, max_new_tokens=10) + converted_out = converted_model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I am a 20 year old male" + self.assertEqual(tokenizer.decode(converted_out[0], skip_special_tokens=True), EXPECTED_TEXT) + self.assertEqual( + tokenizer.decode(converted_out[0], skip_special_tokens=True), + tokenizer.decode(original_out[0], skip_special_tokens=True), + ) + + def test_stablelm_weights_conversion_fp16(self): + original_model = AutoModelForCausalLM.from_pretrained( + self.original_stablelm2_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + converted_model = AutoModelForCausalLM.from_pretrained( + self.stablelm2_model_id, + gguf_file=self.fp16_stablelm2_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + converted_state_dict = converted_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in converted_state_dict: + self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, converted_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + def test_starcoder2_weights_conversion_fp16(self): + original_model = AutoModelForCausalLM.from_pretrained( + self.starcoder2_original_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + converted_model = AutoModelForCausalLM.from_pretrained( + self.starcoder2_fp16_model_id, + gguf_file=self.fp16_starcoder2_gguf_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + converted_state_dict = converted_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in converted_state_dict: + self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, converted_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + def test_starcoder2_q6_k(self): + example_function_text = "def print_hello_world():" + model = AutoModelForCausalLM.from_pretrained( + self.starcoder2_model_id, + gguf_file=self.q6_k_starcoder2_model_id, + device_map="auto", + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.starcoder2_model_id, gguf_file=self.q6_k_starcoder2_model_id) + text = tokenizer(example_function_text, return_tensors="pt").to(torch_device) + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = 'def print_hello_world():\n print("Hello World")\n\ndef print' + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_mamba_weights_conversion_fp16(self): + original_model = AutoModelForCausalLM.from_pretrained( + self.mamba_original_model_id, + torch_dtype=torch.float16, + ) + + converted_model = AutoModelForCausalLM.from_pretrained( + self.mamba_model_id, + gguf_file=self.fp16_mamba_model_id, + torch_dtype=torch.float16, + ) + + converted_state_dict = converted_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in converted_state_dict: + self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape) + if "mixer.A_log" in layer_name: + # we should increase tolerance after exponential reversing + # and performing np.log(-weights) operation as numbers are slightly different + torch.testing.assert_close(original_params, converted_state_dict[layer_name], rtol=1e-3, atol=1e-3) + else: + torch.testing.assert_close(original_params, converted_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + def test_mamba_q6_k(self): + model = AutoModelForCausalLM.from_pretrained( + self.mamba_model_id, + gguf_file=self.q6_k_mamba_model_id, + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.mamba_model_id, gguf_file=self.q6_k_mamba_model_id) + text = tokenizer(self.example_text, return_tensors="pt")["input_ids"] + out = model.generate(text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello,I answerthe question.\n\nA" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_nemotron_weights_conversion_fp16(self): + original_model = AutoModelForCausalLM.from_pretrained( + self.nemotron_original_model_id, + torch_dtype=torch.float16, + ) + + converted_model = AutoModelForCausalLM.from_pretrained( + self.nemotron_model_id, + gguf_file=self.fp16_nemotron_model_id, + torch_dtype=torch.float16, + ) + + converted_state_dict = converted_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in converted_state_dict: + self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, converted_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + def test_nemotron_q6_k(self): + model = AutoModelForCausalLM.from_pretrained( + self.nemotron_model_id, + gguf_file=self.q6_k_nemotron_model_id, + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.nemotron_model_id, gguf_file=self.q6_k_nemotron_model_id) + text = tokenizer(self.example_text, return_tensors="pt")["input_ids"] + out = model.generate(text, max_new_tokens=16) + + EXPECTED_TEXT = "Hello.▁hotmail.com" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_gemma2_q3_k(self): + model = AutoModelForCausalLM.from_pretrained( + self.gemma2_model_id, + gguf_file=self.q3_k_gemma2_model_id, + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.gemma2_model_id, gguf_file=self.q3_k_gemma2_model_id) + text = tokenizer(self.example_text, return_tensors="pt")["input_ids"] + out = model.generate(text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello! 👋\n\nI'm trying to create a" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_gemma2_q8_0(self): + model = AutoModelForCausalLM.from_pretrained( + self.gemma2_model_id, + gguf_file=self.q8_0_gemma2_model_id, + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.gemma2_model_id, gguf_file=self.q8_0_gemma2_model_id) + text = tokenizer(self.example_text, return_tensors="pt")["input_ids"] + out = model.generate(text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello! 👋\n\nI'm a large language model" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_gemma2_fp32(self): + model = AutoModelForCausalLM.from_pretrained( + self.gemma2_model_id, + gguf_file=self.fp32_gemma2_model_id, + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.gemma2_model_id, gguf_file=self.fp32_gemma2_model_id) + text = tokenizer(self.example_text, return_tensors="pt")["input_ids"] + out = model.generate(text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello! 👋\n\nI'm a large language model" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + @require_read_token + def test_gemma2_weights_conversion_fp32(self): + original_model = AutoModelForCausalLM.from_pretrained( + self.original_gemma2_model_id, + torch_dtype=torch.float16, + ) + + converted_model = AutoModelForCausalLM.from_pretrained( + self.gemma2_model_id, + gguf_file=self.fp32_gemma2_model_id, + torch_dtype=torch.float16, + ) + + converted_state_dict = converted_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in converted_state_dict: + self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, converted_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + @require_read_token + @unittest.skipUnless(is_gguf_available("0.16.0"), "test requires gguf version >= 0.16.0") + def test_gemma3_qat_q4_0(self): + model = AutoModelForCausalLM.from_pretrained( + self.gemma3_qat_model_id, + gguf_file=self.q4_0_gemma3_qat_model_id, + torch_dtype=torch.float16, + ) + + tokenizer = AutoTokenizer.from_pretrained(self.gemma3_qat_model_id, gguf_file=self.q4_0_gemma3_qat_model_id) + text = tokenizer(self.example_text, return_tensors="pt")["input_ids"] + out = model.generate(text, max_new_tokens=10) + + EXPECTED_TEXT = 'Hello with the prompt, "What is the best way' + + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + @require_read_token + @unittest.skipUnless(is_gguf_available("0.16.0"), "test requires gguf version >= 0.16.0") + def test_gemma3_text_weights_conversion_bf16(self): + original_model = AutoModelForCausalLM.from_pretrained( + self.original_gemma3_text_model_id, + torch_dtype=torch.float16, + ) + + converted_model = AutoModelForCausalLM.from_pretrained( + self.gemma3_text_model_id, + gguf_file=self.bf16_gemma3_text_model_id, + torch_dtype=torch.float16, + ) + + converted_state_dict = converted_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in converted_state_dict: + self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, converted_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + # Test text backbone conversion for gemma3 vision models + @require_read_token + @unittest.skipUnless(is_gguf_available("0.16.0"), "test requires gguf version >= 0.16.0") + def test_gemma3_vision_weights_conversion_bf16(self): + original_model = AutoModelForCausalLM.from_pretrained( + self.original_gemma3_vision_model_id, + torch_dtype=torch.float16, + ).language_model + + converted_model = AutoModelForCausalLM.from_pretrained( + self.gemma3_vision_model_id, + gguf_file=self.bf16_gemma3_vision_model_id, + torch_dtype=torch.float16, + ) + + converted_state_dict = converted_model.state_dict() + original_state_dict = original_model.state_dict() + + for layer_name, original_params in original_state_dict.items(): + if layer_name in converted_state_dict: + self.assertTrue(original_params.shape == converted_state_dict[layer_name].shape) + torch.testing.assert_close(original_params, converted_state_dict[layer_name]) + else: + raise ValueError(f"Layer {layer_name} is not presented in GGUF model") + + @require_read_token + @unittest.skipUnless(is_gguf_available("0.16.0"), "test requires gguf version >= 0.16.0") + def test_qwen3_q8_0(self): + tokenizer = AutoTokenizer.from_pretrained(self.qwen3_model_id, gguf_file=self.q8_0_qwen3_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.qwen3_model_id, + gguf_file=self.q8_0_qwen3_model_id, + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt")["input_ids"] + out = model.generate(text, max_new_tokens=10) + + EXPECTED_TEXT = "HelloED\nI need to find the value of the" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) + + def test_qwen3moe_q4_k_m(self): + tokenizer = AutoTokenizer.from_pretrained(self.qwen3moe_model_id, gguf_file=self.q4_k_m_qwen3moe_model_id) + model = AutoModelForCausalLM.from_pretrained( + self.qwen3moe_model_id, + gguf_file=self.q4_k_m_qwen3moe_model_id, + torch_dtype=torch.float16, + ) + + text = tokenizer(self.example_text, return_tensors="pt") + out = model.generate(**text, max_new_tokens=10) + + EXPECTED_TEXT = "Hello, I am a 20 year old male" + self.assertEqual(tokenizer.decode(out[0], skip_special_tokens=True), EXPECTED_TEXT) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/test_gptq.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/test_gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..f665ee07f112dbe400786b301d2331f741deb06b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/gptq/test_gptq.py @@ -0,0 +1,499 @@ +# 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. + +import tempfile +import unittest + +import pytest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GPTQConfig +from transformers.testing_utils import ( + is_torch_available, + require_accelerate, + require_gptq, + require_optimum, + require_torch_gpu, + require_torch_multi_gpu, + slow, +) +from transformers.utils import is_auto_gptq_available, is_gptqmodel_available, is_ipex_available + + +if is_torch_available(): + import torch + + +class GPTQConfigTest(unittest.TestCase): + def test_bits(self): + with self.assertRaises(ValueError): + GPTQConfig(bits="") + GPTQConfig(bits=1) + GPTQConfig(bits=2) + GPTQConfig(bits=4) + + def test_dataset(self): + with self.assertRaises(ValueError): + GPTQConfig(bits=2, dataset="auto_gpt") + GPTQConfig(bits=2, dataset="c4") + + def test_damp_percent(self): + with self.assertRaises(ValueError): + GPTQConfig(bits=2, damp_percent=10) + GPTQConfig(bits=2, damp_percent=-1) + GPTQConfig(bits=2, damp_percent="0") + GPTQConfig(bits=2, damp_percent=0.01) + + def test_to_dict(self): + quantization_config = GPTQConfig(bits=2) + quantization_config.to_dict() + + def test_from_dict(self): + dict = {"bits": 2} + quantization_config = GPTQConfig.from_dict(dict) + self.assertEqual(dict["bits"], quantization_config.bits) + + @require_optimum + def test_optimum_config(self): + from optimum.gptq import GPTQQuantizer + + config = GPTQConfig(bits=2) + optimum_config = GPTQQuantizer.from_dict(config.to_dict_optimum()) + self.assertEqual(optimum_config.bits, config.bits) + new_config = GPTQConfig.from_dict_optimum(optimum_config.to_dict()) + self.assertEqual(optimum_config.bits, new_config.bits) + + +@slow +@require_optimum +@require_gptq +class GPTQTest(unittest.TestCase): + model_name = "bigscience/bloom-560m" + + input_text = "Hello my name is" + + EXPECTED_OUTPUTS = set() + # flaky test: gptqmodel and auto-gptq are not output equivalent nor is string compare deterministic even between transformer/torch versions + EXPECTED_OUTPUTS.add("Hello my name is John and I am a professional photographer. I") + EXPECTED_OUTPUTS.add("Hello my name is John, I am a professional photographer and I") + EXPECTED_OUTPUTS.add("Hello my name is John, I am a student in the University of") + EXPECTED_OUTPUTS.add("Hello my name is John and I am a very good looking man.") + EXPECTED_OUTPUTS.add("Hello my name is Alyson, I am a student in the") + EXPECTED_OUTPUTS.add("Hello my name is Alyson and I am a very sweet,") + EXPECTED_OUTPUTS.add("Hello my name is Aiden, I am a student at the University") + EXPECTED_OUTPUTS.add("Hello my name is Nate and I am a member of the N") + EXPECTED_OUTPUTS.add("Hello my name is Nellie and I am a student at the") + EXPECTED_OUTPUTS.add("Hello my name is Nate and I am a new member of the") + + # this seems a little small considering that we are doing 4bit quant but we have a small model and ww don't quantize the embeddings + EXPECTED_RELATIVE_DIFFERENCE = 1.664253062 + + bits = 4 + sym = True + group_size = 128 + desc_act = False + use_exllama = False + + dataset = [ + "auto-gptq is an easy-to-use model quantization library with user-friendly apis, based on GPTQ algorithm." + ] + + device_map = "cpu" if is_gptqmodel_available() else None + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.model_fp16 = AutoModelForCausalLM.from_pretrained( + cls.model_name, torch_dtype=torch.float16, device_map=cls.device_map + ) + cls.mem_fp16 = cls.model_fp16.get_memory_footprint() + + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True) + cls.config = AutoConfig.from_pretrained(cls.model_name) + + cls.quantization_config = GPTQConfig( + bits=cls.bits, + dataset=cls.dataset, + tokenizer=cls.tokenizer, + group_size=cls.group_size, + desc_act=cls.desc_act, + sym=cls.sym, + use_exllama=cls.use_exllama, + ) + + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + torch_dtype=torch.float16, + device_map=cls.device_map, + quantization_config=cls.quantization_config, + ) + + def test_memory_footprint(self): + r""" + A simple test to check if the model conversion has been done correctly by checking on the + memory footprint of the converted model + """ + + mem_quantized = self.quantized_model.get_memory_footprint() + + self.assertAlmostEqual(self.mem_fp16 / mem_quantized, self.EXPECTED_RELATIVE_DIFFERENCE, places=4) + + def test_device_and_dtype_assignment(self): + r""" + Test whether trying to cast (or assigning a device to) a model after quantization will throw an error. + Checks also if other models are casted correctly. + """ + # This should work + if self.device_map in (None, "cpu"): + _ = self.quantized_model.to(0) + + with self.assertRaises(ValueError): + # Tries with a `dtype`` + self.quantized_model.to(torch.float16) + + def test_original_dtype(self): + r""" + A simple test to check if the model successfully stores the original dtype + """ + self.assertTrue(hasattr(self.quantized_model.config, "_pre_quantization_dtype")) + self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype")) + self.assertTrue(self.quantized_model.config._pre_quantization_dtype == torch.float16) + + def test_quantized_layers_class(self): + """ + Simple test to check if the model conversion has been done correctly by checking on + the class type of the linear layers of the converted models + """ + if is_gptqmodel_available(): + from gptqmodel.utils.importer import hf_select_quant_linear + + if hasattr(self.config, "quantization_config"): + checkpoint_format = self.config.quantization_config.get("checkpoint_format") + meta = self.config.quantization_config.get("meta") + else: + checkpoint_format = "gptq" + meta = None + QuantLinear = hf_select_quant_linear( + bits=self.bits, + group_size=self.group_size, + desc_act=self.desc_act, + sym=self.sym, + device_map=self.device_map, + checkpoint_format=checkpoint_format, + meta=meta, + backend=self.quantization_config.backend, + ) + elif is_auto_gptq_available(): + from auto_gptq.utils.import_utils import dynamically_import_QuantLinear as hf_select_quant_linear + + QuantLinear = hf_select_quant_linear( + use_triton=False, + desc_act=self.desc_act, + group_size=self.group_size, + bits=self.bits, + disable_exllama=not self.use_exllama, + disable_exllamav2=True, + ) + self.assertTrue(self.quantized_model.transformer.h[0].mlp.dense_4h_to_h.__class__ == QuantLinear) + + def check_inference_correctness(self, model): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(model.device), max_new_tokens=10) + + # Get the generation + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def check_quantized_layers_type(self, model, value): + self.assertTrue(model.transformer.h[0].mlp.dense_4h_to_h.QUANT_TYPE == value) + + def test_generate_quality(self): + """ + Simple test to check the quality of the model by comparing the generated tokens with the expected tokens + """ + if self.device_map is None: + self.check_inference_correctness(self.quantized_model.to(0)) + else: + if self.device_map == "cpu" and self.quantized_model.device.type != "cpu": + self.quantized_model.to("cpu") + self.check_inference_correctness(self.quantized_model) + + def test_serialization(self): + """ + Test the serialization of the model and the loading of the quantized weights works + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + if is_auto_gptq_available() and not is_gptqmodel_available(): + quant_type = "cuda-old" if not self.use_exllama else "exllama" + if not self.use_exllama: + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained( + tmpdirname, quantization_config=GPTQConfig(use_exllama=False, bits=4) + ) + if self.device_map != "cpu": + quantized_model_from_saved = quantized_model_from_saved.to(0) + else: + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained( + tmpdirname, device_map=self.device_map + ) + else: + if self.device_map == "cpu": + quant_type = "ipex" if is_ipex_available() else "torch" + else: + # We expect tritonv2 to be used here, because exllama backend doesn't support packing https://github.com/ModelCloud/GPTQModel/issues/1354 + # TODO: Remove this once GPTQModel exllama kernels supports packing + quant_type = "tritonv2" + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained( + tmpdirname, device_map=self.device_map + ) + + self.check_quantized_layers_type(quantized_model_from_saved, quant_type) + self.check_inference_correctness(quantized_model_from_saved) + + @require_accelerate + def test_serialization_big_model_inference(self): + """ + Test the serialization of the model and the loading of the quantized weights with big model inference + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + device_map = self.device_map or "auto" + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=device_map) + self.check_inference_correctness(quantized_model_from_saved) + + +@require_torch_gpu +class GPTQTestCUDA(GPTQTest): + device_map = {"": 0} + + def test_change_loading_attributes(self): + """ + Test the serialization of the model and the loading of the quantized weights works with another config file + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + if is_auto_gptq_available() and not is_gptqmodel_available() and not self.use_exllama: + self.check_quantized_layers_type(self.quantized_model, "cuda-old") + # we need to put it directly to the gpu. Otherwise, we won't be able to initialize the exllama kernel + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained( + tmpdirname, quantization_config=GPTQConfig(use_exllama=True, bits=4), device_map=self.device_map + ) + self.assertEqual(quantized_model_from_saved.config.quantization_config.bits, self.bits) + self.check_quantized_layers_type(quantized_model_from_saved, "exllama") + self.check_inference_correctness(quantized_model_from_saved) + + +@require_accelerate +@require_torch_multi_gpu +class GPTQTestDeviceMap(GPTQTestCUDA): + device_map = "auto" + + +@require_accelerate +@require_torch_multi_gpu +class GPTQTestDeviceMapExllama(GPTQTestCUDA): + device_map = "auto" + use_exllama = True + + +@slow +@require_optimum +@require_gptq +@require_torch_gpu +@require_accelerate +class GPTQTestActOrderExllama(unittest.TestCase): + """ + Test GPTQ model with exllama kernel and desc_act=True (also known as act-order). + More information on those arguments here: + https://huggingface.co/docs/transformers/main_classes/quantization#transformers.GPTQConfig + """ + + EXPECTED_OUTPUTS = set() + # flaky test: gptqmodel and auto-gptq are not output equivalent nor is string compare deterministic even between transformer/torch versions + EXPECTED_OUTPUTS.add("Hello, how are you ? I'm doing good, thanks for asking.") + # 4bit + act_order + 128g + model_name = "hf-internal-testing/TinyLlama-1.1B-Chat-v0.3-GPTQ" + input_text = "Hello, how are you ?" + + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.quantization_config = GPTQConfig(bits=4, max_input_length=4028) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + torch_dtype=torch.float16, + device_map={"": 0}, + quantization_config=cls.quantization_config, + ) + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True) + + def check_inference_correctness(self, model): + """ + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Get the generation + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_quantized_layers_type(self): + self.assertTrue(self.quantized_model.model.layers[0].self_attn.k_proj.QUANT_TYPE == "exllama") + + def test_generate_quality(self): + """ + Simple test to check the quality of the model by comparing the generated tokens with the expected tokens + """ + self.check_inference_correctness(self.quantized_model) + + def test_max_input_length(self): + """ + Test if the max_input_length works. It modifies the maximum input length that of the model that runs with exllama backend. + """ + + prompt = "I am in Paris and" * 1000 + inp = self.tokenizer(prompt, return_tensors="pt").to(0) + self.assertTrue(inp["input_ids"].shape[1] > 4028) + with self.assertRaises(RuntimeError) as cm: + self.quantized_model.generate(**inp, num_beams=1, min_new_tokens=3, max_new_tokens=3) + self.assertTrue("temp_state buffer is too small" in str(cm.exception)) + + prompt = "I am in Paris and" + inp = self.tokenizer(prompt, return_tensors="pt").to(0) + self.assertTrue(inp["input_ids"].shape[1] < 4028) + self.quantized_model.generate(**inp, num_beams=1, min_new_tokens=3, max_new_tokens=3) + + +@slow +@require_optimum +@require_gptq +@require_torch_gpu +@require_accelerate +class GPTQTestExllamaV2(unittest.TestCase): + """ + Test GPTQ model with exllamav2 kernel and desc_act=True (also known as act-order). + More information on those arguments here: + https://huggingface.co/docs/transformers/main_classes/quantization#transformers.GPTQConfig + """ + + EXPECTED_OUTPUTS = set() + # flaky test: gptqmodel and auto-gptq are not output equivalent nor is string compare deterministic even between transformer/torch versions + EXPECTED_OUTPUTS.add("Hello, how are you ? I'm doing good, thanks for asking.") + # 4bit + act_order + 128g + model_name = "hf-internal-testing/TinyLlama-1.1B-Chat-v0.3-GPTQ" + input_text = "Hello, how are you ?" + + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.quantization_config = GPTQConfig(bits=4, exllama_config={"version": 2}) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + torch_dtype=torch.float16, + device_map={"": 0}, + quantization_config=cls.quantization_config, + ) + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name, use_fast=True) + + def test_quantized_layers_type(self): + if is_auto_gptq_available() and not is_gptqmodel_available(): + self.assertEqual( + self.quantized_model.model.layers[0].self_attn.k_proj.QUANT_TYPE, + "exllamav2", + ) + else: + # We expect tritonv2 to be used here, because exllama backend doesn't support packing https://github.com/ModelCloud/GPTQModel/issues/1354 + # TODO: Remove this once GPTQModel exllama kernels supports packing + self.assertEqual( + self.quantized_model.model.layers[0].self_attn.k_proj.QUANT_TYPE, + "tritonv2", + ) + + def check_inference_correctness(self, model): + """ + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + # Check the exactness of the results + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), max_new_tokens=10) + + # Get the generation + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality(self): + """ + Simple test to check the quality of the model by comparing the generated tokens with the expected tokens + """ + self.check_inference_correctness(self.quantized_model) + + +# fail when run all together +@pytest.mark.skip +@require_accelerate +@require_torch_multi_gpu +class GPTQTestDeviceMapCPUOffload(GPTQTest): + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": 0, + "lm_head": 0, + "transformer.h.0": 0, + "transformer.h.1": 0, + "transformer.h.2": 0, + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 0, + "transformer.h.10": 1, + "transformer.h.11": 1, + "transformer.h.12": 1, + "transformer.h.13": 1, + "transformer.h.14": 1, + "transformer.h.15": 1, + "transformer.h.16": 1, + "transformer.h.17": 0, + "transformer.h.18": "cpu", + "transformer.h.19": "cpu", + "transformer.h.20": "cpu", + "transformer.h.21": "cpu", + "transformer.h.22": "cpu", + "transformer.h.23": 1, + "transformer.ln_f": 0, + } diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/test_higgs.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/test_higgs.py new file mode 100644 index 0000000000000000000000000000000000000000..20727620269813cdcd23bc1d4c88e699adc97dc8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/higgs/test_higgs.py @@ -0,0 +1,197 @@ +# 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. + +import gc +import tempfile +import unittest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, HiggsConfig, OPTForCausalLM +from transformers.testing_utils import ( + backend_empty_cache, + require_accelerate, + require_flute_hadamard, + require_torch_gpu, + require_torch_multi_gpu, + slow, + torch_device, +) +from transformers.utils import is_accelerate_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_accelerate_available(): + from accelerate import init_empty_weights + + +@require_torch_gpu +class HiggsConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object + """ + quantization_config = HiggsConfig() + config_to_dict = quantization_config.to_dict() + + for key in config_to_dict: + self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) + + def test_from_dict(self): + """ + Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict + """ + dict = {"modules_to_not_convert": ["embed_tokens", "lm_head"], "quant_method": "higgs"} + quantization_config = HiggsConfig.from_dict(dict) + + self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) + self.assertEqual(dict["quant_method"], quantization_config.quant_method) + + +@slow +@require_torch_gpu +@require_flute_hadamard +@require_accelerate +# @require_read_token +class HiggsTest(unittest.TestCase): + model_name = "unsloth/Llama-3.2-1B" + + input_text = "Font test: A quick brown fox jumps over the" + max_new_tokens = 2 + + EXPECTED_OUTPUT = "Font test: A quick brown fox jumps over the lazy dog" + + device_map = "cuda" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + quantization_config = HiggsConfig() + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, device_map=cls.device_map, quantization_config=quantization_config + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_quantized_model_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly + """ + + from transformers.integrations import HiggsLinear, replace_with_higgs_linear + + model_id = "facebook/opt-350m" + config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") + quantization_config = HiggsConfig() + + with init_empty_weights(): + model = OPTForCausalLM(config) + + nb_linears = 0 + for module in model.modules(): + if isinstance(module, torch.nn.Linear): + nb_linears += 1 + + model, _ = replace_with_higgs_linear(model, quantization_config=quantization_config) + nb_higgs_linear = 0 + for module in model.modules(): + if isinstance(module, HiggsLinear): + nb_higgs_linear += 1 + + self.assertEqual(nb_linears - 1, nb_higgs_linear) + + with init_empty_weights(): + model = OPTForCausalLM(config) + quantization_config = HiggsConfig(modules_to_not_convert=["fc1"]) + model, _ = replace_with_higgs_linear(model, quantization_config=quantization_config) + nb_higgs_linear = 0 + for module in model.modules(): + if isinstance(module, HiggsLinear): + nb_higgs_linear += 1 + + self.assertEqual(nb_linears - 24, nb_higgs_linear) + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_quantized_model_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly with multiple GPUs + set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 GPUs + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + quantization_config = HiggsConfig() + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, device_map="auto", quantization_config=quantization_config + ) + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_save_pretrained_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map="auto") + self.assertTrue(set(model.hf_device_map.values()) == {0, 1}) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @unittest.skip("This will almost surely OOM. Enable when switched to a smaller model") + def test_dequantize(self): + """ + Test the ability to dequantize a model + """ + self.quantized_model.dequantize() + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/hqq/test_hqq.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/hqq/test_hqq.py new file mode 100644 index 0000000000000000000000000000000000000000..a3aae71552ff6d4688831a63c772df525ddd5292 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/hqq/test_hqq.py @@ -0,0 +1,314 @@ +# 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. + +import gc +import unittest + +import accelerate + +from transformers import AutoModelForCausalLM, AutoTokenizer, HqqConfig +from transformers.testing_utils import ( + backend_empty_cache, + require_accelerate, + require_deterministic_for_xpu, + require_hqq, + require_torch_accelerator, + require_torch_multi_accelerator, + slow, + torch_device, +) +from transformers.utils import is_hqq_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_hqq_available(): + from hqq.core.quantize import HQQBackend, HQQLinear + + +class HQQLLMRunner: + def __init__(self, model_id, quant_config, compute_dtype, device, cache_dir=None): + self.model = AutoModelForCausalLM.from_pretrained( + model_id, + torch_dtype=compute_dtype, + device_map=device, + quantization_config=quant_config, + cache_dir=cache_dir, + ) + self.tokenizer = AutoTokenizer.from_pretrained(model_id, cache_dir=cache_dir) + self.device = self.model.device + HQQLinear.set_backend(HQQBackend.PYTORCH) + + +def cleanup(): + backend_empty_cache(torch_device) + gc.collect() + + +def check_hqqlayer(test_module, hqq_layer, batch_size=1, context_size=1024): + # Test HQQ layer + W_dequant = hqq_layer.dequantize() # Reconstructed weights + inputs = ( + torch.randn( + (batch_size, context_size, hqq_layer.meta["shape"][1]), + device=hqq_layer.device, + dtype=hqq_layer.compute_dtype, + ) + / 10.0 + ) + with torch.no_grad(): + outputs = hqq_layer(inputs) + test_module.assertEqual(outputs.shape[-1], W_dequant.shape[0]) + test_module.assertEqual(outputs.dtype, hqq_layer.compute_dtype) + del W_dequant, inputs, outputs + cleanup() + + +def check_forward(test_module, model, batch_size=1, context_size=1024): + # Test forward pass + with torch.no_grad(): + out = model(torch.zeros([batch_size, context_size], device=model.device, dtype=torch.int32)).logits + test_module.assertEqual(out.shape[0], batch_size) + test_module.assertEqual(out.shape[1], context_size) + cleanup() + + +MODEL_ID = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" + + +@require_torch_accelerator +@require_hqq +class HqqConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Makes sure the config format is properly set + """ + quantization_config = HqqConfig() + hqq_orig_config = quantization_config.to_dict() + + self.assertEqual(quantization_config.quant_config, hqq_orig_config["quant_config"]) + + +@slow +@require_torch_accelerator +@require_accelerate +@require_hqq +class HQQTest(unittest.TestCase): + def tearDown(self): + cleanup() + + def test_fp16_quantized_model(self): + """ + Simple LLM model testing fp16 + """ + quant_config = HqqConfig(nbits=8, group_size=64) + + hqq_runner = HQQLLMRunner( + model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device + ) + + check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) + check_forward(self, hqq_runner.model) + + def test_quantized_model_to_new_device_and_new_dtype(self): + """ + Simple LLM model testing different devices and dtypes + """ + quant_config = HqqConfig(nbits=8, group_size=64) + + hqq_runner = HQQLLMRunner( + model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device + ) + + check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) + check_forward(self, hqq_runner.model) + + # Remove `accelerate` hooks to enable move the model to a new device + accelerate.hooks.remove_hook_from_module(hqq_runner.model, recurse=True) + + hqq_runner.model.to("cpu", torch.bfloat16) + check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) + check_forward(self, hqq_runner.model) + + hqq_runner.model.to(torch_device) + check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) + check_forward(self, hqq_runner.model) + + def test_quantized_model_fake_weight_dtype(self): + quant_config = HqqConfig(nbits=8, group_size=64) + + hqq_runner = HQQLLMRunner( + model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device + ) + + # We use a hack to inject a fake weight to HQQLinear. Check that it works + self.assertEqual(hqq_runner.model.model.layers[0].self_attn.v_proj.weight.dtype, torch.float16) + + +@slow +@require_torch_accelerator +@require_torch_multi_accelerator +@require_accelerate +@require_hqq +class HQQTestMultiGPU(unittest.TestCase): + def tearDown(self): + cleanup() + + def test_fp16_quantized_model_multipgpu(self): + """ + Simple LLM model testing fp16 with multi-gpu + """ + + quant_config = HqqConfig(nbits=8, group_size=64) + + hqq_runner = HQQLLMRunner( + model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device="auto" + ) + + check_hqqlayer(self, hqq_runner.model.model.layers[0].self_attn.v_proj) + check_forward(self, hqq_runner.model) + + +@slow +@require_torch_accelerator +@require_accelerate +@require_hqq +class HQQTestBias(unittest.TestCase): + def tearDown(self): + cleanup() + + def test_fp16_quantized_model(self): + """ + Simple LLM model testing fp16 with bias + """ + quant_config = HqqConfig(nbits=8, group_size=64) + + hqq_runner = HQQLLMRunner( + model_id="facebook/opt-125m", quant_config=quant_config, compute_dtype=torch.float16, device=torch_device + ) + + check_hqqlayer(self, hqq_runner.model.model.decoder.layers[0].self_attn.v_proj) + check_forward(self, hqq_runner.model) + + @require_deterministic_for_xpu + def test_save_and_load_quantized_model(self): + """ + Test saving and loading a quantized model with bias + """ + import tempfile + + quant_config = HqqConfig(nbits=8, group_size=64) + + hqq_runner = HQQLLMRunner( + model_id="facebook/opt-125m", quant_config=quant_config, compute_dtype=torch.float16, device=torch_device + ) + + input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device) + + # Get reference logits + with torch.no_grad(): + logits_ref = hqq_runner.model.forward(input_tensor).logits + + with tempfile.TemporaryDirectory() as tmpdirname: + hqq_runner.model.save_pretrained(tmpdirname) + + del hqq_runner.model + backend_empty_cache(torch_device) + + model_loaded = AutoModelForCausalLM.from_pretrained( + tmpdirname, torch_dtype=torch.float16, device_map=torch_device + ) + + with torch.no_grad(): + logits_loaded = model_loaded.forward(input_tensor).logits + + self.assertEqual((logits_loaded - logits_ref).abs().mean().item(), 0) + + +@slow +@require_torch_accelerator +@require_accelerate +@require_hqq +class HQQSerializationTest(unittest.TestCase): + def tearDown(self): + cleanup() + + def test_model_serialization(self): + """ + Simple HQQ LLM save/load test + """ + quant_config = HqqConfig(nbits=4, group_size=64) + + hqq_runner = HQQLLMRunner( + model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device + ) + + input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device) + + with torch.no_grad(): + logits_ref = hqq_runner.model.forward(input_tensor).logits + + # Save + saved_model_id = "quant_model" + hqq_runner.model.save_pretrained(saved_model_id) + + # Remove old model + del hqq_runner.model + backend_empty_cache(torch_device) + + # Load and check if the logits match + model_loaded = AutoModelForCausalLM.from_pretrained( + "quant_model", + torch_dtype=torch.float16, + device_map=torch_device, + ) + + with torch.no_grad(): + logits_loaded = model_loaded.forward(input_tensor).logits + + self.assertEqual((logits_loaded - logits_ref).abs().mean().item(), 0) + + def test_model_serialization_dynamic_quant_with_skip(self): + """ + Simple HQQ LLM save/load test with dynamic quant + """ + q4_config = {"nbits": 4, "group_size": 64} + q3_config = {"nbits": 3, "group_size": 64} + + quant_config = HqqConfig( + dynamic_config={ + "self_attn.q_proj": q4_config, + "self_attn.k_proj": q4_config, + "self_attn.v_proj": q4_config, + "self_attn.o_proj": q4_config, + "mlp.gate_proj": q3_config, + "mlp.up_proj": q3_config, + }, + skip_modules=["lm_head", "down_proj"], + ) + + hqq_runner = HQQLLMRunner( + model_id=MODEL_ID, quant_config=quant_config, compute_dtype=torch.float16, device=torch_device + ) + + model = hqq_runner.model + + input_tensor = torch.zeros((1, 8), dtype=torch.int32, device=torch_device) + with torch.no_grad(): + model.forward(input_tensor).logits + + self.assertEqual(isinstance(model.model.layers[1].mlp.down_proj, torch.nn.Linear), True) + self.assertEqual(model.model.layers[1].self_attn.v_proj.quant_config["weight_quant_params"]["nbits"], 4) + self.assertEqual(model.model.layers[1].mlp.gate_proj.quant_config["weight_quant_params"]["nbits"], 3) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/test_mxfp4.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/test_mxfp4.py new file mode 100644 index 0000000000000000000000000000000000000000..1743891f8b3fbc1b01df2c127a6921eba465533b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/mxfp4/test_mxfp4.py @@ -0,0 +1,481 @@ +# Copyright 2025 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. + +import gc +import unittest +from unittest.mock import patch + +from transformers import AutoTokenizer, GptOssForCausalLM, Mxfp4Config +from transformers.testing_utils import ( + require_kernels, + require_torch, + require_torch_gpu, + require_torch_large_gpu, + require_triton, + slow, +) +from transformers.utils import ( + is_torch_available, +) + + +if is_torch_available(): + import torch + + +class Mxfp4ConfigTest(unittest.TestCase): + def test_basic_config_creation(self): + """Test basic configuration creation with default values""" + config = Mxfp4Config() + self.assertEqual(config.quant_method.value, "mxfp4") + self.assertIsNone(config.modules_to_not_convert) + self.assertFalse(config.dequantize) + + def test_config_with_modules_to_not_convert(self): + """Test configuration with modules to not convert""" + modules = ["model.layers.*.self_attn", "lm_head"] + config = Mxfp4Config(modules_to_not_convert=modules) + self.assertEqual(config.modules_to_not_convert, modules) + + def test_config_with_dequantize(self): + """Test configuration with dequantize enabled""" + config = Mxfp4Config(dequantize=True) + self.assertTrue(config.dequantize) + + def test_get_loading_attributes(self): + """Test get_loading_attributes method""" + config = Mxfp4Config(dequantize=True) + attrs = config.get_loading_attributes() + self.assertEqual(attrs, {"dequantize": True}) + + def test_to_dict(self): + """Test configuration serialization to dict""" + config = Mxfp4Config(modules_to_not_convert=["lm_head"], dequantize=True) + config_dict = config.to_dict() + self.assertEqual(config_dict["quant_method"], "mxfp4") + self.assertEqual(config_dict["modules_to_not_convert"], ["lm_head"]) + self.assertTrue(config_dict["dequantize"]) + + def test_from_dict(self): + """Test configuration creation from dict""" + config_dict = {"quant_method": "mxfp4", "modules_to_not_convert": ["lm_head"], "dequantize": True} + config = Mxfp4Config.from_dict(config_dict) + self.assertEqual(config.modules_to_not_convert, ["lm_head"]) + self.assertTrue(config.dequantize) + + +class Mxfp4QuantizerTest(unittest.TestCase): + """Test the Mxfp4HfQuantizer class""" + + def setUp(self): + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + def test_quantizer_validation_no_torch(self): + """Test quantizer validation when torch is not available""" + with patch("transformers.quantizers.quantizer_mxfp4.is_torch_available", return_value=False): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + + with self.assertRaises(ImportError): + quantizer.validate_environment() + + def test_quantizer_validation_no_cuda(self): + """Test quantizer validation when CUDA is not available""" + with patch("torch.cuda.is_available", return_value=False): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + + with self.assertRaises(RuntimeError): + quantizer.validate_environment() + + def test_quantizer_validation_low_compute_capability(self): + """Test quantizer validation with low compute capability""" + with patch("torch.cuda.get_device_capability", return_value=(7, 0)): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + quantizer.pre_quantized = False + + with self.assertRaises(ValueError): + quantizer.validate_environment() + + def test_quantizer_validation_low_compute_capability_with_prequantized(self): + """Test quantizer validation with low compute capability""" + with patch("torch.cuda.get_device_capability", return_value=(7, 0)): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + + # Should automatically set dequantize=True and warn + quantizer.validate_environment() + self.assertTrue(quantizer.quantization_config.dequantize) + + def test_quantizer_validation_low_compute_capability_with_dequantize(self): + """Test quantizer validation with low compute capability but dequantize enabled""" + with patch("torch.cuda.get_device_capability", return_value=(7, 0)): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config(dequantize=True) + quantizer = Mxfp4HfQuantizer(config) + + # Should not raise error with dequantize=True + try: + quantizer.validate_environment() + except ValueError as e: + if "compute capability" in str(e): + self.fail("Should not raise compute capability error when dequantize=True") + + def test_quantizer_validation_dequantize_on_cpu(self): + """Test quantizer validation with dequantize enabled on CPU-only environment""" + with patch("torch.cuda.is_available", return_value=False): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config(dequantize=True) + quantizer = Mxfp4HfQuantizer(config) + + # Should not raise error when dequantize=True even without CUDA + try: + quantizer.validate_environment() + except RuntimeError as e: + if "requires a GPU" in str(e): + self.fail("Should not raise GPU requirement error when dequantize=True on CPU") + + def test_quantizer_validation_order_dequantize_before_cuda_check(self): + """Test that dequantize check happens before CUDA availability check""" + # Mock both torch.cuda.is_available and is_accelerate_available to return False + with ( + patch("torch.cuda.is_available", return_value=False), + patch( + "transformers.quantizers.quantizer_mxfp4.is_accelerate_available", + return_value=False, + ), + ): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + # Test with dequantize=True - should pass even without CUDA and accelerate + config = Mxfp4Config(dequantize=True) + quantizer = Mxfp4HfQuantizer(config) + + # This should not raise any error because dequantize check comes first + try: + quantizer.validate_environment() + except (RuntimeError, ImportError) as e: + if "requires a GPU" in str(e) or "requires Accelerate" in str(e): + self.fail(f"Should not raise error when dequantize=True: {e}") + + # Test with dequantize=False - should still fail due to missing CUDA + config = Mxfp4Config(dequantize=False) + quantizer = Mxfp4HfQuantizer(config) + + with self.assertRaises(RuntimeError) as context: + quantizer.validate_environment() + self.assertIn("requires a GPU", str(context.exception)) + + def test_quantizer_validation_missing_triton(self): + """Test quantizer validation when triton is not available""" + with ( + patch("transformers.quantizers.quantizer_mxfp4.is_triton_available", return_value=False), + patch("transformers.quantizers.quantizer_mxfp4.is_kernels_availalble", return_value=False), + ): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + quantizer.pre_quantized = False + with self.assertRaises(ValueError): + quantizer.validate_environment() + + def test_quantizer_validation_missing_triton_pre_quantized_no_dequantize(self): + """Test quantizer validation when triton is not available but model is pre-quantized and dequantize is False""" + with ( + patch("transformers.quantizers.quantizer_mxfp4.is_triton_available", return_value=False), + patch("transformers.quantizers.quantizer_mxfp4.is_kernels_availalble", return_value=False), + ): + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + quantizer.pre_quantized = True + + # Should automatically set dequantize=True and warn + quantizer.validate_environment() + self.assertTrue(quantizer.quantization_config.dequantize) + + def test_update_torch_dtype(self): + """Test torch dtype updating""" + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + + # Should default to bfloat16 + result_dtype = quantizer.update_torch_dtype(None) + self.assertEqual(result_dtype, torch.bfloat16) + + # Should preserve existing dtype + result_dtype = quantizer.update_torch_dtype(torch.float32) + self.assertEqual(result_dtype, torch.float32) + + def test_update_expected_keys(self): + """Test expected keys updating for quantized models""" + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + + expected_keys = [ + "model.layers.0.mlp.experts.gate_up_proj", + "model.layers.0.mlp.experts.down_proj", + "model.embed_tokens.weight", + ] + + updated_keys = quantizer.update_expected_keys(None, expected_keys, []) + + expected_updated = [ + "model.layers.0.mlp.experts.gate_up_proj_blocks", + "model.layers.0.mlp.experts.gate_up_proj_scales", + "model.layers.0.mlp.experts.down_proj_blocks", + "model.layers.0.mlp.experts.down_proj_scales", + "model.embed_tokens.weight", + ] + + self.assertEqual(set(updated_keys), set(expected_updated)) + + def test_update_param_name_dequantize(self): + """Test parameter name updating when dequantizing""" + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config(dequantize=True) + quantizer = Mxfp4HfQuantizer(config) + + # Should remove _blocks suffix + param_name = "model.layers.0.mlp.experts.gate_up_proj_blocks" + updated_name = quantizer.update_param_name(param_name) + self.assertEqual(updated_name, "model.layers.0.mlp.experts.gate_up_proj") + + # Should remove _scales suffix + param_name = "model.layers.0.mlp.experts.down_proj_scales" + updated_name = quantizer.update_param_name(param_name) + self.assertEqual(updated_name, "model.layers.0.mlp.experts.down_proj") + + # Should not change other names + param_name = "model.embed_tokens.weight" + updated_name = quantizer.update_param_name(param_name) + self.assertEqual(updated_name, "model.embed_tokens.weight") + + def test_update_param_name_no_dequantize(self): + """Test parameter name updating when not dequantizing""" + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config(dequantize=False) + quantizer = Mxfp4HfQuantizer(config) + + param_name = "model.layers.0.mlp.experts.gate_up_proj_blocks" + updated_name = quantizer.update_param_name(param_name) + self.assertEqual(updated_name, param_name) + + def test_is_serializable(self): + """Test serialization capability""" + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + + # MXFP4 is not serializable with safetensors + self.assertFalse(quantizer.is_serializable()) + + def test_is_trainable(self): + """Test trainability""" + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + + # MXFP4 is not trainable + self.assertFalse(quantizer.is_trainable) + + +class Mxfp4IntegrationTest(unittest.TestCase): + """Test mxfp4 integration functions""" + + def test_should_convert_module(self): + """Test module conversion decision logic""" + from transformers.integrations.mxfp4 import should_convert_module + + # Should convert by default + self.assertTrue(should_convert_module(["model", "layers", "0", "mlp"], [])) + + # Should not convert if in exclusion list + patterns = ["model.layers.*.self_attn", "lm_head"] + self.assertFalse(should_convert_module(["model", "layers", "0", "self_attn"], patterns)) + self.assertFalse(should_convert_module(["lm_head"], patterns)) + + # Should convert if not in exclusion list + self.assertTrue(should_convert_module(["model", "layers", "0", "mlp", "experts"], patterns)) + + @require_torch + def test_convert_moe_packed_tensors(self): + """Test unpacking of quantized tensors""" + from transformers.integrations.mxfp4 import convert_moe_packed_tensors + + # Create dummy packed tensors + blocks = torch.randint(0, 255, (2, 4, 8), dtype=torch.uint8) + scales = torch.randint(100, 150, (2, 4), dtype=torch.uint8) + + result = convert_moe_packed_tensors(blocks, scales, dtype=torch.bfloat16) + + # Check output shape - should be [2, 4, 16] (8 * 2 for unpacking) + self.assertEqual(result.shape, (2, 4 * 16)) + self.assertEqual(result.dtype, torch.bfloat16) + + @require_triton(min_version="3.4.0") + @require_kernels + @require_torch_gpu + @require_torch + def test_quantize_to_mxfp4(self): + """Test quantization function""" + from transformers.integrations.mxfp4 import quantize_to_mxfp4 + + # Create dummy weight tensor + w = torch.randn(32, 64, 128, dtype=torch.bfloat16, device=torch.device("cuda")) + + quantized_w, flex_data, mx_ctx = quantize_to_mxfp4(w, None, None) + + # Check that shapes are reasonable + self.assertEqual(quantized_w.dtype, torch.uint8) + self.assertIsNotNone(flex_data) + self.assertIsNotNone(mx_ctx) + + +@require_torch +@require_torch_large_gpu +@require_triton(min_version="3.4.0") +@require_kernels +@slow +class Mxfp4ModelTest(unittest.TestCase): + """Test mxfp4 with actual models (requires specific model and hardware)""" + + # These should be paths to real OpenAI MoE models for proper testing + model_name = "openai/gpt-oss-20b" + + input_text = "Once upon a time" + + # Expected outputs for generation tests + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Once upon a time, in a small village, there lived a young") + + def setUp(self): + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + def tearDown(self): + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + + def check_inference_correctness_quantized(self, model, tokenizer): + # Check that inference pass works on the model + encoded_input = tokenizer(self.input_text, return_tensors="pt").to(model.device) + + # Set pad token if not set + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + with torch.no_grad(): + output_sequences = model.generate( + **encoded_input, + max_new_tokens=10, + do_sample=False, + pad_token_id=tokenizer.eos_token_id, + use_cache=False, + ) + + generated_text = tokenizer.decode(output_sequences[0], skip_special_tokens=True) + + self.assertIn(generated_text, self.EXPECTED_OUTPUTS) + + def test_gpt_oss_model_loading_quantized_with_device_map(self): + """Test loading OpenAI MoE model with mxfp4 quantization and device_map""" + + quantization_config = Mxfp4Config(dequantize=False) + + # Test that config is properly set up + self.assertFalse(quantization_config.dequantize) + + model = GptOssForCausalLM.from_pretrained( + self.model_name, + quantization_config=quantization_config, + torch_dtype=torch.bfloat16, + device_map="auto", + ) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + self.check_inference_correctness_quantized(model, tokenizer) + + def test_gpt_oss_model_loading_dequantized_with_device_map(self): + """Test loading OpenAI MoE model with mxfp4 dequantization and device_map""" + + quantization_config = Mxfp4Config(dequantize=True) + + # Test that config is properly set up + self.assertTrue(quantization_config.dequantize) + + model = GptOssForCausalLM.from_pretrained( + self.model_name, + quantization_config=quantization_config, + torch_dtype=torch.bfloat16, + device_map="auto", + ) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + self.check_inference_correctness_quantized(model, tokenizer) + + def test_model_device_map_validation(self): + """Test device map validation""" + from transformers.quantizers.quantizer_mxfp4 import Mxfp4HfQuantizer + + config = Mxfp4Config() + quantizer = Mxfp4HfQuantizer(config) + quantizer.pre_quantized = False + + # Test with CPU in device map (should raise error for non-pre-quantized) + with self.assertRaises(ValueError): + quantizer.validate_environment(device_map={"": "cpu"}) + + def test_memory_footprint_comparison(self): + """Test memory footprint differences between quantized and unquantized models""" + + # Expected: quantized < dequantized < unquantized memory usage + quantization_config = Mxfp4Config(dequantize=True) + quantized_model = GptOssForCausalLM.from_pretrained( + self.model_name, + torch_dtype=torch.bfloat16, + device_map="auto", + ) + dequantized_model = GptOssForCausalLM.from_pretrained( + self.model_name, + torch_dtype=torch.bfloat16, + device_map="auto", + quantization_config=quantization_config, + ) + quantized_mem = quantized_model.get_memory_footprint() + dequantized_mem = dequantized_model.get_memory_footprint() + self.assertLess(quantized_mem, dequantized_mem) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/test_quanto.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/test_quanto.py new file mode 100644 index 0000000000000000000000000000000000000000..5cc0814332aa09cb409ec25f6d62d5a5a9bc9c40 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quanto_integration/test_quanto.py @@ -0,0 +1,472 @@ +# 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. + +import tempfile +import unittest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, QuantoConfig +from transformers.testing_utils import ( + require_accelerate, + require_optimum_quanto, + require_read_token, + require_torch_accelerator, + slow, + torch_device, +) +from transformers.utils import is_accelerate_available, is_optimum_quanto_available, is_torch_available + + +if is_torch_available(): + import torch + + from transformers import LlamaForCausalLM + +if is_accelerate_available(): + from accelerate import init_empty_weights + +if is_optimum_quanto_available(): + from optimum.quanto import QLayerNorm, QLinear + + from transformers.integrations.quanto import replace_with_quanto_layers + + +class QuantoConfigTest(unittest.TestCase): + def test_attributes(self): + pass + + +@require_optimum_quanto +@require_accelerate +class QuantoTestIntegration(unittest.TestCase): + model_id = "facebook/opt-350m" + + def setUp(self): + config = AutoConfig.from_pretrained(self.model_id) + with init_empty_weights(): + self.model = AutoModelForCausalLM.from_config(config) + self.nb_linear = 0 + self.nb_layernorm = 0 + for module in self.model.modules(): + if isinstance(module, torch.nn.Linear): + self.nb_linear += 1 + elif isinstance(module, torch.nn.LayerNorm): + self.nb_layernorm += 1 + + def test_weight_only_quantization_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly when using weight only quantization + """ + + # Try with weight only quantization + quantization_config = QuantoConfig(weights="int8", activations=None) + self.model, _ = replace_with_quanto_layers(self.model, quantization_config=quantization_config) + + nb_qlinear = 0 + for module in self.model.modules(): + if isinstance(module, QLinear): + nb_qlinear += 1 + + self.assertEqual(self.nb_linear, nb_qlinear) + + def test_weight_and_activation_quantization_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly when using weight + activation quantization + """ + + # Try with weight + activation quantization + quantization_config = QuantoConfig(weights="int8", activations="int8") + self.model, _ = replace_with_quanto_layers(self.model, quantization_config=quantization_config) + + nb_qlinear = 0 + nb_qlayernorm = 0 + for module in self.model.modules(): + if isinstance(module, QLinear): + nb_qlinear += 1 + if isinstance(module, QLayerNorm): + nb_qlayernorm += 1 + + self.assertEqual(self.nb_linear, nb_qlinear) + self.assertEqual(self.nb_layernorm, nb_qlayernorm) + + def test_conversion_with_modules_to_not_convert(self): + """ + Simple test that checks if the quantized model has been converted properly when specifying modules_to_not_convert argument + """ + + # Try with weight + activatioin quantization + quantization_config = QuantoConfig(weights="int8", activations="int8") + self.model, _ = replace_with_quanto_layers( + self.model, quantization_config=quantization_config, modules_to_not_convert=["lm_head"] + ) + + nb_qlinear = 0 + nb_qlayernorm = 0 + for module in self.model.modules(): + if isinstance(module, QLinear): + nb_qlinear += 1 + if isinstance(module, QLayerNorm): + nb_qlayernorm += 1 + + self.assertEqual(self.nb_linear - 1, nb_qlinear) + + +@slow +@require_torch_accelerator +@require_optimum_quanto +@require_accelerate +class QuantoQuantizationTest(unittest.TestCase): + """ + Test 8-bit weights only quantization + """ + + model_name = "bigscience/bloom-560m" + + weights = "int8" + activations = None + device_map = "cpu" + + input_text = "Hello my name is" + EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer and I" + + def setUp(self): + """ + Setup quantized model + """ + quantization_config = QuantoConfig( + weights=self.weights, + activations=self.activations, + ) + + self.quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=self.device_map, + quantization_config=quantization_config, + torch_dtype=torch.float32, + ) + + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + self.have_accelerate_hooks = ( + getattr(self.quantized_model, "hf_device_map", False) and len(self.quantized_model.hf_device_map) > 1 + ) + + def check_inference_correctness(self, model, device): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + if not self.have_accelerate_hooks: + model.to(device) + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(device), max_new_tokens=10) + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality_cpu(self): + """ + Simple test to check the quality of the model on cpu by comparing the generated tokens with the expected tokens + """ + self.check_inference_correctness(self.quantized_model, "cpu") + + def test_generate_quality_accelerator(self): + """ + Simple test to check the quality of the model on accelerators by comparing the generated tokens with the expected tokens + """ + self.check_inference_correctness(self.quantized_model, torch_device) + + def test_quantized_model_layers(self): + from optimum.quanto import QBitsTensor, QModuleMixin, QTensor + + """ + Suite of simple test to check if the layers are quantized and are working properly + """ + # Test the type of the quantized layer + self.assertTrue(isinstance(self.quantized_model.transformer.h[0].self_attention.query_key_value, QModuleMixin)) + self.assertTrue( + isinstance(self.quantized_model.transformer.h[0].self_attention.query_key_value.weight, QTensor) + ) + if self.weights == "int4": + self.assertTrue( + isinstance(self.quantized_model.transformer.h[0].self_attention.query_key_value.weight, QBitsTensor) + ) + + # check that the lm_head was indeed not quantized, just like bnb + self.assertTrue( + isinstance(self.quantized_model.lm_head, torch.nn.Linear) + and not isinstance(self.quantized_model.lm_head, QModuleMixin) + ) + if self.device_map in ["cpu", "cuda"]: + self.assertEqual( + self.quantized_model.transformer.h[0].self_attention.query_key_value.weight._data.device.type, + self.device_map, + ) + self.quantized_model.to(0) + self.assertEqual( + self.quantized_model.transformer.h[0].self_attention.query_key_value.weight._data.device.type, torch_device + ) + + def test_serialization_bin(self): + """ + Test the serialization, the loading and the inference of the quantized weights + """ + with tempfile.TemporaryDirectory() as tmpdirname: + with self.assertRaises(ValueError) as e: + self.quantized_model.save_pretrained(tmpdirname, safe_serialization=False) + self.assertIn( + "The model is quantized with QuantizationMethod.QUANTO and is not serializable", str(e.exception) + ) + # TODO: replace by the following when it works + # quantized_model_from_saved = AutoModelForCausalLM.from_pretrained( + # tmpdirname, torch_dtype=torch.float32, device_map="cpu" + # ) + # self.check_inference_correctness(quantized_model_from_saved, device="cuda") + + def test_serialization_safetensors(self): + """ + Test the serialization, the loading and the inference of the quantized weights + """ + with tempfile.TemporaryDirectory() as tmpdirname: + with self.assertRaises(ValueError) as e: + self.quantized_model.save_pretrained(tmpdirname) + self.assertIn( + "The model is quantized with QuantizationMethod.QUANTO and is not serializable", str(e.exception) + ) + # quantized_model_from_saved = AutoModelForCausalLM.from_pretrained( + # tmpdirname, torch_dtype=torch.float32, device_map="cpu" + # ) + # self.check_inference_correctness(quantized_model_from_saved, device="cuda") + + def check_same_model(self, model1, model2): + d0 = dict(model1.named_parameters()) + d1 = dict(model2.named_parameters()) + self.assertTrue(d0.keys() == d1.keys()) + for k in d0: + self.assertTrue(d0[k].shape == d1[k].shape) + self.assertTrue(d0[k].device.type == d1[k].device.type) + self.assertTrue(d0[k].device == d1[k].device) + self.assertTrue(d0[k].dtype == d1[k].dtype) + self.assertTrue(torch.equal(d0[k], d1[k].to(d0[k].device))) + + def test_compare_with_quanto(self): + from optimum.quanto import freeze, qint4, qint8, quantize + + w_mapping = {"int8": qint8, "int4": qint4} + model = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=self.device_map, + torch_dtype=torch.float32, + ) + # we do not quantize the lm_head since we don't do that in transformers + quantize(model.transformer, weights=w_mapping[self.weights]) + freeze(model.transformer) + self.check_same_model(model, self.quantized_model) + self.check_inference_correctness(model, device=torch_device) + + @unittest.skip + def test_load_from_quanto_saved(self): + from optimum.quanto import freeze, qint4, qint8, quantize + + from transformers import QuantoConfig + + w_mapping = {"int8": qint8, "int4": qint4} + model = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=self.device_map, + torch_dtype=torch.float32, + ) + # we do not quantize the lm_head since we don't do that in transformers + quantize(model.transformer, weights=w_mapping[self.weights]) + freeze(model.transformer) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.config.quantization_config = QuantoConfig( + weights=self.weights, activations=self.activations, modules_to_not_convert=["lm_head"] + ) + model.save_pretrained(tmpdirname, safe_serialization=False) + quantized_model_from_saved = AutoModelForCausalLM.from_pretrained( + tmpdirname, + device_map=self.device_map, + torch_dtype=torch.float32, + ) + self.check_same_model(model, quantized_model_from_saved) + self.check_inference_correctness(quantized_model_from_saved, device="cuda") + + +class QuantoQuantizationOffloadTest(QuantoQuantizationTest): + device_map = { + "transformer.word_embeddings": 0, + "transformer.word_embeddings_layernorm": 0, + "transformer.ln_f": 0, + "transformer.h.0": 0, + "transformer.h.1": 0, + "transformer.h.2": 0, + "transformer.h.3": 0, + "transformer.h.4": 0, + "transformer.h.5": 0, + "transformer.h.6": 0, + "transformer.h.7": 0, + "transformer.h.8": 0, + "transformer.h.9": 0, + "transformer.h.10": 0, + "transformer.h.11": 0, + "transformer.h.12": 0, + "transformer.h.13": 0, + "transformer.h.14": 0, + "transformer.h.15": 0, + "transformer.h.16": 0, + "transformer.h.17": 0, + "transformer.h.18": 0, + "transformer.h.19": 0, + "transformer.h.20": 0, + "transformer.h.21": 0, + "transformer.h.22": "cpu", + "transformer.h.23": "disk", + "lm_head": 0, + } + + @unittest.skip(reason="The execution device is a gpu") + def test_generate_quality_cpu(self): + pass + + @unittest.skip(reason="We can't save offloaded values") + def test_serialization_bin(self): + pass + + @unittest.skip + def test_serialization_safetensors(self): + pass + + @unittest.skip + def test_compare_with_quanto(self): + pass + + @unittest.skip + def test_load_from_quanto_saved(self): + pass + + def test_check_offload_quantized(self): + """ + We check that we have unquantized value in the cpu and in the disk + """ + from optimum.quanto import QBitsTensor, QTensor + + cpu_weights = self.quantized_model.transformer.h[22].self_attention.query_key_value._hf_hook.weights_map[ + "weight" + ] + disk_weights = self.quantized_model.transformer.h[23].self_attention.query_key_value._hf_hook.weights_map[ + "weight" + ] + self.assertTrue(isinstance(cpu_weights, torch.Tensor) and not isinstance(cpu_weights, QTensor)) + self.assertTrue(isinstance(disk_weights, torch.Tensor) and not isinstance(disk_weights, QTensor)) + if self.weights == "int4": + self.assertTrue(isinstance(cpu_weights, torch.Tensor) and not isinstance(disk_weights, QBitsTensor)) + self.assertTrue(isinstance(disk_weights, torch.Tensor) and not isinstance(disk_weights, QBitsTensor)) + + +@unittest.skip(reason="Skipping test class because serialization is not supported yet") +class QuantoQuantizationSerializationTest(QuantoQuantizationTest): + """ + Perform the same tests as in QuantoQuantizationTest but with a serialized model. + """ + + def setUp(self): + """ + Setup quantized model + """ + quantization_config = QuantoConfig( + weights=self.weights, + activations=self.activations, + ) + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=self.device_map, + quantization_config=quantization_config, + torch_dtype=torch.float32, + ) + with tempfile.TemporaryDirectory() as tmpdirname: + quantized_model.save_pretrained(tmpdirname, safe_serialization=False) + self.quantized_model = AutoModelForCausalLM.from_pretrained( + tmpdirname, torch_dtype=torch.float32, device_map=self.device_map + ) + + self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + self.have_accelerate_hooks = ( + getattr(self.quantized_model, "hf_device_map", False) and len(self.quantized_model.hf_device_map) > 1 + ) + + +@unittest.skip(reason="Skipping test class because serialization is not supported yet") +class QuantoQuantizationSerializationCudaTest(QuantoQuantizationTest): + """ + Perform the same tests as in QuantoQuantizationTest but with model on cuda + """ + + device_map = "cuda:0" + + +class QuantoQuantizationQBitsTensorTest(QuantoQuantizationTest): + EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I" + weights = "int4" + + +class QuantoQuantizationQBitsTensorOffloadTest(QuantoQuantizationOffloadTest): + EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I" + weights = "int4" + + +@unittest.skip(reason="Skipping test class because serialization is not supported yet") +class QuantoQuantizationQBitsTensorSerializationTest(QuantoQuantizationSerializationTest): + EXPECTED_OUTPUTS = "Hello my name is John, I am a professional photographer, I" + weights = "int4" + + +@require_torch_accelerator +class QuantoQuantizationActivationTest(unittest.TestCase): + def test_quantize_activation(self): + quantization_config = QuantoConfig( + weights="int8", + activations="int8", + ) + with self.assertRaises(ValueError) as e: + AutoModelForCausalLM.from_pretrained("bigscience/bloom-560m", quantization_config=quantization_config) + self.assertIn("We don't support quantizing the activations with transformers library", str(e.exception)) + + +@require_optimum_quanto +@require_torch_accelerator +class QuantoKVCacheQuantizationTest(unittest.TestCase): + @slow + @require_read_token + def test_quantized_cache(self): + EXPECTED_TEXT_COMPLETION = [ + "Simply put, the theory of relativity states that 1) time and space are not absolute, but are relative to the observer, and 2) the laws of physics are the same everywhere in the universe. This means that the speed of light is", + "My favorite all time favorite condiment is ketchup. I love how it adds a sweet and tangy flavor to my food. I also enjoy using it as a dip for fries, burgers, and grilled meats. It's a classic condiment that never", + ] + + prompts = [ + "Simply put, the theory of relativity states that ", + "My favorite all time favorite condiment is ketchup.", + ] + tokenizer = AutoTokenizer.from_pretrained( + "unsloth/Llama-3.2-1B-Instruct", pad_token="", padding_side="left" + ) + model = LlamaForCausalLM.from_pretrained( + "unsloth/Llama-3.2-1B-Instruct", device_map="sequential", torch_dtype=torch.float16 + ) + inputs = tokenizer(prompts, return_tensors="pt", padding=True).to(torch_device) + + generated_ids = model.generate(**inputs, max_new_tokens=40, do_sample=False, cache_implementation="quantized") + text = tokenizer.batch_decode(generated_ids, skip_special_tokens=True) + self.assertEqual(EXPECTED_TEXT_COMPLETION, text) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/test_quark.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/test_quark.py new file mode 100644 index 0000000000000000000000000000000000000000..5a3f7d77f53c0702d373e68b8f018702eef61bfa --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/quark_integration/test_quark.py @@ -0,0 +1,153 @@ +# Copyright 2025 Advanced Micro Devices, Inc. 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. +import unittest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, GenerationConfig, QuarkConfig +from transformers.testing_utils import ( + cleanup, + is_torch_available, + require_accelerate, + require_quark, + require_torch_gpu, + require_torch_multi_gpu, + slow, + torch_device, +) +from transformers.utils.import_utils import is_quark_available + + +if is_torch_available(): + import torch + +if is_quark_available(): + from quark.torch.export.nn.modules.qparamslinear import QParamsLinear + + +@require_quark +class QuarkConfigTest(unittest.TestCase): + def test_commmon_args(self): + config = AutoConfig.from_pretrained("amd/Llama-3.1-8B-Instruct-w-int8-a-int8-sym-test") + QuarkConfig(**config.quantization_config) + + +@slow +@require_quark +@require_torch_gpu +class QuarkTest(unittest.TestCase): + reference_model_name = "unsloth/Meta-Llama-3.1-8B-Instruct" + quantized_model_name = "amd/Llama-3.1-8B-Instruct-w-int8-a-int8-sym-test" + + input_text = "Today I am in Paris and" + + EXPECTED_OUTPUTS = set() + EXPECTED_OUTPUTS.add("Today I am in Paris and I am not in Paris, France\nToday I am in Paris, Illinois") + EXPECTED_OUTPUTS.add("Today I am in Paris and I am enjoying the city of light. I am not just any ordinary Paris") + EXPECTED_OUTPUTS.add("Today I am in Paris and I am enjoying my day off! The sun is shining, the birds are") + EXPECTED_OUTPUTS.add("Today I am in Paris and I'm here to tell you about it. It's a beautiful day,") + EXPECTED_OUTPUTS.add("Today I am in Paris and I am not in Paris at all! I am not in Paris, but") + + EXPECTED_RELATIVE_DIFFERENCE = 1.66 + device_map = None + + @classmethod + def setUpClass(cls): + """ + Setup reference & quantized model + """ + cls.model_fp16 = AutoModelForCausalLM.from_pretrained( + cls.reference_model_name, torch_dtype=torch.float16, device_map=cls.device_map + ) + cls.mem_fp16 = cls.model_fp16.get_memory_footprint() + + cls.tokenizer = AutoTokenizer.from_pretrained(cls.reference_model_name, use_fast=True) + + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.quantized_model_name, + torch_dtype=torch.float16, + device_map=cls.device_map, + ) + + def tearDown(self): + r""" + TearDown function needs to be called at the end of each test to free the accelerator memory and cache, also to + avoid unexpected behaviors. Please see: https://discuss.pytorch.org/t/how-can-we-release-gpu-memory-cache/14530/27 + """ + cleanup(torch_device, gc_collect=True) + + def test_memory_footprint(self): + mem_quantized = self.quantized_model.get_memory_footprint() + + self.assertTrue(self.mem_fp16 / mem_quantized > self.EXPECTED_RELATIVE_DIFFERENCE) + + def test_device_and_dtype_assignment(self): + r""" + Test whether trying to cast (or assigning a device to) a model after quantization will throw an error. + Checks also if other models are casted correctly . + """ + # This should work + if self.device_map is None: + _ = self.quantized_model.to(0) + + with self.assertRaises(ValueError): + # Tries with a `dtype`` + self.quantized_model.to(torch.float16) + + def test_original_dtype(self): + r""" + A simple test to check if the model successfully stores the original dtype + """ + self.assertTrue(hasattr(self.quantized_model.config, "_pre_quantization_dtype")) + self.assertFalse(hasattr(self.model_fp16.config, "_pre_quantization_dtype")) + self.assertTrue(self.quantized_model.config._pre_quantization_dtype == torch.float16) + + self.assertTrue(isinstance(self.quantized_model.model.layers[0].mlp.gate_proj, QParamsLinear)) + + def check_inference_correctness(self, model): + r""" + Test the generation quality of the quantized model and see that we are matching the expected output. + Given that we are operating on small numbers + the testing model is relatively small, we might not get + the same output across GPUs. So we'll generate few tokens (5-10) and check their output. + """ + # Check that inference pass works on the model + encoded_input = self.tokenizer(self.input_text, return_tensors="pt") + + gen_config = GenerationConfig( + max_new_tokens=15, + min_new_tokens=15, + use_cache=True, + num_beams=1, + do_sample=False, + ) + + # Check the exactness of the results + output_sequences = model.generate(input_ids=encoded_input["input_ids"].to(0), generation_config=gen_config) + + # Get the generation + self.assertIn(self.tokenizer.decode(output_sequences[0], skip_special_tokens=True), self.EXPECTED_OUTPUTS) + + def test_generate_quality(self): + """ + Simple test to check the quality of the model by comparing the generated tokens with the expected tokens + """ + if self.device_map is None: + self.check_inference_correctness(self.quantized_model.to(0)) + else: + self.check_inference_correctness(self.quantized_model) + + +@require_accelerate +@require_torch_multi_gpu +@require_quark +class QuarkTestDeviceMap(QuarkTest): + device_map = "auto" diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/test_spqr.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/test_spqr.py new file mode 100644 index 0000000000000000000000000000000000000000..973ecd6e7db48a4845571abfb8a5f0b5bd80d9e0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/spqr_integration/test_spqr.py @@ -0,0 +1,246 @@ +# 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. + +import gc +import tempfile +import unittest + +import pytest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, SpQRConfig, StaticCache +from transformers.testing_utils import ( + backend_empty_cache, + require_accelerate, + require_spqr, + require_torch_gpu, + require_torch_multi_gpu, + slow, + torch_device, +) +from transformers.utils import is_accelerate_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_accelerate_available(): + from accelerate import init_empty_weights + + +@require_torch_gpu +class SpQRConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Simple test that checks if one uses a config and converts it to a dict, the dict is the same as the config object + """ + quantization_config = SpQRConfig() + config_to_dict = quantization_config.to_dict() + + for key in config_to_dict: + self.assertEqual(getattr(quantization_config, key), config_to_dict[key]) + + def test_from_dict(self): + """ + Simple test that checks if one uses a dict and converts it to a config object, the config object is the same as the dict + """ + dict = { + "beta1": 16, + "beta2": 16, + "bits": 3, + "modules_to_not_convert": ["lm_head.weight"], + "shapes": {"model.layers.0.self_attn.q_proj.dense_weights.shape": 16}, + } + quantization_config = SpQRConfig.from_dict(dict) + + self.assertEqual(dict["beta1"], quantization_config.beta1) + self.assertEqual(dict["beta2"], quantization_config.beta2) + self.assertEqual(dict["bits"], quantization_config.bits) + self.assertEqual(dict["modules_to_not_convert"], quantization_config.modules_to_not_convert) + self.assertEqual(dict["shapes"], quantization_config.shapes) + + +@slow +@require_torch_gpu +@require_spqr +@require_accelerate +class SpQRTest(unittest.TestCase): + model_name = "elvircrn/Llama-2-7b-SPQR-3Bit-16x16-red_pajama-hf" + + input_text = "Hello my name is" + max_new_tokens = 32 + + EXPECTED_OUTPUT = ( + "Hello my name is Jesse. (I'm also known as Jesse) I'm a 25 year old male from United States. I'm looking for" + ) + EXPECTED_OUTPUT_COMPILE = "Hello my name is Jake and I am a 20 year old student at the University of North Texas. (Go Mean Green!) I am a huge fan of the Dallas" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + device_map=torch_device, + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_quantized_model_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly + """ + from spqr_quant import QuantizedLinear + + from transformers.integrations import replace_with_spqr_linear + + model_id = "meta-llama/Llama-2-7b-hf" + config = AutoConfig.from_pretrained(model_id) + quantization_config = AutoConfig.from_pretrained(self.model_name, return_dict=False).quantization_config + quantization_config = SpQRConfig.from_dict(quantization_config) + + with init_empty_weights(): + model = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path=model_id, config=config) + + nb_linears = 0 + for module in model.modules(): + if isinstance(module, torch.nn.Linear): + nb_linears += 1 + + model, _ = replace_with_spqr_linear( + model, + quantization_config=quantization_config, + modules_to_not_convert=quantization_config.modules_to_not_convert, + ) + + nb_spqr_linear = 0 + for module in model.modules(): + if isinstance(module, QuantizedLinear): + nb_spqr_linear += 1 + + self.assertEqual(nb_linears - 1, nb_spqr_linear) + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_raise_if_non_quantized(self): + model_id = "meta-llama/Llama-2-7b-hf" + quantization_config = SpQRConfig() + + with self.assertRaises(ValueError): + _ = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config) + + @unittest.skip + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=torch_device) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_quantized_model_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly with multiple GPUs + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + quantized_model = AutoModelForCausalLM.from_pretrained(self.model_name, device_map="auto") + + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @pytest.mark.torch_compile_test + def test_quantized_model_compile(self): + """ + Simple test that checks if the quantized model is working properly + """ + + # Sample tokens greedily + def decode_one_tokens(model, cur_token, input_pos, cache_position, past_key_values): + logits = model( + cur_token, + position_ids=input_pos, + cache_position=cache_position, + past_key_values=past_key_values, + return_dict=False, + use_cache=True, + )[0] + new_token = torch.argmax(logits[:, [-1]], dim=-1).to(torch.int) + + return new_token + + # Tokenize the test input + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device)["input_ids"] + seq_length = input_ids.shape[1] + + # Setup static KV cache for generation + past_key_values = StaticCache( + config=self.quantized_model.config, max_cache_len=seq_length + self.max_new_tokens + 1 + ) + + # Allocate token ids to be generated and copy prefix ids + cache_position = torch.arange(seq_length, device=torch_device) + generated_ids = torch.zeros(1, seq_length + self.max_new_tokens, dtype=torch.int, device=torch_device) + generated_ids[:, cache_position] = input_ids.to(torch_device).to(torch.int) + + # Do a forward pass to fill the prefix cache and compile the kernels if necessary + logits = self.quantized_model( + input_ids, + cache_position=cache_position, + past_key_values=past_key_values, + return_dict=False, + use_cache=True, + )[0] + next_token = torch.argmax(logits[:, [-1]], dim=-1).to(torch.int) + generated_ids[:, [seq_length]] = next_token + + with torch.no_grad(): + # Compile the CUDA graph + decode_one_tokens = torch.compile(decode_one_tokens, mode="default", backend="inductor", fullgraph=True) + + # Generate tokens one by one + cache_position = torch.tensor([seq_length + 1], device=torch_device) + for _ in range(1, self.max_new_tokens): + with torch.backends.cuda.sdp_kernel(enable_flash=False, enable_mem_efficient=False, enable_math=True): + next_token = decode_one_tokens( + self.quantized_model, next_token.clone(), None, cache_position, past_key_values + ) + generated_ids.index_copy_(1, cache_position, next_token) + cache_position += 1 + + # Check generated text + self.assertEqual( + self.tokenizer.decode(generated_ids[0], skip_special_tokens=True), self.EXPECTED_OUTPUT_COMPILE + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/test_torchao.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/test_torchao.py new file mode 100644 index 0000000000000000000000000000000000000000..2bd4cce834f33d7fc5123b67c7edaf304190ce56 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/torchao_integration/test_torchao.py @@ -0,0 +1,592 @@ +# 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. + +import gc +import importlib.metadata +import tempfile +import unittest + +from packaging import version + +from transformers import AutoModelForCausalLM, AutoTokenizer, TorchAoConfig +from transformers.testing_utils import ( + Expectations, + backend_empty_cache, + get_device_properties, + require_torch_accelerator, + require_torch_multi_accelerator, + require_torchao, + require_torchao_version_greater_or_equal, + torch_device, +) +from transformers.utils import is_torch_available, is_torchao_available + + +if is_torch_available(): + import torch + +if is_torchao_available(): + # renamed in torchao 0.7.0, please install the latest torchao + from torchao.dtypes import ( + AffineQuantizedTensor, + TensorCoreTiledLayout, + ) + from torchao.quantization import ( + Int8WeightOnlyConfig, + IntxWeightOnlyConfig, + MappingType, + ModuleFqnToConfig, + PerAxis, + ) + from torchao.quantization.autoquant import AQMixin + + if version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0"): + from torchao.dtypes import Int4CPULayout + if version.parse(importlib.metadata.version("torchao")) >= version.parse("0.11.0"): + from torchao.dtypes import Int4XPULayout + + +def check_torchao_int4_wo_quantized(test_module, qlayer): + weight = qlayer.weight + test_module.assertEqual(weight.quant_min, 0) + test_module.assertEqual(weight.quant_max, 15) + test_module.assertTrue(isinstance(weight, AffineQuantizedTensor)) + layout = None + if weight.device.type == "cpu": + layout = Int4CPULayout + elif weight.device.type == "xpu": + layout = Int4XPULayout + elif weight.device.type == "cuda": + layout = TensorCoreTiledLayout + test_module.assertTrue(isinstance(weight.tensor_impl._layout, layout)) + + +def check_autoquantized(test_module, qlayer): + weight = qlayer.weight + test_module.assertTrue(isinstance(weight, AQMixin)) + + +def check_forward(test_module, model, batch_size=1, context_size=1024): + # Test forward pass + with torch.no_grad(): + out = model(torch.zeros([batch_size, context_size], device=model.device, dtype=torch.int32)).logits + test_module.assertEqual(out.shape[0], batch_size) + test_module.assertEqual(out.shape[1], context_size) + + +@require_torchao +@require_torchao_version_greater_or_equal("0.8.0") +class TorchAoConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Makes sure the config format is properly set + """ + quantization_config = TorchAoConfig("int4_weight_only") + torchao_orig_config = quantization_config.to_dict() + + for key in torchao_orig_config: + self.assertEqual(getattr(quantization_config, key), torchao_orig_config[key]) + + def test_post_init_check(self): + """ + Test kwargs validations in TorchAoConfig + """ + _ = TorchAoConfig("int4_weight_only") + with self.assertRaisesRegex(ValueError, "Unsupported string quantization type"): + _ = TorchAoConfig("fp6") + + with self.assertRaisesRegex(ValueError, "Unexpected keyword arg"): + _ = TorchAoConfig("int4_weight_only", group_size1=32) + + def test_repr(self): + """ + Check that there is no error in the repr + """ + quantization_config = TorchAoConfig("int4_weight_only", modules_to_not_convert=["conv"], group_size=8) + repr(quantization_config) + + def test_json_serializable(self): + """ + Check that the config dict can be JSON serialized. + """ + quantization_config = TorchAoConfig("int4_weight_only", group_size=32, layout=TensorCoreTiledLayout()) + d = quantization_config.to_dict() + self.assertIsInstance(d["quant_type_kwargs"]["layout"], list) + self.assertTrue("inner_k_tiles" in d["quant_type_kwargs"]["layout"][1]) + quantization_config.to_json_string(use_diff=False) + + +@require_torchao +@require_torchao_version_greater_or_equal("0.8.0") +class TorchAoTest(unittest.TestCase): + input_text = "What are we having for dinner?" + max_new_tokens = 10 + model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" + device = "cpu" + quant_scheme_kwargs = ( + {"group_size": 32, "layout": Int4CPULayout()} + if is_torchao_available() and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0") + else {"group_size": 32} + ) + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + cls.EXPECTED_OUTPUT = "What are we having for dinner?\n- 1. What is the temperature outside" + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_int4wo_quant(self): + """ + Simple LLM model testing int4 weight only quantization + """ + quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs) + + # Note: we quantize the bfloat16 model on the fly to int4 + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + torch_dtype=torch.bfloat16, + device_map=self.device, + quantization_config=quant_config, + ) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + check_torchao_int4_wo_quantized(self, quantized_model.model.layers[0].self_attn.v_proj) + + input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_int4wo_quant_bfloat16_conversion(self): + """ + Testing the dtype of model will be modified to be bfloat16 for int4 weight only quantization + """ + quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs) + + # Note: we quantize the bfloat16 model on the fly to int4 + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + torch_dtype=torch.bfloat16, + device_map=self.device, + quantization_config=quant_config, + ) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + check_torchao_int4_wo_quantized(self, quantized_model.model.layers[0].self_attn.v_proj) + + input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_int8_dynamic_activation_int8_weight_quant(self): + """ + Simple LLM model testing int8_dynamic_activation_int8_weight + """ + quant_config = TorchAoConfig("int8_dynamic_activation_int8_weight") + + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=self.device, + quantization_config=quant_config, + ) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + EXPECTED_OUTPUT = [ + "What are we having for dinner?\n\nJessica: (smiling)", + "What are we having for dinner?\n\nJess: (smiling) I", + ] + self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT) + + @require_torchao_version_greater_or_equal("0.11.0") + def test_include_input_output_embeddings(self): + weight_dtype = torch.int8 + granularity = PerAxis(0) + mapping_type = MappingType.ASYMMETRIC + embedding_config = IntxWeightOnlyConfig( + weight_dtype=weight_dtype, + granularity=granularity, + mapping_type=mapping_type, + ) + config = ModuleFqnToConfig( + {"_default": None, "model.embed_tokens": embedding_config, "lm_head": embedding_config} + ) + # need set `include_input_output_embeddings` to True + quant_config = TorchAoConfig(quant_type=config, include_input_output_embeddings=True) + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=self.device, + quantization_config=quant_config, + ) + # making sure embedding is quantized + self.assertTrue(isinstance(quantized_model.model.embed_tokens.weight, AffineQuantizedTensor)) + self.assertTrue(isinstance(quantized_model.lm_head.weight, AffineQuantizedTensor)) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + EXPECTED_OUTPUT = [ + "What are we having for dinner?\n\nJessica: (smiling)", + "What are we having for dinner?\n\nJess: (smiling) I", + ] + self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT) + + @require_torchao_version_greater_or_equal("0.11.0") + def test_per_module_config_skip(self): + linear_config = Int8WeightOnlyConfig() + config = ModuleFqnToConfig({"_default": linear_config, "model.layers.0.self_attn.q_proj": None}) + quant_config = TorchAoConfig(quant_type=config) + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + device_map=self.device, + quantization_config=quant_config, + ) + # making sure `model.layers.0.self_attn.q_proj` is skipped + self.assertTrue(not isinstance(quantized_model.model.layers[0].self_attn.q_proj.weight, AffineQuantizedTensor)) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + EXPECTED_OUTPUT = [ + "What are we having for dinner?\n\nJessica: (smiling)", + "What are we having for dinner?\n\nJess: (smiling) I", + ] + self.assertTrue(tokenizer.decode(output[0], skip_special_tokens=True) in EXPECTED_OUTPUT) + + +@require_torch_accelerator +class TorchAoAcceleratorTest(TorchAoTest): + device = torch_device + quant_scheme_kwargs = {"group_size": 32} + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + super().setUpClass() + # fmt: off + EXPECTED_OUTPUTS = Expectations( + { + ("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)", + ("cuda", 7): "What are we having for dinner?\n- 1. What is the temperature outside", + } + ) + # fmt: on + cls.EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation() + + def test_int4wo_offload(self): + """ + Simple test that checks if the quantized model int4 weight only is working properly with cpu/disk offload + """ + + device_map_offload = { + "model.embed_tokens": 0, + "model.layers.0": 0, + "model.layers.1": 0, + "model.layers.2": 0, + "model.layers.3": 0, + "model.layers.4": 0, + "model.layers.5": 0, + "model.layers.6": 0, + "model.layers.7": 0, + "model.layers.8": 0, + "model.layers.9": 0, + "model.layers.10": 0, + "model.layers.11": 0, + "model.layers.12": 0, + "model.layers.13": 0, + "model.layers.14": 0, + "model.layers.15": 0, + "model.layers.16": 0, + "model.layers.17": 0, + "model.layers.18": 0, + "model.layers.19": "cpu", + "model.layers.20": "cpu", + "model.layers.21": "disk", + "model.norm": 0, + "model.rotary_emb": 0, + "lm_head": 0, + } + + quant_config = TorchAoConfig("int4_weight_only", group_size=32) + + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + torch_dtype=torch.bfloat16, + device_map=device_map_offload, + quantization_config=quant_config, + ) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) + + # fmt: off + EXPECTED_OUTPUTS = Expectations( + { + ("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)", + ("cuda", 7): "What are we having for dinner?\n- 2. What is the temperature outside", + } + ) + # fmt: on + EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation() + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + generated_text = tokenizer.decode(output[0], skip_special_tokens=True) + + self.assertEqual(generated_text, EXPECTED_OUTPUT) + + @require_torch_multi_accelerator + def test_int4wo_quant_multi_accelerator(self): + """ + Simple test that checks if the quantized model int4 weight only is working properly with multiple accelerators + set CUDA_VISIBLE_DEVICES=0,1 if you have more than 2 CUDA GPUs + set ZE_AFFINITY_MASK=0,1 if you have more than 2 Intel XPUs + """ + + quant_config = TorchAoConfig("int4_weight_only", **self.quant_scheme_kwargs) + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + torch_dtype=torch.bfloat16, + device_map="auto", + quantization_config=quant_config, + ) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_autoquant(self): + """ + Simple LLM model testing autoquant + """ + quant_config = TorchAoConfig("autoquant") + + quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + torch_dtype="auto", + device_map=self.device, + quantization_config=quant_config, + ) + tokenizer = AutoTokenizer.from_pretrained(self.model_name) + input_ids = tokenizer(self.input_text, return_tensors="pt").to(self.device) + output = quantized_model.generate( + **input_ids, max_new_tokens=self.max_new_tokens, cache_implementation="static" + ) + quantized_model.finalize_autoquant() + + check_autoquantized(self, quantized_model.model.layers[0].self_attn.v_proj) + + EXPECTED_OUTPUT = "What are we having for dinner?\n\nJane: (sighs)" + output = quantized_model.generate( + **input_ids, max_new_tokens=self.max_new_tokens, cache_implementation="static" + ) + self.assertEqual(tokenizer.decode(output[0], skip_special_tokens=True), EXPECTED_OUTPUT) + + +@require_torchao +@require_torchao_version_greater_or_equal("0.8.0") +class TorchAoSerializationTest(unittest.TestCase): + input_text = "What are we having for dinner?" + max_new_tokens = 10 + model_name = "TinyLlama/TinyLlama-1.1B-Chat-v1.0" + quant_scheme = "int4_weight_only" + quant_scheme_kwargs = ( + {"group_size": 32, "layout": Int4CPULayout()} + if is_torchao_available() and version.parse(importlib.metadata.version("torchao")) >= version.parse("0.8.0") + else {"group_size": 32} + ) + device = "cpu" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.EXPECTED_OUTPUT = "What are we having for dinner?\n- 1. What is the temperature outside" + + def setUp(self): + self.quant_config = TorchAoConfig(self.quant_scheme, **self.quant_scheme_kwargs) + torch_dtype = torch.bfloat16 if self.quant_scheme == "int4_weight_only" else "auto" + self.quantized_model = AutoModelForCausalLM.from_pretrained( + self.model_name, + torch_dtype=torch_dtype, + device_map=self.device, + quantization_config=self.quant_config, + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_original_model_expected_output(self): + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(self.device) + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def check_serialization_expected_output(self, device, expected_output): + """ + Test if we can serialize and load/infer the model again on the same device + """ + torch_dtype = torch.bfloat16 if self.quant_scheme == "int4_weight_only" else "auto" + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname, safe_serialization=False) + loaded_quantized_model = AutoModelForCausalLM.from_pretrained( + tmpdirname, torch_dtype=torch_dtype, device_map=device + ) + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(device) + + output = loaded_quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), expected_output) + + def test_serialization_expected_output(self): + self.check_serialization_expected_output(self.device, self.EXPECTED_OUTPUT) + + +class TorchAoSerializationW8A8CPUTest(TorchAoSerializationTest): + quant_scheme, quant_scheme_kwargs = "int8_dynamic_activation_int8_weight", {} + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" + + @require_torch_accelerator + def test_serialization_expected_output_on_accelerator(self): + """ + Test if we can serialize on device (cpu) and load/infer the model on accelerator + """ + self.check_serialization_expected_output(torch_device, self.EXPECTED_OUTPUT) + + +class TorchAoSerializationW8CPUTest(TorchAoSerializationTest): + quant_scheme, quant_scheme_kwargs = "int8_weight_only", {} + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" + + @require_torch_accelerator + def test_serialization_expected_output_on_accelerator(self): + """ + Test if we can serialize on device (cpu) and load/infer the model on accelerator + """ + self.check_serialization_expected_output(torch_device, self.EXPECTED_OUTPUT) + + +@require_torch_accelerator +class TorchAoSerializationAcceleratorTest(TorchAoSerializationTest): + quant_scheme, quant_scheme_kwargs = "int4_weight_only", {"group_size": 32} + device = f"{torch_device}:0" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + super().setUpClass() + # fmt: off + EXPECTED_OUTPUTS = Expectations( + { + ("xpu", 3): "What are we having for dinner?\n\nJessica: (smiling)", + ("cuda", 7): "What are we having for dinner?\n- 1. What is the temperature outside", + } + ) + # fmt: on + cls.EXPECTED_OUTPUT = EXPECTED_OUTPUTS.get_expectation() + + +@require_torch_accelerator +class TorchAoSerializationW8A8AcceleratorTest(TorchAoSerializationTest): + quant_scheme, quant_scheme_kwargs = "int8_dynamic_activation_int8_weight", {} + device = f"{torch_device}:0" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" + + +@require_torch_accelerator +class TorchAoSerializationW8AcceleratorTest(TorchAoSerializationTest): + quant_scheme, quant_scheme_kwargs = "int8_weight_only", {} + device = f"{torch_device}:0" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" + + +@require_torch_accelerator +@require_torchao_version_greater_or_equal("0.10.0") +class TorchAoSerializationFP8AcceleratorTest(TorchAoSerializationTest): + device = f"{torch_device}:0" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + device_type, major, minor = get_device_properties() + if device_type == "cuda" and major < 9: + raise unittest.SkipTest("CUDA compute capability 9.0 or higher required for FP8 tests") + + from torchao.quantization import Float8WeightOnlyConfig + + cls.quant_scheme = Float8WeightOnlyConfig() + cls.quant_scheme_kwargs = {} + + super().setUpClass() + + cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" + + +@require_torch_accelerator +@require_torchao_version_greater_or_equal("0.10.0") +class TorchAoSerializationA8W4Test(TorchAoSerializationTest): + device = f"{torch_device}:0" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + device_type, major, minor = get_device_properties() + if device_type == "cuda" and major < 9: + raise unittest.SkipTest("CUDA compute capability 9.0 or higher required for FP8 tests") + + from torchao.quantization import Int8DynamicActivationInt4WeightConfig + + cls.quant_scheme = Int8DynamicActivationInt4WeightConfig() + cls.quant_scheme_kwargs = {} + + super().setUpClass() + + cls.EXPECTED_OUTPUT = "What are we having for dinner?\n\nJessica: (smiling)" + + +if __name__ == "__main__": + unittest.main() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/test_vptq.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/test_vptq.py new file mode 100644 index 0000000000000000000000000000000000000000..0f9e03d4b748f5decbb629de64e9e3ab376b8a20 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/quantization/vptq_integration/test_vptq.py @@ -0,0 +1,194 @@ +# 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. + +import gc +import tempfile +import unittest + +from transformers import AutoConfig, AutoModelForCausalLM, AutoTokenizer, VptqConfig +from transformers.testing_utils import ( + backend_empty_cache, + require_accelerate, + require_torch_gpu, + require_torch_multi_gpu, + require_vptq, + slow, + torch_device, +) +from transformers.utils import is_accelerate_available, is_torch_available + + +if is_torch_available(): + import torch + +if is_accelerate_available(): + from accelerate import init_empty_weights + + +class VptqConfigTest(unittest.TestCase): + def test_to_dict(self): + """ + Makes sure the config format is properly set + """ + quantization_config = VptqConfig() + vptq_orig_config = quantization_config.to_dict() + + self.assertEqual(vptq_orig_config["quant_method"], quantization_config.quant_method) + + +@slow +@require_torch_gpu +@require_vptq +@require_accelerate +class VptqTest(unittest.TestCase): + model_name = "VPTQ-community/Meta-Llama-3.1-8B-Instruct-v12-k65536-4096-woft" + + input_text = "Hello my name is" + max_new_tokens = 32 + + EXPECTED_OUTPUT = "Hello my name is Sarah and I am a 25 year old woman from the United States. I am a college graduate and I am currently working as a marketing specialist for a small" + + device_map = "cuda" + + # called only once for all test in this class + @classmethod + def setUpClass(cls): + """ + Setup quantized model + """ + cls.tokenizer = AutoTokenizer.from_pretrained(cls.model_name) + cls.quantized_model = AutoModelForCausalLM.from_pretrained( + cls.model_name, + device_map=cls.device_map, + ) + + def tearDown(self): + gc.collect() + backend_empty_cache(torch_device) + gc.collect() + + def test_quantized_model(self): + """ + Simple test that checks if the quantized model is working properly + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = self.quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_raise_if_non_quantized(self): + model_id = "facebook/opt-125m" + quantization_config = VptqConfig() + + with self.assertRaises(ValueError): + _ = AutoModelForCausalLM.from_pretrained(model_id, quantization_config=quantization_config) + + def test_save_pretrained(self): + """ + Simple test that checks if the quantized model is working properly after being saved and loaded + """ + with tempfile.TemporaryDirectory() as tmpdirname: + self.quantized_model.save_pretrained(tmpdirname) + model = AutoModelForCausalLM.from_pretrained(tmpdirname, device_map=self.device_map) + + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + output = model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + @require_torch_multi_gpu + def test_quantized_model_multi_gpu(self): + """ + Simple test that checks if the quantized model is working properly with multiple GPUs + """ + input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) + + quantized_model = AutoModelForCausalLM.from_pretrained(self.model_name, device_map="auto") + + self.assertTrue(set(quantized_model.hf_device_map.values()) == {0, 1}) + + output = quantized_model.generate(**input_ids, max_new_tokens=self.max_new_tokens, do_sample=False) + + self.assertEqual(self.tokenizer.decode(output[0], skip_special_tokens=True), self.EXPECTED_OUTPUT) + + def test_quantized_model_conversion(self): + """ + Simple test that checks if the quantized model has been converted properly + """ + from vptq import VQuantLinear + + from transformers.integrations import replace_with_vptq_linear + + model_id = "facebook/opt-350m" + config = AutoConfig.from_pretrained(model_id, revision="cb32f77e905cccbca1d970436fb0f5e6b58ee3c5") + modules_to_not_convert = ["lm_head"] + names = [ + "q_proj", + "k_proj", + "v_proj", + "out_proj", + "fc1", + "fc2", + ] + value = { + "enable_norm": True, + "enable_perm": True, + "group_num": 1, + "group_size": 128, + "indices_as_float": False, + "num_centroids": [-1, 128], + "num_res_centroids": [-1, 128], + "outlier_size": 0, + "vector_lens": [-1, 12], + } + shared_layer_config = {} + for name in names: + shared_layer_config[name] = value + for i in range(24): + modules_to_not_convert.append(f"model.decoder.layers.{i}.fc1") + layer_configs = {} + layer_configs["model.decoder.project_out"] = value + layer_configs["model.decoder.project_in"] = value + quantization_config = VptqConfig(config_for_layers=layer_configs, shared_layer_config=shared_layer_config) + + with init_empty_weights(): + model = AutoModelForCausalLM.from_config(config) + + nb_linears = 0 + for module in model.modules(): + if isinstance(module, torch.nn.Linear): + nb_linears += 1 + + model, _ = replace_with_vptq_linear(model, quantization_config=quantization_config) + nb_vptq_linear = 0 + for module in model.modules(): + if isinstance(module, VQuantLinear): + nb_vptq_linear += 1 + + self.assertEqual(nb_linears - 1, nb_vptq_linear) + + # Try with `linear_weights_not_to_quantize` + with init_empty_weights(): + model = AutoModelForCausalLM.from_config(config) + quantization_config = VptqConfig(config_for_layers=layer_configs, shared_layer_config=shared_layer_config) + model, _ = replace_with_vptq_linear( + model, quantization_config=quantization_config, modules_to_not_convert=modules_to_not_convert + ) + nb_vptq_linear = 0 + for module in model.modules(): + if isinstance(module, VQuantLinear): + nb_vptq_linear += 1 + # 25 comes from 24 decoder.layers.{layer_idx}.fc1 + # and the last lm_head + self.assertEqual(nb_linears - 25, nb_vptq_linear) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/modular/test_conversion_order.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/modular/test_conversion_order.py new file mode 100644 index 0000000000000000000000000000000000000000..65d31c2203c21dccc2f75f7b23313274982ba5e1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/modular/test_conversion_order.py @@ -0,0 +1,74 @@ +import os +import sys +import unittest + + +ROOT_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(ROOT_DIR, "utils")) + +import create_dependency_mapping # noqa: E402 + + +# This is equivalent to `all` in the current library state (as of 09/01/2025) +MODEL_ROOT = os.path.join("src", "transformers", "models") +FILES_TO_PARSE = [ + os.path.join(MODEL_ROOT, "starcoder2", "modular_starcoder2.py"), + os.path.join(MODEL_ROOT, "gemma", "modular_gemma.py"), + os.path.join(MODEL_ROOT, "olmo2", "modular_olmo2.py"), + os.path.join(MODEL_ROOT, "diffllama", "modular_diffllama.py"), + os.path.join(MODEL_ROOT, "granite", "modular_granite.py"), + os.path.join(MODEL_ROOT, "gemma2", "modular_gemma2.py"), + os.path.join(MODEL_ROOT, "mixtral", "modular_mixtral.py"), + os.path.join(MODEL_ROOT, "olmo", "modular_olmo.py"), + os.path.join(MODEL_ROOT, "rt_detr", "modular_rt_detr.py"), + os.path.join(MODEL_ROOT, "qwen2", "modular_qwen2.py"), + os.path.join(MODEL_ROOT, "qwen3", "modular_qwen3.py"), + os.path.join(MODEL_ROOT, "llava_next_video", "modular_llava_next_video.py"), + os.path.join(MODEL_ROOT, "cohere2", "modular_cohere2.py"), + os.path.join(MODEL_ROOT, "modernbert", "modular_modernbert.py"), + os.path.join(MODEL_ROOT, "colpali", "modular_colpali.py"), + os.path.join(MODEL_ROOT, "deformable_detr", "modular_deformable_detr.py"), + os.path.join(MODEL_ROOT, "aria", "modular_aria.py"), + os.path.join(MODEL_ROOT, "ijepa", "modular_ijepa.py"), + os.path.join(MODEL_ROOT, "bamba", "modular_bamba.py"), + os.path.join(MODEL_ROOT, "dinov2_with_registers", "modular_dinov2_with_registers.py"), + os.path.join(MODEL_ROOT, "instructblipvideo", "modular_instructblipvideo.py"), + os.path.join(MODEL_ROOT, "glm", "modular_glm.py"), + os.path.join(MODEL_ROOT, "phi", "modular_phi.py"), + os.path.join(MODEL_ROOT, "mistral", "modular_mistral.py"), + os.path.join(MODEL_ROOT, "phi3", "modular_phi3.py"), + os.path.join(MODEL_ROOT, "cohere", "modular_cohere.py"), + os.path.join(MODEL_ROOT, "glm4", "modular_glm4.py"), +] + + +def appear_after(model1: str, model2: str, priority_list: list[list[str]]) -> bool: + """Return True if `model1` appear after `model2` in `priority_list`.""" + model1_index, model2_index = None, None + for i, level in enumerate(priority_list): + if model1 in level: + model1_index = i + if model2 in level: + model2_index = i + if model1_index is None or model2_index is None: + raise ValueError(f"Model {model1} or {model2} not found in {priority_list}") + return model1_index > model2_index + + +class ConversionOrderTest(unittest.TestCase): + def test_conversion_order(self): + # Find the order + priority_list, _ = create_dependency_mapping.find_priority_list(FILES_TO_PARSE) + # Extract just the model names (list of lists) + model_priority_list = [[file.split("/")[-2] for file in level] for level in priority_list] + + # These are based on what the current library order should be (as of 09/01/2025) + self.assertTrue(appear_after("mixtral", "mistral", model_priority_list)) + self.assertTrue(appear_after("gemma2", "gemma", model_priority_list)) + self.assertTrue(appear_after("starcoder2", "mistral", model_priority_list)) + self.assertTrue(appear_after("olmo2", "olmo", model_priority_list)) + self.assertTrue(appear_after("diffllama", "mistral", model_priority_list)) + self.assertTrue(appear_after("cohere2", "gemma2", model_priority_list)) + self.assertTrue(appear_after("cohere2", "cohere", model_priority_list)) + self.assertTrue(appear_after("phi3", "mistral", model_priority_list)) + self.assertTrue(appear_after("glm4", "glm", model_priority_list)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_copies.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_copies.py new file mode 100644 index 0000000000000000000000000000000000000000..f6ae669c4cc1ac17a2bda915fb93d7d815f975d8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_copies.py @@ -0,0 +1,454 @@ +# 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. + +import os +import shutil +import sys +import tempfile +import unittest +from contextlib import contextmanager +from pathlib import Path + + +git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(git_repo_path, "utils")) + +import check_copies # noqa: E402 +from check_copies import convert_to_localized_md, find_code_in_transformers, is_copy_consistent # noqa: E402 + + +# This is the reference code that will be used in the tests. +# If BertLMPredictionHead is changed in modeling_bert.py, this code needs to be manually updated. +REFERENCE_CODE = """ def __init__(self, config): + super().__init__() + self.transform = BertPredictionHeadTransform(config) + + # The output weights are the same as the input embeddings, but there is + # an output-only bias for each token. + self.decoder = nn.Linear(config.hidden_size, config.vocab_size, bias=False) + + self.bias = nn.Parameter(torch.zeros(config.vocab_size)) + + # Need a link between the two variables so that the bias is correctly resized with `resize_token_embeddings` + self.decoder.bias = self.bias + + def forward(self, hidden_states): + hidden_states = self.transform(hidden_states) + hidden_states = self.decoder(hidden_states) + return hidden_states +""" + +MOCK_BERT_CODE = """from ...modeling_utils import PreTrainedModel + +def bert_function(x): + return x + + +class BertAttention(nn.Module): + def __init__(self, config): + super().__init__() + + +class BertModel(BertPreTrainedModel): + def __init__(self, config): + super().__init__() + self.bert = BertEncoder(config) + + @add_docstring(BERT_DOCSTRING) + def forward(self, x): + return self.bert(x) +""" + +MOCK_BERT_COPY_CODE = """from ...modeling_utils import PreTrainedModel + +# Copied from transformers.models.bert.modeling_bert.bert_function +def bert_copy_function(x): + return x + + +# Copied from transformers.models.bert.modeling_bert.BertAttention +class BertCopyAttention(nn.Module): + def __init__(self, config): + super().__init__() + + +# Copied from transformers.models.bert.modeling_bert.BertModel with Bert->BertCopy all-casing +class BertCopyModel(BertCopyPreTrainedModel): + def __init__(self, config): + super().__init__() + self.bertcopy = BertCopyEncoder(config) + + @add_docstring(BERTCOPY_DOCSTRING) + def forward(self, x): + return self.bertcopy(x) +""" + + +MOCK_DUMMY_BERT_CODE_MATCH = """ +class BertDummyModel: + attr_1 = 1 + attr_2 = 2 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def existing_common(self, c): + return 4 + + def existing_diff_to_be_ignored(self, c): + return 9 +""" + + +MOCK_DUMMY_ROBERTA_CODE_MATCH = """ +# Copied from transformers.models.dummy_bert_match.modeling_dummy_bert_match.BertDummyModel with BertDummy->RobertaBertDummy +class RobertaBertDummyModel: + + attr_1 = 1 + attr_2 = 2 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Ignore copy + def only_in_roberta_to_be_ignored(self, c): + return 3 + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def existing_common(self, c): + return 4 + + # Ignore copy + def existing_diff_to_be_ignored(self, c): + return 6 +""" + + +MOCK_DUMMY_BERT_CODE_NO_MATCH = """ +class BertDummyModel: + attr_1 = 1 + attr_2 = 2 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def only_in_bert(self, c): + return 7 + + def existing_common(self, c): + return 4 + + def existing_diff_not_ignored(self, c): + return 8 + + def existing_diff_to_be_ignored(self, c): + return 9 +""" + + +MOCK_DUMMY_ROBERTA_CODE_NO_MATCH = """ +# Copied from transformers.models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel with BertDummy->RobertaBertDummy +class RobertaBertDummyModel: + + attr_1 = 1 + attr_2 = 3 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Ignore copy + def only_in_roberta_to_be_ignored(self, c): + return 3 + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def only_in_roberta_not_ignored(self, c): + return 2 + + def existing_common(self, c): + return 4 + + def existing_diff_not_ignored(self, c): + return 5 + + # Ignore copy + def existing_diff_to_be_ignored(self, c): + return 6 +""" + + +EXPECTED_REPLACED_CODE = """ +# Copied from transformers.models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel with BertDummy->RobertaBertDummy +class RobertaBertDummyModel: + attr_1 = 1 + attr_2 = 2 + + def __init__(self, a=1, b=2): + self.a = a + self.b = b + + # Copied from transformers.models.dummy_gpt2.modeling_dummy_gpt2.GPT2DummyModel.forward + def forward(self, c): + return 1 + + def only_in_bert(self, c): + return 7 + + def existing_common(self, c): + return 4 + + def existing_diff_not_ignored(self, c): + return 8 + + # Ignore copy + def existing_diff_to_be_ignored(self, c): + return 6 + + # Ignore copy + def only_in_roberta_to_be_ignored(self, c): + return 3 +""" + + +def replace_in_file(filename, old, new): + with open(filename, encoding="utf-8") as f: + content = f.read() + + content = content.replace(old, new) + + with open(filename, "w", encoding="utf-8", newline="\n") as f: + f.write(content) + + +def create_tmp_repo(tmp_dir): + """ + Creates a mock repository in a temporary folder for testing. + """ + tmp_dir = Path(tmp_dir) + if tmp_dir.exists(): + shutil.rmtree(tmp_dir) + tmp_dir.mkdir(exist_ok=True) + + model_dir = tmp_dir / "src" / "transformers" / "models" + model_dir.mkdir(parents=True, exist_ok=True) + + models = { + "bert": MOCK_BERT_CODE, + "bertcopy": MOCK_BERT_COPY_CODE, + "dummy_bert_match": MOCK_DUMMY_BERT_CODE_MATCH, + "dummy_roberta_match": MOCK_DUMMY_ROBERTA_CODE_MATCH, + "dummy_bert_no_match": MOCK_DUMMY_BERT_CODE_NO_MATCH, + "dummy_roberta_no_match": MOCK_DUMMY_ROBERTA_CODE_NO_MATCH, + } + for model, code in models.items(): + model_subdir = model_dir / model + model_subdir.mkdir(exist_ok=True) + with open(model_subdir / f"modeling_{model}.py", "w", encoding="utf-8", newline="\n") as f: + f.write(code) + + +@contextmanager +def patch_transformer_repo_path(new_folder): + """ + Temporarily patches the variables defines in `check_copies` to use a different location for the repo. + """ + old_repo_path = check_copies.REPO_PATH + old_doc_path = check_copies.PATH_TO_DOCS + old_transformer_path = check_copies.TRANSFORMERS_PATH + repo_path = Path(new_folder).resolve() + check_copies.REPO_PATH = str(repo_path) + check_copies.PATH_TO_DOCS = str(repo_path / "docs" / "source" / "en") + check_copies.TRANSFORMERS_PATH = str(repo_path / "src" / "transformers") + try: + yield + finally: + check_copies.REPO_PATH = old_repo_path + check_copies.PATH_TO_DOCS = old_doc_path + check_copies.TRANSFORMERS_PATH = old_transformer_path + + +class CopyCheckTester(unittest.TestCase): + def test_find_code_in_transformers(self): + with tempfile.TemporaryDirectory() as tmp_folder: + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + code = find_code_in_transformers("models.bert.modeling_bert.BertAttention") + + reference_code = ( + "class BertAttention(nn.Module):\n def __init__(self, config):\n super().__init__()\n" + ) + self.assertEqual(code, reference_code) + + def test_is_copy_consistent(self): + path_to_check = ["src", "transformers", "models", "bertcopy", "modeling_bertcopy.py"] + with tempfile.TemporaryDirectory() as tmp_folder: + # Base check + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + file_to_check = os.path.join(tmp_folder, *path_to_check) + diffs = is_copy_consistent(file_to_check) + self.assertEqual(diffs, []) + + # Base check with an inconsistency + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + file_to_check = os.path.join(tmp_folder, *path_to_check) + + replace_in_file(file_to_check, "self.bertcopy(x)", "self.bert(x)") + diffs = is_copy_consistent(file_to_check) + self.assertEqual(diffs, [["models.bert.modeling_bert.BertModel", 22]]) + + _ = is_copy_consistent(file_to_check, overwrite=True) + + with open(file_to_check, encoding="utf-8") as f: + self.assertEqual(f.read(), MOCK_BERT_COPY_CODE) + + def test_is_copy_consistent_with_ignored_match(self): + path_to_check = ["src", "transformers", "models", "dummy_roberta_match", "modeling_dummy_roberta_match.py"] + with tempfile.TemporaryDirectory() as tmp_folder: + # Base check + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + file_to_check = os.path.join(tmp_folder, *path_to_check) + diffs = is_copy_consistent(file_to_check) + self.assertEqual(diffs, []) + + def test_is_copy_consistent_with_ignored_no_match(self): + path_to_check = [ + "src", + "transformers", + "models", + "dummy_roberta_no_match", + "modeling_dummy_roberta_no_match.py", + ] + with tempfile.TemporaryDirectory() as tmp_folder: + # Base check with an inconsistency + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + file_to_check = os.path.join(tmp_folder, *path_to_check) + + diffs = is_copy_consistent(file_to_check) + # line 6: `attr_2 = 3` in `MOCK_DUMMY_ROBERTA_CODE_NO_MATCH`. + # (which has a leading `\n`.) + self.assertEqual( + diffs, [["models.dummy_bert_no_match.modeling_dummy_bert_no_match.BertDummyModel", 6]] + ) + + _ = is_copy_consistent(file_to_check, overwrite=True) + + with open(file_to_check, encoding="utf-8") as f: + self.assertEqual(f.read(), EXPECTED_REPLACED_CODE) + + def test_convert_to_localized_md(self): + localized_readme = check_copies.LOCALIZED_READMES["README_zh-hans.md"] + + md_list = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" + " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" + " Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong" + " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut.\n1." + " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (from HuggingFace)," + " released together with the paper [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" + " lighter](https://huggingface.co/papers/1910.01108) by Victor Sanh, Lysandre Debut and Thomas Wolf. The same" + " method has been applied to compress GPT2 into" + " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" + " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," + " Multilingual BERT into" + " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" + " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)**" + " (from Google Research/Stanford University) released with the paper [ELECTRA: Pre-training text encoders" + " as discriminators rather than generators](https://huggingface.co/papers/2003.10555) by Kevin Clark, Minh-Thang" + " Luong, Quoc V. Le, Christopher D. Manning." + ) + localized_md_list = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" + " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" + " Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" + " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" + ) + converted_md_list_sample = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" + " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" + " Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" + " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n1." + " **[DistilBERT](https://huggingface.co/transformers/model_doc/distilbert.html)** (来自 HuggingFace) 伴随论文" + " [DistilBERT, a distilled version of BERT: smaller, faster, cheaper and" + " lighter](https://huggingface.co/papers/1910.01108) 由 Victor Sanh, Lysandre Debut and Thomas Wolf 发布。 The same" + " method has been applied to compress GPT2 into" + " [DistilGPT2](https://github.com/huggingface/transformers/tree/main/examples/distillation), RoBERTa into" + " [DistilRoBERTa](https://github.com/huggingface/transformers/tree/main/examples/distillation)," + " Multilingual BERT into" + " [DistilmBERT](https://github.com/huggingface/transformers/tree/main/examples/distillation) and a German" + " version of DistilBERT.\n1. **[ELECTRA](https://huggingface.co/transformers/model_doc/electra.html)** (来自" + " Google Research/Stanford University) 伴随论文 [ELECTRA: Pre-training text encoders as discriminators rather" + " than generators](https://huggingface.co/papers/2003.10555) 由 Kevin Clark, Minh-Thang Luong, Quoc V. Le," + " Christopher D. Manning 发布。\n" + ) + + num_models_equal, converted_md_list = convert_to_localized_md( + md_list, localized_md_list, localized_readme["format_model_list"] + ) + + self.assertFalse(num_models_equal) + self.assertEqual(converted_md_list, converted_md_list_sample) + + num_models_equal, converted_md_list = convert_to_localized_md( + md_list, converted_md_list, localized_readme["format_model_list"] + ) + + # Check whether the number of models is equal to README.md after conversion. + self.assertTrue(num_models_equal) + + link_changed_md_list = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (from Google Research and the" + " Toyota Technological Institute at Chicago) released with the paper [ALBERT: A Lite BERT for" + " Self-supervised Learning of Language Representations](https://huggingface.co/papers/1909.11942), by Zhenzhong" + " Lan, Mingda Chen, Sebastian Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut." + ) + link_unchanged_md_list = ( + "1. **[ALBERT](https://huggingface.co/transformers/main/model_doc/albert.html)** (来自 Google Research and" + " the Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" + " Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" + " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" + ) + converted_md_list_sample = ( + "1. **[ALBERT](https://huggingface.co/transformers/model_doc/albert.html)** (来自 Google Research and the" + " Toyota Technological Institute at Chicago) 伴随论文 [ALBERT: A Lite BERT for Self-supervised Learning of" + " Language Representations](https://huggingface.co/papers/1909.11942), 由 Zhenzhong Lan, Mingda Chen, Sebastian" + " Goodman, Kevin Gimpel, Piyush Sharma, Radu Soricut 发布。\n" + ) + + num_models_equal, converted_md_list = convert_to_localized_md( + link_changed_md_list, link_unchanged_md_list, localized_readme["format_model_list"] + ) + + # Check if the model link is synchronized. + self.assertEqual(converted_md_list, converted_md_list_sample) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_docstrings.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..f761514a084d0087cfddb8306803f5e654f668d1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_check_docstrings.py @@ -0,0 +1,98 @@ +# 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. + +import inspect +import os +import sys +import unittest + + +git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(git_repo_path, "utils")) + +from check_docstrings import get_default_description, replace_default_in_arg_description # noqa: E402 + + +class CheckDostringsTested(unittest.TestCase): + def test_replace_default_in_arg_description(self): + # Standard docstring with default. + desc_with_default = "`float`, *optional*, defaults to 2.0" + self.assertEqual( + replace_default_in_arg_description(desc_with_default, 2.0), "`float`, *optional*, defaults to 2.0" + ) + self.assertEqual( + replace_default_in_arg_description(desc_with_default, 1.0), "`float`, *optional*, defaults to 1.0" + ) + self.assertEqual(replace_default_in_arg_description(desc_with_default, inspect._empty), "`float`") + + # Standard docstring with default but optional is not using the stars. + desc_with_default_typo = "`float`, `optional`, defaults to 2.0" + self.assertEqual( + replace_default_in_arg_description(desc_with_default_typo, 2.0), "`float`, *optional*, defaults to 2.0" + ) + self.assertEqual( + replace_default_in_arg_description(desc_with_default_typo, 1.0), "`float`, *optional*, defaults to 1.0" + ) + + # If the default is None we do not erase the value in the docstring. + self.assertEqual( + replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*, defaults to 2.0" + ) + # If the default is None (and set as such in the docstring), we do not include it. + desc_with_default = "`float`, *optional*, defaults to None" + self.assertEqual(replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*") + desc_with_default = "`float`, *optional*, defaults to `None`" + self.assertEqual(replace_default_in_arg_description(desc_with_default, None), "`float`, *optional*") + + # Operations are not replaced, but put in backtiks. + desc_with_default = "`float`, *optional*, defaults to 1/255" + self.assertEqual( + replace_default_in_arg_description(desc_with_default, 1 / 255), "`float`, *optional*, defaults to `1/255`" + ) + desc_with_default = "`float`, *optional*, defaults to `1/255`" + self.assertEqual( + replace_default_in_arg_description(desc_with_default, 1 / 255), "`float`, *optional*, defaults to `1/255`" + ) + + desc_with_optional = "`float`, *optional*" + self.assertEqual( + replace_default_in_arg_description(desc_with_optional, 2.0), "`float`, *optional*, defaults to 2.0" + ) + self.assertEqual( + replace_default_in_arg_description(desc_with_optional, 1.0), "`float`, *optional*, defaults to 1.0" + ) + self.assertEqual(replace_default_in_arg_description(desc_with_optional, None), "`float`, *optional*") + self.assertEqual(replace_default_in_arg_description(desc_with_optional, inspect._empty), "`float`") + + desc_with_no_optional = "`float`" + self.assertEqual( + replace_default_in_arg_description(desc_with_no_optional, 2.0), "`float`, *optional*, defaults to 2.0" + ) + self.assertEqual( + replace_default_in_arg_description(desc_with_no_optional, 1.0), "`float`, *optional*, defaults to 1.0" + ) + self.assertEqual(replace_default_in_arg_description(desc_with_no_optional, None), "`float`, *optional*") + self.assertEqual(replace_default_in_arg_description(desc_with_no_optional, inspect._empty), "`float`") + + def test_get_default_description(self): + # Fake function to have arguments to test. + def _fake_function(a, b: int, c=1, d: float = 2.0, e: str = "blob"): + pass + + params = inspect.signature(_fake_function).parameters + assert get_default_description(params["a"]) == "``" + assert get_default_description(params["b"]) == "`int`" + assert get_default_description(params["c"]) == "``, *optional*, defaults to 1" + assert get_default_description(params["d"]) == "`float`, *optional*, defaults to 2.0" + assert get_default_description(params["e"]) == '`str`, *optional*, defaults to `"blob"`' diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_get_test_info.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_get_test_info.py new file mode 100644 index 0000000000000000000000000000000000000000..b478cb1b7625e5f100b5b87535201d1cdb060f8a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_get_test_info.py @@ -0,0 +1,108 @@ +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. + +import os +import sys +import unittest + + +git_repo_path = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(git_repo_path, "utils")) + +import get_test_info # noqa: E402 +from get_test_info import ( # noqa: E402 + get_model_to_test_mapping, + get_model_to_tester_mapping, + get_test_to_tester_mapping, +) + + +BERT_TEST_FILE = os.path.join("tests", "models", "bert", "test_modeling_bert.py") +BLIP_TEST_FILE = os.path.join("tests", "models", "blip", "test_modeling_blip.py") + + +class GetTestInfoTester(unittest.TestCase): + def test_get_test_to_tester_mapping(self): + bert_test_tester_mapping = get_test_to_tester_mapping(BERT_TEST_FILE) + blip_test_tester_mapping = get_test_to_tester_mapping(BLIP_TEST_FILE) + + EXPECTED_BERT_MAPPING = {"BertModelTest": "BertModelTester"} + + EXPECTED_BLIP_MAPPING = { + "BlipModelTest": "BlipModelTester", + "BlipTextImageModelTest": "BlipTextImageModelsModelTester", + "BlipTextModelTest": "BlipTextModelTester", + "BlipTextRetrievalModelTest": "BlipTextRetrievalModelTester", + "BlipVQAModelTest": "BlipVQAModelTester", + "BlipVisionModelTest": "BlipVisionModelTester", + } + + self.assertEqual(get_test_info.to_json(bert_test_tester_mapping), EXPECTED_BERT_MAPPING) + self.assertEqual(get_test_info.to_json(blip_test_tester_mapping), EXPECTED_BLIP_MAPPING) + + def test_get_model_to_test_mapping(self): + bert_model_test_mapping = get_model_to_test_mapping(BERT_TEST_FILE) + blip_model_test_mapping = get_model_to_test_mapping(BLIP_TEST_FILE) + + EXPECTED_BERT_MAPPING = { + "BertForMaskedLM": ["BertModelTest"], + "BertForMultipleChoice": ["BertModelTest"], + "BertForNextSentencePrediction": ["BertModelTest"], + "BertForPreTraining": ["BertModelTest"], + "BertForQuestionAnswering": ["BertModelTest"], + "BertForSequenceClassification": ["BertModelTest"], + "BertForTokenClassification": ["BertModelTest"], + "BertLMHeadModel": ["BertModelTest"], + "BertModel": ["BertModelTest"], + } + + EXPECTED_BLIP_MAPPING = { + "BlipForConditionalGeneration": ["BlipTextImageModelTest"], + "BlipForImageTextRetrieval": ["BlipTextRetrievalModelTest"], + "BlipForQuestionAnswering": ["BlipVQAModelTest"], + "BlipModel": ["BlipModelTest"], + "BlipTextModel": ["BlipTextModelTest"], + "BlipVisionModel": ["BlipVisionModelTest"], + } + + self.assertEqual(get_test_info.to_json(bert_model_test_mapping), EXPECTED_BERT_MAPPING) + self.assertEqual(get_test_info.to_json(blip_model_test_mapping), EXPECTED_BLIP_MAPPING) + + def test_get_model_to_tester_mapping(self): + bert_model_tester_mapping = get_model_to_tester_mapping(BERT_TEST_FILE) + blip_model_tester_mapping = get_model_to_tester_mapping(BLIP_TEST_FILE) + + EXPECTED_BERT_MAPPING = { + "BertForMaskedLM": ["BertModelTester"], + "BertForMultipleChoice": ["BertModelTester"], + "BertForNextSentencePrediction": ["BertModelTester"], + "BertForPreTraining": ["BertModelTester"], + "BertForQuestionAnswering": ["BertModelTester"], + "BertForSequenceClassification": ["BertModelTester"], + "BertForTokenClassification": ["BertModelTester"], + "BertLMHeadModel": ["BertModelTester"], + "BertModel": ["BertModelTester"], + } + + EXPECTED_BLIP_MAPPING = { + "BlipForConditionalGeneration": ["BlipTextImageModelsModelTester"], + "BlipForImageTextRetrieval": ["BlipTextRetrievalModelTester"], + "BlipForQuestionAnswering": ["BlipVQAModelTester"], + "BlipModel": ["BlipModelTester"], + "BlipTextModel": ["BlipTextModelTester"], + "BlipVisionModel": ["BlipVisionModelTester"], + } + + self.assertEqual(get_test_info.to_json(bert_model_tester_mapping), EXPECTED_BERT_MAPPING) + self.assertEqual(get_test_info.to_json(blip_model_tester_mapping), EXPECTED_BLIP_MAPPING) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_tests_fetcher.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_tests_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..8f3f64c1a25c47e53bb5d3467ab7c7d629b11e64 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/repo_utils/test_tests_fetcher.py @@ -0,0 +1,788 @@ +# 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. + +import os +import shutil +import sys +import tempfile +import unittest +from contextlib import contextmanager +from pathlib import Path + +from git import Repo + +from transformers.testing_utils import CaptureStdout + + +REPO_PATH = os.path.abspath(os.path.dirname(os.path.dirname(os.path.dirname(__file__)))) +sys.path.append(os.path.join(REPO_PATH, "utils")) + +import tests_fetcher # noqa: E402 +from tests_fetcher import ( # noqa: E402 + checkout_commit, + clean_code, + create_reverse_dependency_map, + create_reverse_dependency_tree, + diff_is_docstring_only, + extract_imports, + get_all_tests, + get_diff, + get_module_dependencies, + get_tree_starting_at, + infer_tests_to_run, + init_test_examples_dependencies, + parse_commit_message, + print_tree_deps_of, +) + + +BERT_MODELING_FILE = "src/transformers/models/bert/modeling_bert.py" +BERT_MODEL_FILE = """from ...modeling_utils import PreTrainedModel +from ...utils import is_torch_available +from .configuration_bert import BertConfig + +class BertModel: + ''' + This is the docstring. + ''' + This is the code +""" + +BERT_MODEL_FILE_NEW_DOCSTRING = """from ...modeling_utils import PreTrainedModel +from ...utils import is_torch_available +from .configuration_bert import BertConfig + +class BertModel: + ''' + This is the docstring. It has been updated. + ''' + This is the code +""" + +BERT_MODEL_FILE_NEW_CODE = """from ...modeling_utils import PreTrainedModel +from ...utils import is_torch_available +from .configuration_bert import BertConfig + +class BertModel: + ''' + This is the docstring. + ''' + This is the code. It has been updated +""" + + +def create_tmp_repo(tmp_dir, models=None): + """ + Creates a repository in a temporary directory mimicking the structure of Transformers. Uses the list of models + provided (which defaults to just `["bert"]`). + """ + tmp_dir = Path(tmp_dir) + if tmp_dir.exists(): + shutil.rmtree(tmp_dir) + tmp_dir.mkdir(exist_ok=True) + repo = Repo.init(tmp_dir) + + if models is None: + models = ["bert"] + class_names = [model[0].upper() + model[1:] for model in models] + + transformers_dir = tmp_dir / "src" / "transformers" + transformers_dir.mkdir(parents=True, exist_ok=True) + with open(transformers_dir / "__init__.py", "w") as f: + init_lines = ["from .utils import cached_file, is_torch_available"] + init_lines.extend( + [f"from .models.{model} import {cls}Config, {cls}Model" for model, cls in zip(models, class_names)] + ) + f.write("\n".join(init_lines) + "\n") + with open(transformers_dir / "configuration_utils.py", "w") as f: + f.write("from .utils import cached_file\n\ncode") + with open(transformers_dir / "modeling_utils.py", "w") as f: + f.write("from .utils import cached_file\n\ncode") + + utils_dir = tmp_dir / "src" / "transformers" / "utils" + utils_dir.mkdir(exist_ok=True) + with open(utils_dir / "__init__.py", "w") as f: + f.write("from .hub import cached_file\nfrom .imports import is_torch_available\n") + with open(utils_dir / "hub.py", "w") as f: + f.write("import huggingface_hub\n\ncode") + with open(utils_dir / "imports.py", "w") as f: + f.write("code") + + model_dir = tmp_dir / "src" / "transformers" / "models" + model_dir.mkdir(parents=True, exist_ok=True) + with open(model_dir / "__init__.py", "w") as f: + f.write("\n".join([f"import {model}" for model in models])) + + for model, cls in zip(models, class_names): + model_dir = tmp_dir / "src" / "transformers" / "models" / model + model_dir.mkdir(parents=True, exist_ok=True) + with open(model_dir / "__init__.py", "w") as f: + f.write(f"from .configuration_{model} import {cls}Config\nfrom .modeling_{model} import {cls}Model\n") + with open(model_dir / f"configuration_{model}.py", "w") as f: + f.write("from ...configuration_utils import PretrainedConfig\ncode") + with open(model_dir / f"modeling_{model}.py", "w") as f: + modeling_code = BERT_MODEL_FILE.replace("bert", model).replace("Bert", cls) + f.write(modeling_code) + + test_dir = tmp_dir / "tests" + test_dir.mkdir(exist_ok=True) + with open(test_dir / "test_modeling_common.py", "w") as f: + f.write("from transformers.modeling_utils import PreTrainedModel\ncode") + + for model, cls in zip(models, class_names): + test_model_dir = test_dir / "models" / model + test_model_dir.mkdir(parents=True, exist_ok=True) + (test_model_dir / "__init__.py").touch() + with open(test_model_dir / f"test_modeling_{model}.py", "w") as f: + f.write( + f"from transformers import {cls}Config, {cls}Model\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode" + ) + + example_dir = tmp_dir / "examples" + example_dir.mkdir(exist_ok=True) + for framework in ["flax", "pytorch", "tensorflow"]: + framework_dir = example_dir / framework + framework_dir.mkdir(exist_ok=True) + with open(framework_dir / f"test_{framework}_examples.py", "w") as f: + f.write("""test_args = "run_glue.py"\n""") + glue_dir = framework_dir / "text-classification" + glue_dir.mkdir(exist_ok=True) + with open(glue_dir / "run_glue.py", "w") as f: + f.write("from transformers import BertModel\n\ncode") + + repo.index.add(["examples", "src", "tests"]) + repo.index.commit("Initial commit") + repo.create_head("main") + repo.head.reference = repo.refs.main + repo.delete_head("master") + return repo + + +@contextmanager +def patch_transformer_repo_path(new_folder): + """ + Temporarily patches the variables defines in `tests_fetcher` to use a different location for the repo. + """ + old_repo_path = tests_fetcher.PATH_TO_REPO + tests_fetcher.PATH_TO_REPO = Path(new_folder).resolve() + tests_fetcher.PATH_TO_EXAMPLES = tests_fetcher.PATH_TO_REPO / "examples" + tests_fetcher.PATH_TO_TRANFORMERS = tests_fetcher.PATH_TO_REPO / "src/transformers" + tests_fetcher.PATH_TO_TESTS = tests_fetcher.PATH_TO_REPO / "tests" + try: + yield + finally: + tests_fetcher.PATH_TO_REPO = old_repo_path + tests_fetcher.PATH_TO_EXAMPLES = tests_fetcher.PATH_TO_REPO / "examples" + tests_fetcher.PATH_TO_TRANFORMERS = tests_fetcher.PATH_TO_REPO / "src/transformers" + tests_fetcher.PATH_TO_TESTS = tests_fetcher.PATH_TO_REPO / "tests" + + +def commit_changes(filenames, contents, repo, commit_message="Commit"): + """ + Commit new `contents` to `filenames` inside a given `repo`. + """ + if not isinstance(filenames, list): + filenames = [filenames] + if not isinstance(contents, list): + contents = [contents] + + folder = Path(repo.working_dir) + for filename, content in zip(filenames, contents): + with open(folder / filename, "w") as f: + f.write(content) + repo.index.add(filenames) + commit = repo.index.commit(commit_message) + return commit.hexsha + + +class TestFetcherTester(unittest.TestCase): + def test_checkout_commit(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + repo = create_tmp_repo(tmp_folder) + initial_sha = repo.head.commit.hexsha + new_sha = commit_changes(BERT_MODELING_FILE, BERT_MODEL_FILE_NEW_DOCSTRING, repo) + + assert repo.head.commit.hexsha == new_sha + with checkout_commit(repo, initial_sha): + assert repo.head.commit.hexsha == initial_sha + with open(tmp_folder / BERT_MODELING_FILE) as f: + assert f.read() == BERT_MODEL_FILE + + assert repo.head.commit.hexsha == new_sha + with open(tmp_folder / BERT_MODELING_FILE) as f: + assert f.read() == BERT_MODEL_FILE_NEW_DOCSTRING + + def test_clean_code(self): + # Clean code removes all strings in triple quotes + assert clean_code('"""\nDocstring\n"""\ncode\n"""Long string"""\ncode\n') == "code\ncode" + assert clean_code("'''\nDocstring\n'''\ncode\n'''Long string'''\ncode\n'''") == "code\ncode" + + # Clean code removes all comments + assert clean_code("code\n# Comment\ncode") == "code\ncode" + assert clean_code("code # inline comment\ncode") == "code \ncode" + + def test_get_all_tests(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + assert get_all_tests() == ["tests/models/bert", "tests/test_modeling_common.py"] + + def test_get_all_tests_on_full_repo(self): + all_tests = get_all_tests() + assert "tests/models/albert" in all_tests + assert "tests/models/bert" in all_tests + assert "tests/repo_utils" in all_tests + assert "tests/test_pipeline_mixin.py" in all_tests + assert "tests/models" not in all_tests + assert "tests/__pycache__" not in all_tests + assert "tests/models/albert/test_modeling_albert.py" not in all_tests + assert "tests/repo_utils/test_tests_fetcher.py" not in all_tests + + def test_diff_is_docstring_only(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + repo = create_tmp_repo(tmp_folder) + + branching_point = repo.refs.main.commit + bert_file = BERT_MODELING_FILE + commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING, repo) + assert diff_is_docstring_only(repo, branching_point, bert_file) + + commit_changes(bert_file, BERT_MODEL_FILE_NEW_CODE, repo) + assert not diff_is_docstring_only(repo, branching_point, bert_file) + + def test_get_diff(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + repo = create_tmp_repo(tmp_folder) + + initial_commit = repo.refs.main.commit + bert_file = BERT_MODELING_FILE + commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING, repo) + assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == [] + + commit_changes(bert_file, BERT_MODEL_FILE_NEW_DOCSTRING + "\n# Adding a comment\n", repo) + assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == [] + + commit_changes(bert_file, BERT_MODEL_FILE_NEW_CODE, repo) + assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == [ + "src/transformers/models/bert/modeling_bert.py" + ] + + commit_changes("src/transformers/utils/hub.py", "import huggingface_hub\n\nnew code", repo) + assert get_diff(repo, repo.head.commit, repo.head.commit.parents) == ["src/transformers/utils/hub.py"] + assert get_diff(repo, repo.head.commit, [initial_commit]) == [ + "src/transformers/models/bert/modeling_bert.py", + "src/transformers/utils/hub.py", + ] + + def test_extract_imports_relative(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + expected_bert_imports = [ + ("src/transformers/modeling_utils.py", ["PreTrainedModel"]), + ("src/transformers/utils/__init__.py", ["is_torch_available"]), + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ] + expected_utils_imports = [ + ("src/transformers/utils/hub.py", ["cached_file"]), + ("src/transformers/utils/imports.py", ["is_torch_available"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + assert extract_imports("src/transformers/utils/__init__.py") == expected_utils_imports + + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from ...utils import cached_file, is_torch_available\nfrom .configuration_bert import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + # Test with multi-line imports + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from ...utils import (\n cached_file,\n is_torch_available\n)\nfrom .configuration_bert import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + def test_extract_imports_absolute(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from transformers.utils import cached_file, is_torch_available\nfrom transformers.models.bert.configuration_bert import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + # Test with multi-line imports + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from transformers.utils import (\n cached_file,\n is_torch_available\n)\nfrom transformers.models.bert.configuration_bert import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/models/bert/configuration_bert.py", ["BertConfig"]), + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + # Test with base imports + with open(tmp_folder / BERT_MODELING_FILE, "w") as f: + f.write( + "from transformers.utils import (\n cached_file,\n is_torch_available\n)\nfrom transformers import BertConfig\n" + ) + expected_bert_imports = [ + ("src/transformers/__init__.py", ["BertConfig"]), + ("src/transformers/utils/__init__.py", ["cached_file", "is_torch_available"]), + ] + with patch_transformer_repo_path(tmp_folder): + assert extract_imports(BERT_MODELING_FILE) == expected_bert_imports + + def test_get_module_dependencies(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + expected_bert_dependencies = [ + "src/transformers/modeling_utils.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/utils/imports.py", + ] + with patch_transformer_repo_path(tmp_folder): + assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies + + expected_test_bert_dependencies = [ + "tests/test_modeling_common.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + ] + + with patch_transformer_repo_path(tmp_folder): + assert ( + get_module_dependencies("tests/models/bert/test_modeling_bert.py") + == expected_test_bert_dependencies + ) + + # Test with a submodule + (tmp_folder / "src/transformers/utils/logging.py").touch() + with open(tmp_folder / BERT_MODELING_FILE, "a") as f: + f.write("from ...utils import logging\n") + + expected_bert_dependencies = [ + "src/transformers/modeling_utils.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/utils/logging.py", + "src/transformers/utils/imports.py", + ] + with patch_transformer_repo_path(tmp_folder): + assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies + + # Test with an object non-imported in the init + create_tmp_repo(tmp_folder) + with open(tmp_folder / BERT_MODELING_FILE, "a") as f: + f.write("from ...utils import CONSTANT\n") + + expected_bert_dependencies = [ + "src/transformers/modeling_utils.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/utils/__init__.py", + "src/transformers/utils/imports.py", + ] + with patch_transformer_repo_path(tmp_folder): + assert get_module_dependencies(BERT_MODELING_FILE) == expected_bert_dependencies + + # Test with an example + create_tmp_repo(tmp_folder) + + expected_example_dependencies = ["src/transformers/models/bert/modeling_bert.py"] + + with patch_transformer_repo_path(tmp_folder): + assert ( + get_module_dependencies("examples/pytorch/text-classification/run_glue.py") + == expected_example_dependencies + ) + + def test_create_reverse_dependency_tree(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + tree = create_reverse_dependency_tree() + + init_edges = [ + "src/transformers/utils/hub.py", + "src/transformers/utils/imports.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + ] + assert {f for f, g in tree if g == "src/transformers/__init__.py"} == set(init_edges) + + bert_edges = [ + "src/transformers/modeling_utils.py", + "src/transformers/utils/imports.py", + "src/transformers/models/bert/configuration_bert.py", + ] + assert {f for f, g in tree if g == "src/transformers/models/bert/modeling_bert.py"} == set(bert_edges) + + test_bert_edges = [ + "tests/test_modeling_common.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + ] + assert {f for f, g in tree if g == "tests/models/bert/test_modeling_bert.py"} == set(test_bert_edges) + + def test_get_tree_starting_at(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + edges = create_reverse_dependency_tree() + + bert_tree = get_tree_starting_at("src/transformers/models/bert/modeling_bert.py", edges) + config_utils_tree = get_tree_starting_at("src/transformers/configuration_utils.py", edges) + + expected_bert_tree = [ + "src/transformers/models/bert/modeling_bert.py", + [("src/transformers/models/bert/modeling_bert.py", "tests/models/bert/test_modeling_bert.py")], + ] + assert bert_tree == expected_bert_tree + + expected_config_tree = [ + "src/transformers/configuration_utils.py", + [("src/transformers/configuration_utils.py", "src/transformers/models/bert/configuration_bert.py")], + [ + ("src/transformers/models/bert/configuration_bert.py", "tests/models/bert/test_modeling_bert.py"), + ( + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + ), + ], + ] + # Order of the edges is random + assert [set(v) for v in config_utils_tree] == [set(v) for v in expected_config_tree] + + def test_print_tree_deps_of(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + # There are two possible outputs since the order of the last two lines is non-deterministic. + expected_std_out = """src/transformers/models/bert/modeling_bert.py + tests/models/bert/test_modeling_bert.py +src/transformers/configuration_utils.py + src/transformers/models/bert/configuration_bert.py + src/transformers/models/bert/modeling_bert.py + tests/models/bert/test_modeling_bert.py""" + + expected_std_out_2 = """src/transformers/models/bert/modeling_bert.py + tests/models/bert/test_modeling_bert.py +src/transformers/configuration_utils.py + src/transformers/models/bert/configuration_bert.py + tests/models/bert/test_modeling_bert.py + src/transformers/models/bert/modeling_bert.py""" + + with patch_transformer_repo_path(tmp_folder), CaptureStdout() as cs: + print_tree_deps_of("src/transformers/models/bert/modeling_bert.py") + print_tree_deps_of("src/transformers/configuration_utils.py") + + assert cs.out.strip() in [expected_std_out, expected_std_out_2] + + def test_init_test_examples_dependencies(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + + expected_example_deps = { + "examples/flax/test_flax_examples.py": [ + "examples/flax/text-classification/run_glue.py", + "examples/flax/test_flax_examples.py", + ], + "examples/pytorch/test_pytorch_examples.py": [ + "examples/pytorch/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + ], + "examples/tensorflow/test_tensorflow_examples.py": [ + "examples/tensorflow/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + ], + } + + expected_examples = { + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + + with patch_transformer_repo_path(tmp_folder): + example_deps, all_examples = init_test_examples_dependencies() + assert example_deps == expected_example_deps + assert {str(f.relative_to(tmp_folder)) for f in all_examples} == expected_examples + + def test_create_reverse_dependency_map(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + create_tmp_repo(tmp_folder) + with patch_transformer_repo_path(tmp_folder): + reverse_map = create_reverse_dependency_map() + + # impact of BERT modeling file (note that we stop at the inits and don't go down further) + expected_bert_deps = { + "src/transformers/__init__.py", + "src/transformers/models/bert/__init__.py", + "tests/models/bert/test_modeling_bert.py", + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + assert set(reverse_map["src/transformers/models/bert/modeling_bert.py"]) == expected_bert_deps + + # init gets the direct deps (and their recursive deps) + expected_init_deps = { + "src/transformers/utils/__init__.py", + "src/transformers/utils/hub.py", + "src/transformers/utils/imports.py", + "src/transformers/models/bert/__init__.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + "src/transformers/configuration_utils.py", + "src/transformers/modeling_utils.py", + "tests/test_modeling_common.py", + "tests/models/bert/test_modeling_bert.py", + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + assert set(reverse_map["src/transformers/__init__.py"]) == expected_init_deps + + expected_init_deps = { + "src/transformers/__init__.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + "tests/models/bert/test_modeling_bert.py", + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + assert set(reverse_map["src/transformers/models/bert/__init__.py"]) == expected_init_deps + + # Test that with more models init of bert only gets deps to bert. + create_tmp_repo(tmp_folder, models=["bert", "gpt2"]) + with patch_transformer_repo_path(tmp_folder): + reverse_map = create_reverse_dependency_map() + + # init gets the direct deps (and their recursive deps) + expected_init_deps = { + "src/transformers/__init__.py", + "src/transformers/models/bert/configuration_bert.py", + "src/transformers/models/bert/modeling_bert.py", + "tests/models/bert/test_modeling_bert.py", + "examples/flax/test_flax_examples.py", + "examples/flax/text-classification/run_glue.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/pytorch/text-classification/run_glue.py", + "examples/tensorflow/test_tensorflow_examples.py", + "examples/tensorflow/text-classification/run_glue.py", + } + assert set(reverse_map["src/transformers/models/bert/__init__.py"]) == expected_init_deps + + @unittest.skip("Broken for now TODO @ArthurZucker") + def test_infer_tests_to_run(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + models = ["bert", "gpt2"] + [f"bert{i}" for i in range(10)] + repo = create_tmp_repo(tmp_folder, models=models) + + commit_changes("src/transformers/models/bert/modeling_bert.py", BERT_MODEL_FILE_NEW_CODE, repo) + + example_tests = { + "examples/flax/test_flax_examples.py", + "examples/pytorch/test_pytorch_examples.py", + "examples/tensorflow/test_tensorflow_examples.py", + } + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True) + with open(tmp_folder / "test-output.txt") as f: + tests_to_run = f.read() + with open(tmp_folder / "examples_test_list.txt") as f: + example_tests_to_run = f.read() + + assert tests_to_run == "tests/models/bert/test_modeling_bert.py" + assert set(example_tests_to_run.split(" ")) == example_tests + + # Fake a new model addition + repo = create_tmp_repo(tmp_folder, models=models) + + branch = repo.create_head("new_model") + branch.checkout() + + with open(tmp_folder / "src/transformers/__init__.py", "a") as f: + f.write("from .models.t5 import T5Config, T5Model\n") + + model_dir = tmp_folder / "src/transformers/models/t5" + model_dir.mkdir(exist_ok=True) + + with open(model_dir / "__init__.py", "w") as f: + f.write("from .configuration_t5 import T5Config\nfrom .modeling_t5 import T5Model\n") + with open(model_dir / "configuration_t5.py", "w") as f: + f.write("from ...configuration_utils import PretrainedConfig\ncode") + with open(model_dir / "modeling_t5.py", "w") as f: + modeling_code = BERT_MODEL_FILE.replace("bert", "t5").replace("Bert", "T5") + f.write(modeling_code) + + test_dir = tmp_folder / "tests/models/t5" + test_dir.mkdir(exist_ok=True) + (test_dir / "__init__.py").touch() + with open(test_dir / "test_modeling_t5.py", "w") as f: + f.write( + "from transformers import T5Config, T5Model\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode" + ) + + repo.index.add(["src", "tests"]) + repo.index.commit("Add T5 model") + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt") + with open(tmp_folder / "test-output.txt") as f: + tests_to_run = f.read() + with open(tmp_folder / "examples_test_list.txt") as f: + example_tests_to_run = f.read() + + expected_tests = { + "tests/models/bert/test_modeling_bert.py", + "tests/models/gpt2/test_modeling_gpt2.py", + "tests/models/t5/test_modeling_t5.py", + "tests/test_modeling_common.py", + } + assert set(tests_to_run.split(" ")) == expected_tests + assert set(example_tests_to_run.split(" ")) == example_tests + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", filter_models=False) + with open(tmp_folder / "test-output.txt") as f: + tests_to_run = f.read() + with open(tmp_folder / "examples_test_list.txt") as f: + example_tests_to_run = f.read() + + expected_tests = [f"tests/models/{name}/test_modeling_{name}.py" for name in models + ["t5"]] + expected_tests = set(expected_tests + ["tests/test_modeling_common.py"]) + assert set(tests_to_run.split(" ")) == expected_tests + assert set(example_tests_to_run.split(" ")) == example_tests + + @unittest.skip("Broken for now TODO @ArthurZucker") + def test_infer_tests_to_run_with_test_modifs(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + models = ["bert", "gpt2"] + [f"bert{i}" for i in range(10)] + repo = create_tmp_repo(tmp_folder, models=models) + + commit_changes( + "tests/models/bert/test_modeling_bert.py", + "from transformers import BertConfig, BertModel\nfrom ...test_modeling_common import ModelTesterMixin\n\ncode1", + repo, + ) + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True) + with open(tmp_folder / "test-output.txt") as f: + tests_to_run = f.read() + + assert tests_to_run == "tests/models/bert/test_modeling_bert.py" + + @unittest.skip("Broken for now TODO @ArthurZucker") + def test_infer_tests_to_run_with_examples_modifs(self): + with tempfile.TemporaryDirectory() as tmp_folder: + tmp_folder = Path(tmp_folder) + models = ["bert", "gpt2"] + repo = create_tmp_repo(tmp_folder, models=models) + + # Modification in one example trigger the corresponding test + commit_changes( + "examples/pytorch/text-classification/run_glue.py", + "from transformers import BertModeln\n\ncode1", + repo, + ) + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True) + with open(tmp_folder / "examples_test_list.txt") as f: + example_tests_to_run = f.read() + + assert example_tests_to_run == "examples/pytorch/test_pytorch_examples.py" + + # Modification in one test example file trigger that test + repo = create_tmp_repo(tmp_folder, models=models) + commit_changes( + "examples/pytorch/test_pytorch_examples.py", + """test_args = "run_glue.py"\nmore_code""", + repo, + ) + + with patch_transformer_repo_path(tmp_folder): + infer_tests_to_run(tmp_folder / "test-output.txt", diff_with_last_commit=True) + with open(tmp_folder / "examples_test_list.txt") as f: + example_tests_to_run = f.read() + + assert example_tests_to_run == "examples/pytorch/test_pytorch_examples.py" + + def test_parse_commit_message(self): + assert parse_commit_message("Normal commit") == {"skip": False, "no_filter": False, "test_all": False} + + assert parse_commit_message("[skip ci] commit") == {"skip": True, "no_filter": False, "test_all": False} + assert parse_commit_message("[ci skip] commit") == {"skip": True, "no_filter": False, "test_all": False} + assert parse_commit_message("[skip-ci] commit") == {"skip": True, "no_filter": False, "test_all": False} + assert parse_commit_message("[skip_ci] commit") == {"skip": True, "no_filter": False, "test_all": False} + + assert parse_commit_message("[no filter] commit") == {"skip": False, "no_filter": True, "test_all": False} + assert parse_commit_message("[no-filter] commit") == {"skip": False, "no_filter": True, "test_all": False} + assert parse_commit_message("[no_filter] commit") == {"skip": False, "no_filter": True, "test_all": False} + assert parse_commit_message("[filter-no] commit") == {"skip": False, "no_filter": True, "test_all": False} + + assert parse_commit_message("[test all] commit") == {"skip": False, "no_filter": False, "test_all": True} + assert parse_commit_message("[all test] commit") == {"skip": False, "no_filter": False, "test_all": True} + assert parse_commit_message("[test-all] commit") == {"skip": False, "no_filter": False, "test_all": True} + assert parse_commit_message("[all_test] commit") == {"skip": False, "no_filter": False, "test_all": True} diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/README.md b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..70dc301f9c33b2c976af3b3835e7e27c10cb340e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/README.md @@ -0,0 +1,148 @@ +# Testing new Hugging Face Deep Learning Container. + +This document explains the testing strategy for releasing the new Hugging Face Deep Learning Container. AWS maintains 14 days of currency with framework releases. Besides framework releases, AWS release train is bi-weekly on Monday. Code cutoff date for any changes is the Wednesday before release-Monday. + + +## Test Case 1: Releasing a New Version (Minor/Major) of 🤗 Transformers + +### Requirements: Test should run on Release Candidate for new `transformers` release to validate the new release is compatible with the DLCs. To run these tests you need credentials for the HF SageMaker AWS Account. You can ask @philschmid or @n1t0 to get access. + +### Run Tests: + +Before we can run the tests we need to adjust the `requirements.txt` for PyTorch under `/tests/sagemaker/scripts/pytorch` and for TensorFlow under `/tests/sagemaker/scripts/pytorch`. We adjust the branch to the new RC-tag. + +``` +git+https://github.com/huggingface/transformers.git@v4.5.0.rc0 # install main or adjust ist with vX.X.X for installing version specific-transforms +``` + +After we adjusted the `requirements.txt` we can run Amazon SageMaker tests with: + +```bash +AWS_PROFILE= make test-sagemaker +``` +These tests take around 10-15 minutes to finish. Preferably make a screenshot of the successfully ran tests. + +### After Transformers Release: + +After we have released the Release Candidate we need to create a PR at the [Deep Learning Container Repository](https://github.com/aws/deep-learning-containers). + +**Creating the update PR:** + +1. Update the two latest `buildspec.yaml` config for [PyTorch](https://github.com/aws/deep-learning-containers/tree/master/huggingface/pytorch) and [TensorFlow](https://github.com/aws/deep-learning-containers/tree/master/huggingface/tensorflow). The two latest `buildspec.yaml` are the `buildspec.yaml` without a version tag and the one with the highest framework version, e.g. `buildspec-1-7-1.yml` and not `buildspec-1-6.yml`. + +To update the `buildspec.yaml` we need to adjust either the `transformers_version` or the `datasets_version` or both. Example for upgrading to `transformers 4.5.0` and `datasets 1.6.0`. +```yaml +account_id: &ACCOUNT_ID +region: ®ION +base_framework: &BASE_FRAMEWORK pytorch +framework: &FRAMEWORK !join [ "huggingface_", *BASE_FRAMEWORK] +version: &VERSION 1.6.0 +short_version: &SHORT_VERSION 1.6 + +repository_info: + training_repository: &TRAINING_REPOSITORY + image_type: &TRAINING_IMAGE_TYPE training + root: !join [ "huggingface/", *BASE_FRAMEWORK, "/", *TRAINING_IMAGE_TYPE ] + repository_name: &REPOSITORY_NAME !join ["pr", "-", "huggingface", "-", *BASE_FRAMEWORK, "-", *TRAINING_IMAGE_TYPE] + repository: &REPOSITORY !join [ *ACCOUNT_ID, .dkr.ecr., *REGION, .amazonaws.com/, + *REPOSITORY_NAME ] + +images: + BuildHuggingFacePytorchGpuPy37Cu110TrainingDockerImage: + <<: *TRAINING_REPOSITORY + build: &HUGGINGFACE_PYTORCH_GPU_TRAINING_PY3 false + image_size_baseline: &IMAGE_SIZE_BASELINE 15000 + device_type: &DEVICE_TYPE gpu + python_version: &DOCKER_PYTHON_VERSION py3 + tag_python_version: &TAG_PYTHON_VERSION py36 + cuda_version: &CUDA_VERSION cu110 + os_version: &OS_VERSION ubuntu18.04 + transformers_version: &TRANSFORMERS_VERSION 4.5.0 # this was adjusted from 4.4.2 to 4.5.0 + datasets_version: &DATASETS_VERSION 1.6.0 # this was adjusted from 1.5.0 to 1.6.0 + tag: !join [ *VERSION, '-', 'transformers', *TRANSFORMERS_VERSION, '-', *DEVICE_TYPE, '-', *TAG_PYTHON_VERSION, '-', + *CUDA_VERSION, '-', *OS_VERSION ] + docker_file: !join [ docker/, *SHORT_VERSION, /, *DOCKER_PYTHON_VERSION, /, + *CUDA_VERSION, /Dockerfile., *DEVICE_TYPE ] +``` +2. In the PR comment describe what test, we ran and with which package versions. Here you can copy the table from [Current Tests](#current-tests). + +2. In the PR comment describe what test we ran and with which framework versions. Here you can copy the table from [Current Tests](#current-tests). You can take a look at this [PR](https://github.com/aws/deep-learning-containers/pull/1016), which information are needed. +## Test Case 2: Releasing a New AWS Framework DLC + + +## Execute Tests + +### Requirements: +AWS is going to release new DLCs for PyTorch and/or TensorFlow. The Tests should run on the new framework versions with current `transformers` release to validate the new framework release is compatible with the `transformers` version. To run these tests you need credentials for the HF SageMaker AWS Account. You can ask @philschmid or @n1t0 to get access. AWS will notify us with a new issue in the repository pointing to their framework upgrade PR. + +### Run Tests: + +Before we can run the tests we need to adjust the `requirements.txt` for Pytorch under `/tests/sagemaker/scripts/pytorch` and for Tensorflow under `/tests/sagemaker/scripts/pytorch`. We add the new framework version to it. + +``` +torch==1.8.1 # for pytorch +tensorflow-gpu==2.5.0 # for tensorflow +``` + +After we adjusted the `requirements.txt` we can run Amazon SageMaker tests with. + +```bash +AWS_PROFILE= make test-sagemaker +``` +These tests take around 10-15 minutes to finish. Preferably make a screenshot of the successfully ran tests. + +### After successful Tests: + +After we have successfully run tests for the new framework version we need to create a PR at the [Deep Learning Container Repository](https://github.com/aws/deep-learning-containers). + +**Creating the update PR:** + +1. Create a new `buildspec.yaml` config for [PyTorch](https://github.com/aws/deep-learning-containers/tree/master/huggingface/pytorch) and [TensorFlow](https://github.com/aws/deep-learning-containers/tree/master/huggingface/tensorflow) and rename the old `buildspec.yaml` to `buildespec-x.x.x`, where `x.x.x` is the base framework version, e.g. if pytorch 1.6.0 is the latest version in `buildspec.yaml` the file should be renamed to `buildspec-yaml-1-6.yaml`. + +To create the new `buildspec.yaml` we need to adjust the `version` and the `short_version`. Example for upgrading to `pytorch 1.7.1`. + +```yaml +account_id: &ACCOUNT_ID +region: ®ION +base_framework: &BASE_FRAMEWORK pytorch +framework: &FRAMEWORK !join [ "huggingface_", *BASE_FRAMEWORK] +version: &VERSION 1.7.1 # this was adjusted from 1.6.0 to 1.7.1 +short_version: &SHORT_VERSION 1.7 # this was adjusted from 1.6 to 1.7 + +repository_info: + training_repository: &TRAINING_REPOSITORY + image_type: &TRAINING_IMAGE_TYPE training + root: !join [ "huggingface/", *BASE_FRAMEWORK, "/", *TRAINING_IMAGE_TYPE ] + repository_name: &REPOSITORY_NAME !join ["pr", "-", "huggingface", "-", *BASE_FRAMEWORK, "-", *TRAINING_IMAGE_TYPE] + repository: &REPOSITORY !join [ *ACCOUNT_ID, .dkr.ecr., *REGION, .amazonaws.com/, + *REPOSITORY_NAME ] + +images: + BuildHuggingFacePytorchGpuPy37Cu110TrainingDockerImage: + <<: *TRAINING_REPOSITORY + build: &HUGGINGFACE_PYTORCH_GPU_TRAINING_PY3 false + image_size_baseline: &IMAGE_SIZE_BASELINE 15000 + device_type: &DEVICE_TYPE gpu + python_version: &DOCKER_PYTHON_VERSION py3 + tag_python_version: &TAG_PYTHON_VERSION py36 + cuda_version: &CUDA_VERSION cu110 + os_version: &OS_VERSION ubuntu18.04 + transformers_version: &TRANSFORMERS_VERSION 4.4.2 + datasets_version: &DATASETS_VERSION 1.5.0 + tag: !join [ *VERSION, '-', 'transformers', *TRANSFORMERS_VERSION, '-', *DEVICE_TYPE, '-', *TAG_PYTHON_VERSION, '-', + *CUDA_VERSION, '-', *OS_VERSION ] + docker_file: !join [ docker/, *SHORT_VERSION, /, *DOCKER_PYTHON_VERSION, /, + *CUDA_VERSION, /Dockerfile., *DEVICE_TYPE ] +``` +2. In the PR comment describe what test we ran and with which framework versions. Here you can copy the table from [Current Tests](#current-tests). You can take a look at this [PR](https://github.com/aws/deep-learning-containers/pull/1025), which information are needed. + +## Current Tests + +| ID | Description | Platform | #GPUs | Collected & evaluated metrics | +|-------------------------------------|-------------------------------------------------------------------|-----------------------------|-------|------------------------------------------| +| pytorch-transfromers-test-single | test bert finetuning using BERT fromtransformerlib+PT | SageMaker createTrainingJob | 1 | train_runtime, eval_accuracy & eval_loss | +| pytorch-transfromers-test-2-ddp | test bert finetuning using BERT from transformer lib+ PT DPP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss | +| pytorch-transfromers-test-2-smd | test bert finetuning using BERT from transformer lib+ PT SM DDP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss | +| pytorch-transfromers-test-1-smp | test roberta finetuning using BERT from transformer lib+ PT SM MP | SageMaker createTrainingJob | 8 | train_runtime, eval_accuracy & eval_loss | +| tensorflow-transfromers-test-single | Test bert finetuning using BERT from transformer lib+TF | SageMaker createTrainingJob | 1 | train_runtime, eval_accuracy & eval_loss | +| tensorflow-transfromers-test-2-smd | test bert finetuning using BERT from transformer lib+ TF SM DDP | SageMaker createTrainingJob | 16 | train_runtime, eval_accuracy & eval_loss | diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ecda04614d4218221a399640932b6ecf4f9b60f2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/__init__.py @@ -0,0 +1,5 @@ +import importlib + + +def is_sagemaker_available(): + return importlib.util.find_spec("sagemaker") is not None diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/conftest.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/conftest.py new file mode 100644 index 0000000000000000000000000000000000000000..9d987bc8d0066caf1f2ab1b56484311d0e56caf0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/conftest.py @@ -0,0 +1,64 @@ +# we define a fixture function below and it will be "used" by +# referencing its name from tests + +import os + +import pytest +from attr import dataclass + + +os.environ["AWS_DEFAULT_REGION"] = "us-east-1" # defaults region + + +@dataclass +class SageMakerTestEnvironment: + framework: str + role = "arn:aws:iam::558105141721:role/sagemaker_execution_role" + hyperparameters = { + "task_name": "mnli", + "per_device_train_batch_size": 16, + "per_device_eval_batch_size": 16, + "do_train": True, + "do_eval": True, + "do_predict": True, + "output_dir": "/opt/ml/model", + "overwrite_output_dir": True, + "max_steps": 500, + "save_steps": 5500, + } + distributed_hyperparameters = {**hyperparameters, "max_steps": 1000} + + @property + def metric_definitions(self) -> str: + if self.framework == "pytorch": + return [ + {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, + {"Name": "eval_accuracy", "Regex": r"eval_accuracy.*=\D*(.*?)$"}, + {"Name": "eval_loss", "Regex": r"eval_loss.*=\D*(.*?)$"}, + ] + else: + return [ + {"Name": "train_runtime", "Regex": r"train_runtime.*=\D*(.*?)$"}, + {"Name": "eval_accuracy", "Regex": r"loss.*=\D*(.*?)]?$"}, + {"Name": "eval_loss", "Regex": r"sparse_categorical_accuracy.*=\D*(.*?)]?$"}, + ] + + @property + def base_job_name(self) -> str: + return f"{self.framework}-transfromers-test" + + @property + def test_path(self) -> str: + return f"./tests/sagemaker/scripts/{self.framework}" + + @property + def image_uri(self) -> str: + if self.framework == "pytorch": + return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-pytorch-training:1.7.1-transformers4.6.1-gpu-py36-cu110-ubuntu18.04" + else: + return "763104351884.dkr.ecr.us-east-1.amazonaws.com/huggingface-tensorflow-training:2.4.1-transformers4.6.1-gpu-py37-cu110-ubuntu18.04" + + +@pytest.fixture(scope="class") +def sm_env(request): + request.cls.env = SageMakerTestEnvironment(framework=request.cls.framework) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/requirements.txt b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..2e2ed672726689713a8b62564c1f744f579907df --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/requirements.txt @@ -0,0 +1,2 @@ +git+https://github.com/huggingface/transformers.git@main # install main or adjust it with vX.X.X for installing version specific transforms +datasets==1.8.0 \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_ddp.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_ddp.py new file mode 100644 index 0000000000000000000000000000000000000000..474285841b0d360a2895e6110dd40fc23542f0cf --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_ddp.py @@ -0,0 +1,52 @@ +import json +import logging +import os +import subprocess +from argparse import ArgumentParser + + +logger = logging.getLogger(__name__) + + +def parse_args(): + parser = ArgumentParser() + parsed, unknown = parser.parse_known_args() + for arg in unknown: + if arg.startswith(("-", "--")): + parser.add_argument(arg.split("=")[0]) + + return parser.parse_args() + + +def main(): + args = parse_args() + port = 8888 + num_gpus = int(os.environ["SM_NUM_GPUS"]) + hosts = json.loads(os.environ["SM_HOSTS"]) + num_nodes = len(hosts) + current_host = os.environ["SM_CURRENT_HOST"] + rank = hosts.index(current_host) + os.environ["NCCL_DEBUG"] = "INFO" + + if num_nodes > 1: + cmd = f"""python -m torch.distributed.launch \ + --nnodes={num_nodes} \ + --node_rank={rank} \ + --nproc_per_node={num_gpus} \ + --master_addr={hosts[0]} \ + --master_port={port} \ + ./run_glue.py \ + {"".join([f" --{parameter} {value}" for parameter, value in args.__dict__.items()])}""" + else: + cmd = f"""python -m torch.distributed.launch \ + --nproc_per_node={num_gpus} \ + ./run_glue.py \ + {"".join([f" --{parameter} {value}" for parameter, value in args.__dict__.items()])}""" + try: + subprocess.run(cmd, shell=True) + except Exception as e: + logger.info(e) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py new file mode 100644 index 0000000000000000000000000000000000000000..d18484d1cd361ca29483e2950f00547af099785f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/pytorch/run_glue_model_parallelism.py @@ -0,0 +1,540 @@ +#!/usr/bin/env python +# Copyright 2021 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. +"""Finetuning the library models for sequence classification on GLUE.""" +# You can also adapt this script on your own text classification task. Pointers for this are left as comments. + +import logging +import os +import random +import sys +from dataclasses import dataclass, field +from typing import Optional + +import numpy as np +from datasets import load_dataset, load_metric + +import transformers +from transformers import ( # Trainer,; TrainingArguments, + AutoConfig, + AutoModelForSequenceClassification, + AutoTokenizer, + DataCollatorWithPadding, + EvalPrediction, + HfArgumentParser, + PretrainedConfig, + default_data_collator, + set_seed, +) + +# Will import SageMaker Model parallelism specific Trainer +from transformers.sagemaker import SageMakerTrainer as Trainer +from transformers.sagemaker import SageMakerTrainingArguments as TrainingArguments +from transformers.trainer_utils import get_last_checkpoint +from transformers.utils import check_min_version + + +# Will error if the minimal version of Transformers is not installed. Remove at your own risks. +check_min_version("4.4.2") + +task_to_keys = { + "cola": ("sentence", None), + "mnli": ("premise", "hypothesis"), + "mrpc": ("sentence1", "sentence2"), + "qnli": ("question", "sentence"), + "qqp": ("question1", "question2"), + "rte": ("sentence1", "sentence2"), + "sst2": ("sentence", None), + "stsb": ("sentence1", "sentence2"), + "wnli": ("sentence1", "sentence2"), +} + +logger = logging.getLogger(__name__) + + +@dataclass +class DataTrainingArguments: + """ + Arguments pertaining to what data we are going to input our model for training and eval. + + Using `HfArgumentParser` we can turn this class + into argparse arguments to be able to specify them on + the command line. + """ + + task_name: Optional[str] = field( + default=None, + metadata={"help": "The name of the task to train on: " + ", ".join(task_to_keys.keys())}, + ) + max_seq_length: int = field( + default=128, + metadata={ + "help": ( + "The maximum total input sequence length after tokenization. Sequences longer " + "than this will be truncated, sequences shorter will be padded." + ) + }, + ) + overwrite_cache: bool = field( + default=False, metadata={"help": "Overwrite the cached preprocessed datasets or not."} + ) + pad_to_max_length: bool = field( + default=True, + metadata={ + "help": ( + "Whether to pad all samples to `max_seq_length`. " + "If False, will pad the samples dynamically when batching to the maximum length in the batch." + ) + }, + ) + max_train_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of training examples to this " + "value if set." + ) + }, + ) + max_val_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of validation examples to this " + "value if set." + ) + }, + ) + max_test_samples: Optional[int] = field( + default=None, + metadata={ + "help": ( + "For debugging purposes or quicker training, truncate the number of test examples to this " + "value if set." + ) + }, + ) + train_file: Optional[str] = field( + default=None, metadata={"help": "A csv or a json file containing the training data."} + ) + validation_file: Optional[str] = field( + default=None, metadata={"help": "A csv or a json file containing the validation data."} + ) + test_file: Optional[str] = field(default=None, metadata={"help": "A csv or a json file containing the test data."}) + + def __post_init__(self): + if self.task_name is not None: + self.task_name = self.task_name.lower() + if self.task_name not in task_to_keys: + raise ValueError("Unknown task, you should pick one in " + ",".join(task_to_keys.keys())) + elif self.train_file is None or self.validation_file is None: + raise ValueError("Need either a GLUE task or a training/validation file.") + else: + train_extension = self.train_file.split(".")[-1] + assert train_extension in ["csv", "json"], "`train_file` should be a csv or a json file." + validation_extension = self.validation_file.split(".")[-1] + assert validation_extension == train_extension, ( + "`validation_file` should have the same extension (csv or json) as `train_file`." + ) + + +@dataclass +class ModelArguments: + """ + Arguments pertaining to which model/config/tokenizer we are going to fine-tune from. + """ + + model_name_or_path: str = field( + metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"} + ) + config_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained config name or path if not the same as model_name"} + ) + tokenizer_name: Optional[str] = field( + default=None, metadata={"help": "Pretrained tokenizer name or path if not the same as model_name"} + ) + cache_dir: Optional[str] = field( + default=None, + metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}, + ) + use_fast_tokenizer: bool = field( + default=True, + metadata={"help": "Whether to use one of the fast tokenizer (backed by the tokenizers library) or not."}, + ) + model_revision: str = field( + default="main", + metadata={"help": "The specific model version to use (can be a branch name, tag name or commit id)."}, + ) + use_auth_token: bool = field( + default=False, + metadata={ + "help": ( + "Will use the token generated when running `hf auth login` (necessary to use this script " + "with private models)." + ) + }, + ) + + +def main(): + # See all possible arguments in src/transformers/training_args.py + # or by passing the --help flag to this script. + # We now keep distinct sets of args, for a cleaner separation of concerns. + + parser = HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)) + if len(sys.argv) == 2 and sys.argv[1].endswith(".json"): + # If we pass only one argument to the script and it's the path to a json file, + # let's parse it to get our arguments. + model_args, data_args, training_args = parser.parse_json_file(json_file=os.path.abspath(sys.argv[1])) + else: + model_args, data_args, training_args = parser.parse_args_into_dataclasses() + + # Detecting last checkpoint. + last_checkpoint = None + if os.path.isdir(training_args.output_dir) and training_args.do_train and not training_args.overwrite_output_dir: + last_checkpoint = get_last_checkpoint(training_args.output_dir) + if last_checkpoint is None and len(os.listdir(training_args.output_dir)) > 0: + raise ValueError( + f"Output directory ({training_args.output_dir}) already exists and is not empty. " + "Use --overwrite_output_dir to overcome." + ) + elif last_checkpoint is not None: + logger.info( + f"Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change " + "the `--output_dir` or add `--overwrite_output_dir` to train from scratch." + ) + + # Setup logging + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + handlers=[logging.StreamHandler(sys.stdout)], + ) + logger.setLevel(logging.INFO if training_args.should_log else logging.WARN) + + # Log on each process the small summary: + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}" + + f"distributed training: {bool(training_args.local_rank != -1)}, 16-bits training: {training_args.fp16}" + ) + # Set the verbosity to info of the Transformers logger (on main process only): + if training_args.should_log: + transformers.utils.logging.set_verbosity_info() + transformers.utils.logging.enable_default_handler() + transformers.utils.logging.enable_explicit_format() + logger.info(f"Training/evaluation parameters {training_args}") + + # Set seed before initializing model. + set_seed(training_args.seed) + + # Get the datasets: you can either provide your own CSV/JSON training and evaluation files (see below) + # or specify a GLUE benchmark task (the dataset will be downloaded automatically from the datasets Hub). + # + # For CSV/JSON files, this script will use as labels the column called 'label' and as pair of sentences the + # sentences in columns called 'sentence1' and 'sentence2' if such column exists or the first two columns not named + # label if at least two columns are provided. + # + # If the CSVs/JSONs contain only one non-label column, the script does single sentence classification on this + # single column. You can easily tweak this behavior (see below) + # + # In distributed training, the load_dataset function guarantee that only one local process can concurrently + # download the dataset. + if data_args.task_name is not None: + # Downloading and loading a dataset from the hub. + datasets = load_dataset("nyu-mll/glue", data_args.task_name) + else: + # Loading a dataset from your local files. + # CSV/JSON training and evaluation files are needed. + data_files = {"train": data_args.train_file, "validation": data_args.validation_file} + + # Get the test dataset: you can provide your own CSV/JSON test file (see below) + # when you use `do_predict` without specifying a GLUE benchmark task. + if training_args.do_predict: + if data_args.test_file is not None: + train_extension = data_args.train_file.split(".")[-1] + test_extension = data_args.test_file.split(".")[-1] + assert test_extension == train_extension, ( + "`test_file` should have the same extension (csv or json) as `train_file`." + ) + data_files["test"] = data_args.test_file + else: + raise ValueError("Need either a GLUE task or a test file for `do_predict`.") + + for key in data_files: + logger.info(f"load a local file for {key}: {data_files[key]}") + + if data_args.train_file.endswith(".csv"): + # Loading a dataset from local csv files + datasets = load_dataset("csv", data_files=data_files) + else: + # Loading a dataset from local json files + datasets = load_dataset("json", data_files=data_files) + # See more about loading any type of standard or custom dataset at + # https://huggingface.co/docs/datasets/loading_datasets. + + # Labels + if data_args.task_name is not None: + is_regression = data_args.task_name == "stsb" + if not is_regression: + label_list = datasets["train"].features["label"].names + num_labels = len(label_list) + else: + num_labels = 1 + else: + # Trying to have good defaults here, don't hesitate to tweak to your needs. + is_regression = datasets["train"].features["label"].dtype in ["float32", "float64"] + if is_regression: + num_labels = 1 + else: + # A useful fast method: + # https://huggingface.co/docs/datasets/package_reference/main_classes#datasets.Dataset.unique + label_list = datasets["train"].unique("label") + label_list.sort() # Let's sort it for determinism + num_labels = len(label_list) + + # Load pretrained model and tokenizer + # + # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently + # download model & vocab. + config = AutoConfig.from_pretrained( + model_args.config_name if model_args.config_name else model_args.model_name_or_path, + num_labels=num_labels, + finetuning_task=data_args.task_name, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + token=True if model_args.use_auth_token else None, + ) + tokenizer = AutoTokenizer.from_pretrained( + model_args.tokenizer_name if model_args.tokenizer_name else model_args.model_name_or_path, + cache_dir=model_args.cache_dir, + use_fast=model_args.use_fast_tokenizer, + revision=model_args.model_revision, + token=True if model_args.use_auth_token else None, + ) + model = AutoModelForSequenceClassification.from_pretrained( + model_args.model_name_or_path, + from_tf=bool(".ckpt" in model_args.model_name_or_path), + config=config, + cache_dir=model_args.cache_dir, + revision=model_args.model_revision, + token=True if model_args.use_auth_token else None, + ) + + # Preprocessing the datasets + if data_args.task_name is not None: + sentence1_key, sentence2_key = task_to_keys[data_args.task_name] + else: + # Again, we try to have some nice defaults but don't hesitate to tweak to your use case. + non_label_column_names = [name for name in datasets["train"].column_names if name != "label"] + if "sentence1" in non_label_column_names and "sentence2" in non_label_column_names: + sentence1_key, sentence2_key = "sentence1", "sentence2" + else: + if len(non_label_column_names) >= 2: + sentence1_key, sentence2_key = non_label_column_names[:2] + else: + sentence1_key, sentence2_key = non_label_column_names[0], None + + # Padding strategy + if data_args.pad_to_max_length: + padding = "max_length" + else: + # We will pad later, dynamically at batch creation, to the max sequence length in each batch + padding = False + + # Some models have set the order of the labels to use, so let's make sure we do use it. + label_to_id = None + if ( + model.config.label2id != PretrainedConfig(num_labels=num_labels).label2id + and data_args.task_name is not None + and not is_regression + ): + # Some have all caps in their config, some don't. + label_name_to_id = {k.lower(): v for k, v in model.config.label2id.items()} + if sorted(label_name_to_id.keys()) == sorted(label_list): + label_to_id = {i: int(label_name_to_id[label_list[i]]) for i in range(num_labels)} + else: + logger.warning( + "Your model seems to have been trained with labels, but they don't match the dataset: " + f"model labels: {sorted(label_name_to_id.keys())}, dataset labels: {sorted(label_list)}." + "\nIgnoring the model labels as a result.", + ) + elif data_args.task_name is None and not is_regression: + label_to_id = {v: i for i, v in enumerate(label_list)} + + if data_args.max_seq_length > tokenizer.model_max_length: + logger.warning( + f"The max_seq_length passed ({data_args.max_seq_length}) is larger than the maximum length for the " + f"model ({tokenizer.model_max_length}). Using max_seq_length={tokenizer.model_max_length}." + ) + max_seq_length = min(data_args.max_seq_length, tokenizer.model_max_length) + + def preprocess_function(examples): + # Tokenize the texts + args = ( + (examples[sentence1_key],) if sentence2_key is None else (examples[sentence1_key], examples[sentence2_key]) + ) + result = tokenizer(*args, padding=padding, max_length=max_seq_length, truncation=True) + + # Map labels to IDs (not necessary for GLUE tasks) + if label_to_id is not None and "label" in examples: + result["label"] = [(label_to_id[l] if l != -1 else -1) for l in examples["label"]] + return result + + datasets = datasets.map(preprocess_function, batched=True, load_from_cache_file=not data_args.overwrite_cache) + if training_args.do_train: + if "train" not in datasets: + raise ValueError("--do_train requires a train dataset") + train_dataset = datasets["train"] + if data_args.max_train_samples is not None: + train_dataset = train_dataset.select(range(data_args.max_train_samples)) + + if training_args.do_eval: + if "validation" not in datasets and "validation_matched" not in datasets: + raise ValueError("--do_eval requires a validation dataset") + eval_dataset = datasets["validation_matched" if data_args.task_name == "mnli" else "validation"] + if data_args.max_val_samples is not None: + eval_dataset = eval_dataset.select(range(data_args.max_val_samples)) + + if training_args.do_predict or data_args.task_name is not None or data_args.test_file is not None: + if "test" not in datasets and "test_matched" not in datasets: + raise ValueError("--do_predict requires a test dataset") + test_dataset = datasets["test_matched" if data_args.task_name == "mnli" else "test"] + if data_args.max_test_samples is not None: + test_dataset = test_dataset.select(range(data_args.max_test_samples)) + + # Log a few random samples from the training set: + if training_args.do_train: + for index in random.sample(range(len(train_dataset)), 3): + logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") + + # Get the metric function + if data_args.task_name is not None: + metric = load_metric("glue", data_args.task_name) + # TODO: When datasets metrics include regular accuracy, make an else here and remove special branch from + # compute_metrics + + # You can define your custom compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a + # predictions and label_ids field) and has to return a dictionary string to float. + def compute_metrics(p: EvalPrediction): + preds = p.predictions[0] if isinstance(p.predictions, tuple) else p.predictions + preds = np.squeeze(preds) if is_regression else np.argmax(preds, axis=1) + if data_args.task_name is not None: + result = metric.compute(predictions=preds, references=p.label_ids) + if len(result) > 1: + result["combined_score"] = np.mean(list(result.values())).item() + return result + elif is_regression: + return {"mse": ((preds - p.label_ids) ** 2).mean().item()} + else: + return {"accuracy": (preds == p.label_ids).astype(np.float32).mean().item()} + + # Data collator will default to DataCollatorWithPadding, so we change it if we already did the padding. + if data_args.pad_to_max_length: + data_collator = default_data_collator + elif training_args.fp16: + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) + else: + data_collator = None + + # Initialize our Trainer + trainer = Trainer( + model=model, + args=training_args, + train_dataset=train_dataset if training_args.do_train else None, + eval_dataset=eval_dataset if training_args.do_eval else None, + compute_metrics=compute_metrics, + processing_class=tokenizer, + data_collator=data_collator, + ) + + # Training + if training_args.do_train: + checkpoint = None + if last_checkpoint is not None: + checkpoint = last_checkpoint + elif os.path.isdir(model_args.model_name_or_path): + # Check the config from that potential checkpoint has the right number of labels before using it as a + # checkpoint. + if AutoConfig.from_pretrained(model_args.model_name_or_path).num_labels == num_labels: + checkpoint = model_args.model_name_or_path + + train_result = trainer.train(resume_from_checkpoint=checkpoint) + metrics = train_result.metrics + max_train_samples = ( + data_args.max_train_samples if data_args.max_train_samples is not None else len(train_dataset) + ) + metrics["train_samples"] = min(max_train_samples, len(train_dataset)) + + trainer.save_model() # Saves the tokenizer too for easy upload + + trainer.log_metrics("train", metrics) + trainer.save_metrics("train", metrics) + trainer.save_state() + + # Evaluation + if training_args.do_eval: + logger.info("*** Evaluate ***") + + # Loop to handle MNLI double evaluation (matched, mis-matched) + tasks = [data_args.task_name] + eval_datasets = [eval_dataset] + if data_args.task_name == "mnli": + tasks.append("mnli-mm") + eval_datasets.append(datasets["validation_mismatched"]) + + for eval_dataset, task in zip(eval_datasets, tasks): + metrics = trainer.evaluate(eval_dataset=eval_dataset) + + max_val_samples = data_args.max_val_samples if data_args.max_val_samples is not None else len(eval_dataset) + metrics["eval_samples"] = min(max_val_samples, len(eval_dataset)) + + trainer.log_metrics("eval", metrics) + trainer.save_metrics("eval", metrics) + + if training_args.do_predict: + logger.info("*** Test ***") + + # Loop to handle MNLI double evaluation (matched, mis-matched) + tasks = [data_args.task_name] + test_datasets = [test_dataset] + if data_args.task_name == "mnli": + tasks.append("mnli-mm") + test_datasets.append(datasets["test_mismatched"]) + + for test_dataset, task in zip(test_datasets, tasks): + # Removing the `label` columns because it contains -1 and Trainer won't like that. + test_dataset = test_dataset.remove_columns("label") + predictions = trainer.predict(test_dataset=test_dataset).predictions + predictions = np.squeeze(predictions) if is_regression else np.argmax(predictions, axis=1) + + output_test_file = os.path.join(training_args.output_dir, f"test_results_{task}.txt") + if trainer.is_world_process_zero(): + with open(output_test_file, "w") as writer: + logger.info(f"***** Test results {task} *****") + writer.write("index\tprediction\n") + for index, item in enumerate(predictions): + if is_regression: + writer.write(f"{index}\t{item:3.3f}\n") + else: + item = label_list[item] + writer.write(f"{index}\t{item}\n") + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/requirements.txt b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..34a3d05b460e2dcac55c9cf3d186afed24c7f9fb --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/requirements.txt @@ -0,0 +1 @@ +git+https://github.com/huggingface/transformers.git@main # install main or adjust ist with vX.X.X for installing version specific transforms \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/run_tf.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/run_tf.py new file mode 100644 index 0000000000000000000000000000000000000000..a5b8e3fe1f05d114237ec085cf5ad82c73539aff --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/scripts/tensorflow/run_tf.py @@ -0,0 +1,104 @@ +import argparse +import logging +import sys +import time + +import tensorflow as tf +from datasets import load_dataset +from packaging.version import parse + +from transformers import AutoTokenizer, TFAutoModelForSequenceClassification + + +try: + import tf_keras as keras +except (ModuleNotFoundError, ImportError): + import keras + + if parse(keras.__version__).major > 2: + raise ValueError( + "Your currently installed version of Keras is Keras 3, but this is not yet supported in " + "Transformers. Please install the backwards-compatible tf-keras package with " + "`pip install tf-keras`." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + + # Hyperparameters sent by the client are passed as command-line arguments to the script. + parser.add_argument("--epochs", type=int, default=1) + parser.add_argument("--per_device_train_batch_size", type=int, default=16) + parser.add_argument("--per_device_eval_batch_size", type=int, default=8) + parser.add_argument("--model_name_or_path", type=str) + parser.add_argument("--learning_rate", type=str, default=5e-5) + parser.add_argument("--do_train", type=bool, default=True) + parser.add_argument("--do_eval", type=bool, default=True) + parser.add_argument("--output_dir", type=str) + + args, _ = parser.parse_known_args() + + # overwrite batch size until we have tf_glue.py + args.per_device_train_batch_size = 16 + args.per_device_eval_batch_size = 16 + + # Set up logging + logger = logging.getLogger(__name__) + + logging.basicConfig( + level=logging.getLevelName("INFO"), + handlers=[logging.StreamHandler(sys.stdout)], + format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", + ) + + # Load model and tokenizer + model = TFAutoModelForSequenceClassification.from_pretrained(args.model_name_or_path) + tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) + + # Load dataset + train_dataset, test_dataset = load_dataset("stanfordnlp/imdb", split=["train", "test"]) + train_dataset = train_dataset.shuffle().select(range(5000)) # smaller the size for train dataset to 5k + test_dataset = test_dataset.shuffle().select(range(500)) # smaller the size for test dataset to 500 + + # Preprocess train dataset + train_dataset = train_dataset.map( + lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True + ) + train_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"]) + + train_features = { + x: train_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) + for x in ["input_ids", "attention_mask"] + } + tf_train_dataset = tf.data.Dataset.from_tensor_slices((train_features, train_dataset["label"])).batch( + args.per_device_train_batch_size + ) + + # Preprocess test dataset + test_dataset = test_dataset.map( + lambda e: tokenizer(e["text"], truncation=True, padding="max_length"), batched=True + ) + test_dataset.set_format(type="tensorflow", columns=["input_ids", "attention_mask", "label"]) + + test_features = { + x: test_dataset[x].to_tensor(default_value=0, shape=[None, tokenizer.model_max_length]) + for x in ["input_ids", "attention_mask"] + } + tf_test_dataset = tf.data.Dataset.from_tensor_slices((test_features, test_dataset["label"])).batch( + args.per_device_eval_batch_size + ) + + # fine optimizer and loss + optimizer = keras.optimizers.Adam(learning_rate=args.learning_rate) + loss = keras.losses.SparseCategoricalCrossentropy(from_logits=True) + metrics = [keras.metrics.SparseCategoricalAccuracy()] + model.compile(optimizer=optimizer, loss=loss, metrics=metrics) + + start_train_time = time.time() + train_results = model.fit(tf_train_dataset, epochs=args.epochs, batch_size=args.per_device_train_batch_size) + end_train_time = time.time() - start_train_time + + logger.info("*** Train ***") + logger.info(f"train_runtime = {end_train_time}") + for key, value in train_results.history.items(): + logger.info(f" {key} = {value}") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_data_parallel.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_data_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..2ea029a285517d86e11f20201ee6e288f4ed7665 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_data_parallel.py @@ -0,0 +1,109 @@ +import json +import os +import subprocess +import unittest +from ast import literal_eval + +import pytest +from parameterized import parameterized, parameterized_class + +from . import is_sagemaker_available + + +if is_sagemaker_available(): + from sagemaker import Session, TrainingJobAnalytics + from sagemaker.huggingface import HuggingFace + + +@pytest.mark.skipif( + literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True, + reason="Skipping test because should only be run when releasing minor transformers version", +) +@pytest.mark.usefixtures("sm_env") +@parameterized_class( + [ + { + "framework": "pytorch", + "script": "run_glue.py", + "model_name_or_path": "distilbert/distilbert-base-cased", + "instance_type": "ml.p3.16xlarge", + "results": {"train_runtime": 650, "eval_accuracy": 0.7, "eval_loss": 0.6}, + }, + { + "framework": "pytorch", + "script": "run_ddp.py", + "model_name_or_path": "distilbert/distilbert-base-cased", + "instance_type": "ml.p3.16xlarge", + "results": {"train_runtime": 600, "eval_accuracy": 0.7, "eval_loss": 0.6}, + }, + { + "framework": "tensorflow", + "script": "run_tf_dist.py", + "model_name_or_path": "distilbert/distilbert-base-cased", + "instance_type": "ml.p3.16xlarge", + "results": {"train_runtime": 600, "eval_accuracy": 0.6, "eval_loss": 0.7}, + }, + ] +) +class MultiNodeTest(unittest.TestCase): + def setUp(self): + if self.framework == "pytorch": + subprocess.run( + f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(), + encoding="utf-8", + check=True, + ) + assert hasattr(self, "env") + + def create_estimator(self, instance_count): + job_name = f"{self.env.base_job_name}-{instance_count}-{'ddp' if 'ddp' in self.script else 'smd'}" + # distributed data settings + distribution = {"smdistributed": {"dataparallel": {"enabled": True}}} if self.script != "run_ddp.py" else None + + # creates estimator + return HuggingFace( + entry_point=self.script, + source_dir=self.env.test_path, + role=self.env.role, + image_uri=self.env.image_uri, + base_job_name=job_name, + instance_count=instance_count, + instance_type=self.instance_type, + debugger_hook_config=False, + hyperparameters={**self.env.distributed_hyperparameters, "model_name_or_path": self.model_name_or_path}, + metric_definitions=self.env.metric_definitions, + distribution=distribution, + py_version="py36", + ) + + def save_results_as_csv(self, job_name): + TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv") + + # @parameterized.expand([(2,), (4,),]) + @parameterized.expand([(2,)]) + def test_script(self, instance_count): + # create estimator + estimator = self.create_estimator(instance_count) + + # run training + estimator.fit() + + # result dataframe + result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() + + # extract kpis + eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]) + eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]) + # get train time from SageMaker job, this includes starting, preprocessing, stopping + train_runtime = ( + Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999) + ) + + # assert kpis + assert train_runtime <= self.results["train_runtime"] + assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy) + assert all(t <= self.results["eval_loss"] for t in eval_loss) + + # dump tests result into json file to share in PR + with open(f"{estimator.latest_training_job.name}.json", "w") as outfile: + json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_model_parallel.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_model_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..216d31de47106a28da7c788d92672f00eff80f74 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_multi_node_model_parallel.py @@ -0,0 +1,122 @@ +import json +import os +import subprocess +import unittest +from ast import literal_eval + +import pytest +from parameterized import parameterized, parameterized_class + +from . import is_sagemaker_available + + +if is_sagemaker_available(): + from sagemaker import Session, TrainingJobAnalytics + from sagemaker.huggingface import HuggingFace + + +@pytest.mark.skipif( + literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True, + reason="Skipping test because should only be run when releasing minor transformers version", +) +@pytest.mark.usefixtures("sm_env") +@parameterized_class( + [ + { + "framework": "pytorch", + "script": "run_glue_model_parallelism.py", + "model_name_or_path": "FacebookAI/roberta-large", + "instance_type": "ml.p3dn.24xlarge", + "results": {"train_runtime": 1600, "eval_accuracy": 0.3, "eval_loss": 1.2}, + }, + { + "framework": "pytorch", + "script": "run_glue.py", + "model_name_or_path": "FacebookAI/roberta-large", + "instance_type": "ml.p3dn.24xlarge", + "results": {"train_runtime": 1600, "eval_accuracy": 0.3, "eval_loss": 1.2}, + }, + ] +) +class MultiNodeTest(unittest.TestCase): + def setUp(self): + if self.framework == "pytorch": + subprocess.run( + f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(), + encoding="utf-8", + check=True, + ) + assert hasattr(self, "env") + + def create_estimator(self, instance_count): + # configuration for running training on smdistributed Model Parallel + mpi_options = { + "enabled": True, + "processes_per_host": 8, + } + smp_options = { + "enabled": True, + "parameters": { + "microbatches": 4, + "placement_strategy": "spread", + "pipeline": "interleaved", + "optimize": "speed", + "partitions": 4, + "ddp": True, + }, + } + + distribution = {"smdistributed": {"modelparallel": smp_options}, "mpi": mpi_options} + + name_extension = "trainer" if self.script == "run_glue.py" else "smtrainer" + # creates estimator + return HuggingFace( + entry_point=self.script, + source_dir=self.env.test_path, + role=self.env.role, + image_uri=self.env.image_uri, + base_job_name=f"{self.env.base_job_name}-{instance_count}-smp-{name_extension}", + instance_count=instance_count, + instance_type=self.instance_type, + debugger_hook_config=False, + hyperparameters={ + **self.env.hyperparameters, + "model_name_or_path": self.model_name_or_path, + "max_steps": 500, + }, + metric_definitions=self.env.metric_definitions, + distribution=distribution, + py_version="py36", + ) + + def save_results_as_csv(self, job_name): + TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv") + + # @parameterized.expand([(2,), (4,),]) + @parameterized.expand([(1,)]) + def test_scripz(self, instance_count): + # create estimator + estimator = self.create_estimator(instance_count) + + # run training + estimator.fit() + + # result dataframe + result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() + + # extract kpis + eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]) + eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]) + # get train time from SageMaker job, this includes starting, preprocessing, stopping + train_runtime = ( + Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999) + ) + + # assert kpis + assert train_runtime <= self.results["train_runtime"] + assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy) + assert all(t <= self.results["eval_loss"] for t in eval_loss) + + # dump tests result into json file to share in PR + with open(f"{estimator.latest_training_job.name}.json", "w") as outfile: + json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_single_node_gpu.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_single_node_gpu.py new file mode 100644 index 0000000000000000000000000000000000000000..53d966bd1e8591233296c49c95385b8e19a3ead6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/sagemaker/test_single_node_gpu.py @@ -0,0 +1,95 @@ +import json +import os +import subprocess +import unittest +from ast import literal_eval + +import pytest +from parameterized import parameterized_class + +from . import is_sagemaker_available + + +if is_sagemaker_available(): + from sagemaker import Session, TrainingJobAnalytics + from sagemaker.huggingface import HuggingFace + + +@pytest.mark.skipif( + literal_eval(os.getenv("TEST_SAGEMAKER", "False")) is not True, + reason="Skipping test because should only be run when releasing minor transformers version", +) +@pytest.mark.usefixtures("sm_env") +@parameterized_class( + [ + { + "framework": "pytorch", + "script": "run_glue.py", + "model_name_or_path": "distilbert/distilbert-base-cased", + "instance_type": "ml.g4dn.xlarge", + "results": {"train_runtime": 650, "eval_accuracy": 0.6, "eval_loss": 0.9}, + }, + { + "framework": "tensorflow", + "script": "run_tf.py", + "model_name_or_path": "distilbert/distilbert-base-cased", + "instance_type": "ml.g4dn.xlarge", + "results": {"train_runtime": 600, "eval_accuracy": 0.3, "eval_loss": 0.9}, + }, + ] +) +class SingleNodeTest(unittest.TestCase): + def setUp(self): + if self.framework == "pytorch": + subprocess.run( + f"cp ./examples/pytorch/text-classification/run_glue.py {self.env.test_path}/run_glue.py".split(), + encoding="utf-8", + check=True, + ) + assert hasattr(self, "env") + + def create_estimator(self, instance_count=1): + # creates estimator + return HuggingFace( + entry_point=self.script, + source_dir=self.env.test_path, + role=self.env.role, + image_uri=self.env.image_uri, + base_job_name=f"{self.env.base_job_name}-single", + instance_count=instance_count, + instance_type=self.instance_type, + debugger_hook_config=False, + hyperparameters={**self.env.hyperparameters, "model_name_or_path": self.model_name_or_path}, + metric_definitions=self.env.metric_definitions, + py_version="py36", + ) + + def save_results_as_csv(self, job_name): + TrainingJobAnalytics(job_name).export_csv(f"{self.env.test_path}/{job_name}_metrics.csv") + + def test_glue(self): + # create estimator + estimator = self.create_estimator() + + # run training + estimator.fit() + + # result dataframe + result_metrics_df = TrainingJobAnalytics(estimator.latest_training_job.name).dataframe() + + # extract kpis + eval_accuracy = list(result_metrics_df[result_metrics_df.metric_name == "eval_accuracy"]["value"]) + eval_loss = list(result_metrics_df[result_metrics_df.metric_name == "eval_loss"]["value"]) + # get train time from SageMaker job, this includes starting, preprocessing, stopping + train_runtime = ( + Session().describe_training_job(estimator.latest_training_job.name).get("TrainingTimeInSeconds", 999999) + ) + + # assert kpis + assert train_runtime <= self.results["train_runtime"] + assert all(t >= self.results["eval_accuracy"] for t in eval_accuracy) + assert all(t <= self.results["eval_loss"] for t in eval_loss) + + # dump tests result into json file to share in PR + with open(f"{estimator.latest_training_job.name}.json", "w") as outfile: + json.dump({"train_time": train_runtime, "eval_accuracy": eval_accuracy, "eval_loss": eval_loss}, outfile) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tasksmith_behavior.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tasksmith_behavior.py new file mode 100644 index 0000000000000000000000000000000000000000..0a20685e91f77d3ca38104ff123a196997de76a7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tasksmith_behavior.py @@ -0,0 +1,224 @@ + +import pytest + + +def _make_tiny_metaclip2_config(): + from transformers import MetaClip2Config, MetaClip2TextConfig, MetaClip2VisionConfig + text_cfg = MetaClip2TextConfig( + vocab_size=64, hidden_size=32, intermediate_size=64, + projection_dim=32, num_hidden_layers=2, num_attention_heads=4, + max_position_embeddings=16, eos_token_id=3, + ) + vision_cfg = MetaClip2VisionConfig( + hidden_size=32, intermediate_size=64, projection_dim=32, + num_hidden_layers=2, num_attention_heads=4, + image_size=16, patch_size=4, + ) + return MetaClip2Config( + text_config=text_cfg.to_dict(), + vision_config=vision_cfg.to_dict(), + projection_dim=32, + ) + + +def test_clip_processor_tokenizer_class(): + """Accept a generic tokenizer through real combined text/image processing.""" + import numpy as np + processor, pixels = _local_clip_processor_fixture() + output = processor(text='hello world', images=pixels, return_tensors='np') + np.testing.assert_array_equal(output['input_ids'], np.array([[1, 2]])) + np.testing.assert_array_equal(output['pixel_values'], pixels.transpose(2, 0, 1)[None]) + + +def test_clip_processor_image_processor_class_unchanged(): + """Image-only processing preserves actual pixel values and channel layout.""" + import numpy as np + processor, pixels = _local_clip_processor_fixture() + output = processor(images=pixels, return_tensors='np') + np.testing.assert_array_equal(output['pixel_values'], pixels.transpose(2, 0, 1)[None]) + assert 'input_ids' not in output + + +def test_metaclip2_config_defaults(): + from transformers import MetaClip2Config + cfg = MetaClip2Config() + assert cfg.model_type == "metaclip_2" + assert cfg.text_config.model_type == "metaclip_2_text_model" + assert cfg.vision_config.model_type == "metaclip_2_vision_model" + assert cfg.logit_scale_init_value == pytest.approx(2.6592) + assert cfg.projection_dim == 512 + assert cfg.text_config.hidden_size == 512 + assert cfg.vision_config.hidden_size == 768 + + +def test_autoconfig_for_metaclip2(): + from transformers import AutoConfig, MetaClip2Config + cls = AutoConfig.for_model("metaclip_2") + assert isinstance(cls, MetaClip2Config) + + +def test_metaclip2_text_model_eos_pooling(): + import torch + from transformers import MetaClip2TextModel, MetaClip2TextConfig + cfg = MetaClip2TextConfig( + vocab_size=64, hidden_size=32, intermediate_size=64, + projection_dim=32, num_hidden_layers=2, num_attention_heads=4, + max_position_embeddings=16, eos_token_id=3, + ) + model = MetaClip2TextModel(cfg).eval() + # Batch of 2; place EOS at position 4 and 6 respectively + input_ids = torch.full((2, 10), 27, dtype=torch.long) + input_ids[0, 4] = 3 # EOS at position 4 + input_ids[1, 6] = 3 # EOS at position 6 + input_ids[:, 8] = 3 # a later EOS must not replace the first + with torch.no_grad(): + out = model(input_ids=input_ids) + assert out.last_hidden_state.shape == (2, 10, 32) + assert out.pooler_output.shape == (2, 32) + # pooler_output should equal last_hidden_state at EOS positions + assert torch.allclose(out.pooler_output[0], out.last_hidden_state[0, 4]) + assert torch.allclose(out.pooler_output[1], out.last_hidden_state[1, 6]) + + +def test_metaclip2_model_normalized_logits(): + import torch + cfg = _make_tiny_metaclip2_config() + from transformers import MetaClip2Model + model = MetaClip2Model(cfg).eval() + batch = 2 + seq_len = 8 + input_ids = torch.randint(0, 64, (batch, seq_len)) + input_ids[:, -1] = 3 # place EOS + pixel_values = torch.randn(batch, 3, 16, 16) + with torch.no_grad(): + out = model(input_ids=input_ids, pixel_values=pixel_values) + # embeddings should be L2-normalized + img_norm = out.image_embeds.norm(dim=-1) + txt_norm = out.text_embeds.norm(dim=-1) + assert torch.allclose(img_norm, torch.ones_like(img_norm), atol=1e-5) + assert torch.allclose(txt_norm, torch.ones_like(txt_norm), atol=1e-5) + # logits_per_image == logits_per_text.T + assert out.logits_per_image.shape == (batch, batch) + assert torch.allclose(out.logits_per_image, out.logits_per_text.T, atol=1e-5) + + +def test_metaclip2_model_return_loss(): + import torch + cfg = _make_tiny_metaclip2_config() + from transformers import MetaClip2Model + model = MetaClip2Model(cfg).eval() + batch = 3 + input_ids = torch.randint(0, 64, (batch, 8)) + input_ids[:, -1] = 3 + pixel_values = torch.randn(batch, 3, 16, 16) + with torch.no_grad(): + out = model(input_ids=input_ids, pixel_values=pixel_values, return_loss=True) + assert out.loss is not None + assert out.loss.shape == () + assert out.loss.isfinite() + + +def test_metaclip2_image_classifier_patch_pooling(): + import torch + from transformers import MetaClip2ForImageClassification, MetaClip2Config, MetaClip2VisionConfig + vision_cfg = MetaClip2VisionConfig( + hidden_size=32, intermediate_size=64, projection_dim=32, + num_hidden_layers=2, num_attention_heads=4, + image_size=16, patch_size=4, + ) + cfg = MetaClip2Config(vision_config=vision_cfg.to_dict(), num_labels=5) + model = MetaClip2ForImageClassification(cfg).eval() + pixel_values = torch.randn(2, 3, 16, 16) + with torch.no_grad(): + out = model(pixel_values=pixel_values) + # 16x16 image, patch_size=4 -> 4x4=16 patches + 1 CLS = 17 tokens; logits shape (2, 5) + assert out.logits.shape == (2, 5) + # gradient flows + model.train() + out2 = model(pixel_values=pixel_values) + out2.logits.sum().backward() + assert model.classifier.weight.grad is not None + +@pytest.fixture(autouse=True) +def _actual_cuda(): + import torch + assert torch.cuda.is_available() + torch.backends.cuda.matmul.allow_tf32=False + with torch.device('cuda'): + yield + + +def test_metaclip2_cuda_matches_clip_architecture_and_gradients(): + import torch + from transformers import CLIPConfig, CLIPModel, MetaClip2Model + torch.manual_seed(113) + cfg=_make_tiny_metaclip2_config() + clip_config=CLIPConfig(text_config=cfg.text_config.to_dict(),vision_config=cfg.vision_config.to_dict(),projection_dim=cfg.projection_dim) + reference=CLIPModel(clip_config).eval() + model=MetaClip2Model(cfg).eval() + model.load_state_dict(reference.state_dict(),strict=True) + ids=torch.tensor([[29,18,3,7,3,0],[12,27,16,3,8,3],[31,20,6,10,3,0]]) + pixels=torch.randn(3,3,16,16) + actual=model(input_ids=ids,pixel_values=pixels,return_loss=True) + expected=reference(input_ids=ids,pixel_values=pixels,return_loss=True) + assert actual.logits_per_image.is_cuda + for name in ['logits_per_image','logits_per_text','text_embeds','image_embeds','loss']: + torch.testing.assert_close(getattr(actual,name),getattr(expected,name),atol=3e-5,rtol=3e-5) + labels=torch.arange(3) + logits=actual.image_embeds @ actual.text_embeds.T * model.logit_scale.exp() + independent=(torch.nn.functional.cross_entropy(logits,labels)+torch.nn.functional.cross_entropy(logits.T,labels))/2 + torch.testing.assert_close(actual.loss,independent,atol=2e-5,rtol=2e-5) + actual.loss.backward();expected.loss.backward() + for (name,p),(other_name,q) in zip(model.named_parameters(),reference.named_parameters(),strict=True): + assert name==other_name + if q.grad is not None: + assert p.grad is not None + torch.testing.assert_close(p.grad,q.grad,atol=5e-5,rtol=1e-4) + + +def test_metaclip2_save_load_autoclass_offline(tmp_path): + import torch + from transformers import AutoConfig,AutoModel,MetaClip2Config,MetaClip2Model + model=MetaClip2Model(_make_tiny_metaclip2_config()).eval() + model.save_pretrained(tmp_path) + assert isinstance(AutoConfig.from_pretrained(tmp_path,local_files_only=True),MetaClip2Config) + restored=AutoModel.from_pretrained(tmp_path,local_files_only=True).eval() + assert isinstance(restored,MetaClip2Model) + ids=torch.tensor([[9,3,0,0],[17,22,3,0]]) + pixels=torch.randn(2,3,16,16) + with torch.no_grad(): + a=model(input_ids=ids,pixel_values=pixels) + b=restored(input_ids=ids,pixel_values=pixels) + torch.testing.assert_close(a.logits_per_image,b.logits_per_image) + + +def test_clip_processor_accepts_non_clip_tokenizer(tmp_path): + from tokenizers import Tokenizer + from tokenizers.models import WordLevel + from tokenizers.pre_tokenizers import Whitespace + from transformers import PreTrainedTokenizerFast,CLIPImageProcessor,CLIPProcessor + backend=Tokenizer(WordLevel({'[UNK]':0,'hello':1,'world':2},unk_token='[UNK]')) + backend.pre_tokenizer=Whitespace() + tokenizer=PreTrainedTokenizerFast(tokenizer_object=backend,unk_token='[UNK]') + processor=CLIPProcessor(image_processor=CLIPImageProcessor(),tokenizer=tokenizer) + processor.save_pretrained(tmp_path) + restored=CLIPProcessor.from_pretrained(tmp_path,local_files_only=True) + assert restored(text='hello world')['input_ids']==[1,2] + + +def _local_clip_processor_fixture(): + import numpy as np + from tokenizers import Tokenizer + from tokenizers.models import WordLevel + from tokenizers.pre_tokenizers import Whitespace + from transformers import PreTrainedTokenizerFast, CLIPImageProcessor, CLIPProcessor + + backend = Tokenizer(WordLevel({'[UNK]': 0, 'hello': 1, 'world': 2}, unk_token='[UNK]')) + backend.pre_tokenizer = Whitespace() + tokenizer = PreTrainedTokenizerFast(tokenizer_object=backend, unk_token='[UNK]') + image_processor = CLIPImageProcessor( + do_resize=False, do_center_crop=False, do_rescale=False, do_normalize=False, + ) + processor = CLIPProcessor(image_processor=image_processor, tokenizer=tokenizer) + pixels = np.arange(4 * 4 * 3, dtype=np.uint8).reshape(4, 4, 3) + return processor, pixels diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tensor_parallel/test_tensor_parallel.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tensor_parallel/test_tensor_parallel.py new file mode 100644 index 0000000000000000000000000000000000000000..14fd1a0904b49e0fb89efed8fd5c8d755cc82f7c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tensor_parallel/test_tensor_parallel.py @@ -0,0 +1,220 @@ +# 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. + +# Run the test: CUDA_VISIBLE_DEVICES=0,1 RUN_SLOW=1 pytest -sv tests/tensor_parallel/test_tensor_parallel.py + +import os +import tempfile +import textwrap + +from transformers import is_torch_available +from transformers.integrations.tensor_parallel import get_packed_weights, repack_weights +from transformers.testing_utils import ( + TestCasePlus, + backend_device_count, + require_huggingface_hub_greater_or_equal, + require_torch_multi_accelerator, + torch_device, + torchrun, +) + + +if is_torch_available(): + import torch + + +class TestTensorParallelUtils(TestCasePlus): + def test_packed_unpacked_conversion(self): + WORLD_SIZE = 2 + PACKED_BLOCK_SIZE = 800 + SHARDING_DIM = 2 + NUM_BLOCKS = 2 + + original_packed_weights = torch.randn(4, 512, 2 * PACKED_BLOCK_SIZE) + original_packed_weights.get_dtype = lambda: "F32" # get_packed_weights expects PySlice object + empty_param = torch.empty(4, 512, 2 * PACKED_BLOCK_SIZE) + + class MockDeviceMesh: + def size(self): + return WORLD_SIZE + + mock_mesh = ( + MockDeviceMesh() + ) # get_packed_weights only calls `.size()`, do this to avoid doing actual distributed run + + packed_weights_0 = get_packed_weights(original_packed_weights, empty_param, mock_mesh, 0, SHARDING_DIM) + packed_weights_1 = get_packed_weights(original_packed_weights, empty_param, mock_mesh, 1, SHARDING_DIM) + + # simulate all gather of sharded weights + packed_weights = torch.cat([packed_weights_0, packed_weights_1], dim=SHARDING_DIM) + unpacked_weights = repack_weights(packed_weights, SHARDING_DIM, WORLD_SIZE, NUM_BLOCKS) + + assert torch.allclose(unpacked_weights, original_packed_weights) + + +class TestTensorParallel(TestCasePlus): + nproc_per_node = 2 + + def test_model_forward(self): + script_to_run = textwrap.dedent( + """ + import torch + import os + from transformers import AutoModelForCausalLM, AutoTokenizer + + model_id = "JackFram/llama-68m" + + rank = int(os.environ["RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + + model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", tp_plan="auto") + torch.distributed.barrier() + + has_dtensor = 0 + for name, parameter in model.named_parameters(): + if isinstance(parameter.data, torch.distributed.tensor.DTensor): + has_dtensor = 1 + break + + assert has_dtensor == 1, "TP model must has DTensor" + + tokenizer = AutoTokenizer.from_pretrained(model_id, legacy=False) + prompt = "Can I help" + + inputs = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device) + outputs = model(inputs) + + next_token_logits = outputs[0][:, -1, :] + next_token = torch.argmax(next_token_logits, dim=-1) + response = tokenizer.decode(next_token) + assert response == "with" + + torch.distributed.barrier() + torch.distributed.destroy_process_group() + """ + ) + torchrun(script_to_run, self.nproc_per_node, env=self.get_env()) + + def test_model_backward_pass(self): + script_to_run = textwrap.dedent( + """ + import torch + import os + from transformers import AutoModelForCausalLM + from torch import nn + + model_id = "JackFram/llama-68m" + + model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float32, tp_plan="auto") + torch.distributed.barrier() + + # Dummy forward and backward pass + # Note that loss.backward() will fail if there is a bug in the TP implementation + inputs = torch.randint(0, model.config.vocab_size, (2, 10), device=model.device) + labels = torch.randint(0, model.config.vocab_size, (2, 10), device=model.device) + loss = model(inputs, labels=labels).loss + loss.backward() + + torch.distributed.barrier() + torch.distributed.destroy_process_group() + """ + ) + torchrun(script_to_run, self.nproc_per_node, env=self.get_env()) + + def test_model_generate(self): + script_to_run = textwrap.dedent( + """ + import torch + import os + from transformers import AutoModelForCausalLM, AutoTokenizer + + model_id = "JackFram/llama-68m" + + rank = int(os.environ["RANK"]) + world_size = int(os.environ["WORLD_SIZE"]) + + model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", tp_plan="auto") + torch.distributed.barrier() + + model.forward = torch.compile(model.forward) + + has_dtensor = 0 + for name, parameter in model.named_parameters(): + if isinstance(parameter.data, torch.distributed.tensor.DTensor): + has_dtensor = 1 + break + + assert has_dtensor == 1, "TP model must has DTensor" + + tokenizer = AutoTokenizer.from_pretrained(model_id) + prompt = "Can I help" + + inputs = tokenizer(prompt, return_tensors="pt").input_ids.to(model.device) + outputs = model.generate(inputs, max_new_tokens=10, cache_implementation="static") + + output_text = tokenizer.batch_decode(outputs, skip_special_tokens=True) + assert output_text[0].startswith(prompt), f"Expected output to start with '{prompt}', got '{output_text[0]}'" + + torch.distributed.barrier() + torch.distributed.destroy_process_group() + """ + ) + torchrun(script_to_run, self.nproc_per_node, env=self.get_env()) + + @require_huggingface_hub_greater_or_equal("0.31.4") + def test_model_save(self): + from safetensors import safe_open + + with tempfile.TemporaryDirectory() as tmp_dir: + for is_torchrun in [True, False]: + script_to_run = textwrap.dedent( + f""" + import torch + import os + from transformers import AutoModelForCausalLM + + model_id = "JackFram/llama-68m" + kwargs = dict() + + if os.environ.get("RANK", None) is not None: + kwargs["tp_plan"] = "auto" + result_dir = "{tmp_dir}/tp" + else: + result_dir = "{tmp_dir}/nontp" + + model = AutoModelForCausalLM.from_pretrained(model_id, **kwargs) + model.save_pretrained(result_dir) + """ + ) + torchrun(script_to_run, self.nproc_per_node, is_torchrun=is_torchrun, env=self.get_env()) + + non_tp_model_path = os.path.join(tmp_dir, "nontp") + tp_model_path = os.path.join(tmp_dir, "tp") + + for filename in os.listdir(non_tp_model_path): + if not filename.endswith(".safetensors"): + continue + + non_tp_model = safe_open(os.path.join(non_tp_model_path, filename), device="cpu", framework="pt") + tp_model = safe_open(os.path.join(tp_model_path, filename), device="cpu", framework="pt") + for non_tp_key in non_tp_model.keys(): + non_tp_tensor = non_tp_model.get_tensor(non_tp_key) + tp_tensor = tp_model.get_tensor(non_tp_key) + assert torch.allclose(non_tp_tensor, tp_tensor), f"Tensor with key: {non_tp_key} does not match" + del non_tp_tensor, tp_tensor + + +@require_torch_multi_accelerator +class TestTensorParallelAccelerator(TestTensorParallel): + nproc_per_node = backend_device_count(torch_device) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_backbone_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_backbone_common.py new file mode 100644 index 0000000000000000000000000000000000000000..d2229ad4b6f6acc4b58c481a8d25fecdb30d7aaf --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_backbone_common.py @@ -0,0 +1,226 @@ +# Copyright 2023 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. + +import copy +import inspect +import tempfile + +from transformers.testing_utils import require_torch, torch_device +from transformers.utils.backbone_utils import BackboneType + + +@require_torch +class BackboneTesterMixin: + all_model_classes = () + has_attentions = True + + def test_config(self): + config_class = self.config_class + + # test default config + config = config_class() + self.assertIsNotNone(config) + num_stages = len(config.depths) if hasattr(config, "depths") else config.num_hidden_layers + expected_stage_names = ["stem"] + [f"stage{idx}" for idx in range(1, num_stages + 1)] + self.assertEqual(config.stage_names, expected_stage_names) + self.assertTrue(set(config.out_features).issubset(set(config.stage_names))) + + # Test out_features and out_indices are correctly set + # out_features and out_indices both None + config = config_class(out_features=None, out_indices=None) + self.assertEqual(config.out_features, [config.stage_names[-1]]) + self.assertEqual(config.out_indices, [len(config.stage_names) - 1]) + + # out_features and out_indices both set + config = config_class(out_features=["stem", "stage1"], out_indices=[0, 1]) + self.assertEqual(config.out_features, ["stem", "stage1"]) + self.assertEqual(config.out_indices, [0, 1]) + + # Only out_features set + config = config_class(out_features=["stage1", "stage3"]) + self.assertEqual(config.out_features, ["stage1", "stage3"]) + self.assertEqual(config.out_indices, [1, 3]) + + # Only out_indices set + config = config_class(out_indices=[0, 2]) + self.assertEqual(config.out_features, [config.stage_names[0], config.stage_names[2]]) + self.assertEqual(config.out_indices, [0, 2]) + + # Error raised when out_indices do not correspond to out_features + with self.assertRaises(ValueError): + config = config_class(out_features=["stage1", "stage2"], out_indices=[0, 2]) + + def test_forward_signature(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + signature = inspect.signature(model.forward) + # signature.parameters is an OrderedDict => so arg_names order is deterministic + arg_names = [*signature.parameters.keys()] + expected_arg_names = ["pixel_values"] + self.assertListEqual(arg_names[:1], expected_arg_names) + + def test_config_save_pretrained(self): + config_class = self.config_class + config_first = config_class(out_indices=[0, 1, 2, 3]) + + with tempfile.TemporaryDirectory() as tmpdirname: + config_first.save_pretrained(tmpdirname) + config_second = self.config_class.from_pretrained(tmpdirname) + + self.assertEqual(config_second.to_dict(), config_first.to_dict()) + + def test_channels(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + self.assertEqual(len(model.channels), len(config.out_features)) + num_features = model.num_features + out_indices = [config.stage_names.index(feat) for feat in config.out_features] + out_channels = [num_features[idx] for idx in out_indices] + self.assertListEqual(model.channels, out_channels) + + new_config = copy.deepcopy(config) + new_config.out_features = None + model = model_class(new_config) + self.assertEqual(len(model.channels), 1) + self.assertListEqual(model.channels, [num_features[-1]]) + + new_config = copy.deepcopy(config) + new_config.out_indices = None + model = model_class(new_config) + self.assertEqual(len(model.channels), 1) + self.assertListEqual(model.channels, [num_features[-1]]) + + def test_create_from_modified_config(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + self.assertEqual(len(result.feature_maps), len(config.out_features)) + self.assertEqual(len(model.channels), len(config.out_features)) + self.assertEqual(len(result.feature_maps), len(config.out_indices)) + self.assertEqual(len(model.channels), len(config.out_indices)) + + # Check output of last stage is taken if out_features=None, out_indices=None + modified_config = copy.deepcopy(config) + modified_config.out_features = None + model = model_class(modified_config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + self.assertEqual(len(result.feature_maps), 1) + self.assertEqual(len(model.channels), 1) + + modified_config = copy.deepcopy(config) + modified_config.out_indices = None + model = model_class(modified_config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + self.assertEqual(len(result.feature_maps), 1) + self.assertEqual(len(model.channels), 1) + + # Check backbone can be initialized with fresh weights + modified_config = copy.deepcopy(config) + modified_config.use_pretrained_backbone = False + model = model_class(modified_config) + model.to(torch_device) + model.eval() + result = model(**inputs_dict) + + def test_backbone_common_attributes(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for backbone_class in self.all_model_classes: + backbone = backbone_class(config) + + self.assertTrue(hasattr(backbone, "backbone_type")) + self.assertTrue(hasattr(backbone, "stage_names")) + self.assertTrue(hasattr(backbone, "num_features")) + self.assertTrue(hasattr(backbone, "out_indices")) + self.assertTrue(hasattr(backbone, "out_features")) + self.assertTrue(hasattr(backbone, "out_feature_channels")) + self.assertTrue(hasattr(backbone, "channels")) + + self.assertIsInstance(backbone.backbone_type, BackboneType) + # Verify num_features has been initialized in the backbone init + self.assertIsNotNone(backbone.num_features) + self.assertTrue(len(backbone.channels) == len(backbone.out_indices)) + self.assertTrue(len(backbone.stage_names) == len(backbone.num_features)) + self.assertTrue(len(backbone.channels) <= len(backbone.num_features)) + self.assertTrue(len(backbone.out_feature_channels) == len(backbone.stage_names)) + + def test_backbone_outputs(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + batch_size = inputs_dict["pixel_values"].shape[0] + + for backbone_class in self.all_model_classes: + backbone = backbone_class(config) + backbone.to(torch_device) + backbone.eval() + + outputs = backbone(**inputs_dict) + + # Test default outputs and verify feature maps + self.assertIsInstance(outputs.feature_maps, tuple) + self.assertTrue(len(outputs.feature_maps) == len(backbone.channels)) + for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels): + self.assertTrue(feature_map.shape[:2], (batch_size, n_channels)) + self.assertIsNone(outputs.hidden_states) + self.assertIsNone(outputs.attentions) + + # Test output_hidden_states=True + outputs = backbone(**inputs_dict, output_hidden_states=True) + self.assertIsNotNone(outputs.hidden_states) + self.assertTrue(len(outputs.hidden_states), len(backbone.stage_names)) + for hidden_state, n_channels in zip(outputs.hidden_states, backbone.channels): + self.assertTrue(hidden_state.shape[:2], (batch_size, n_channels)) + + # Test output_attentions=True + if self.has_attentions: + outputs = backbone(**inputs_dict, output_attentions=True) + self.assertIsNotNone(outputs.attentions) + + def test_backbone_stage_selection(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + batch_size = inputs_dict["pixel_values"].shape[0] + + for backbone_class in self.all_model_classes: + config.out_indices = [-2, -1] + backbone = backbone_class(config) + backbone.to(torch_device) + backbone.eval() + + outputs = backbone(**inputs_dict) + + # Test number of feature maps returned + self.assertIsInstance(outputs.feature_maps, tuple) + self.assertTrue(len(outputs.feature_maps) == 2) + + # Order of channels returned is same as order of channels iterating over stage names + channels_from_stage_names = [ + backbone.out_feature_channels[name] for name in backbone.stage_names if name in backbone.out_features + ] + self.assertEqual(backbone.channels, channels_from_stage_names) + for feature_map, n_channels in zip(outputs.feature_maps, backbone.channels): + self.assertTrue(feature_map.shape[:2], (batch_size, n_channels)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_configuration_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_configuration_common.py new file mode 100644 index 0000000000000000000000000000000000000000..c47e23cc3ae5ad9ac7ed5afa2533102e980967ce --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_configuration_common.py @@ -0,0 +1,206 @@ +# Copyright 2019 HuggingFace 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. + +import copy +import json +import os +import tempfile +from pathlib import Path + +from transformers import is_torch_available +from transformers.utils import direct_transformers_import + +from .utils.test_configuration_utils import config_common_kwargs + + +transformers_module = direct_transformers_import(Path(__file__).parent) + + +class ConfigTester: + def __init__(self, parent, config_class=None, has_text_modality=True, common_properties=None, **kwargs): + self.parent = parent + self.config_class = config_class + self.has_text_modality = has_text_modality + self.inputs_dict = kwargs + self.common_properties = common_properties + + def create_and_test_config_common_properties(self): + config = self.config_class(**self.inputs_dict) + common_properties = ( + ["hidden_size", "num_attention_heads", "num_hidden_layers"] + if self.common_properties is None and not self.config_class.sub_configs + else self.common_properties + ) + common_properties = [] if common_properties is None else common_properties + + # Add common fields for text models + if self.has_text_modality: + common_properties.extend(["vocab_size"]) + + # Test that config has the common properties as getters + for prop in common_properties: + self.parent.assertTrue(hasattr(config, prop), msg=f"`{prop}` does not exist") + + # Test that config has the common properties as setter + for idx, name in enumerate(common_properties): + try: + setattr(config, name, idx) + self.parent.assertEqual( + getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" + ) + except NotImplementedError: + # Some models might not be able to implement setters for common_properties + # In that case, a NotImplementedError is raised + pass + + # Test if config class can be called with Config(prop_name=..) + for idx, name in enumerate(common_properties): + try: + config = self.config_class(**{name: idx}) + self.parent.assertEqual( + getattr(config, name), idx, msg=f"`{name} value {idx} expected, but was {getattr(config, name)}" + ) + except NotImplementedError: + # Some models might not be able to implement setters for common_properties + # In that case, a NotImplementedError is raised + pass + + def create_and_test_config_to_json_string(self): + config = self.config_class(**self.inputs_dict) + obj = json.loads(config.to_json_string()) + for key, value in self.inputs_dict.items(): + self.parent.assertEqual(obj[key], value) + + def create_and_test_config_to_json_file(self): + config_first = self.config_class(**self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "config.json") + config_first.to_json_file(json_file_path) + config_second = self.config_class.from_json_file(json_file_path) + + self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) + + def create_and_test_config_from_and_save_pretrained(self): + config_first = self.config_class(**self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + config_first.save_pretrained(tmpdirname) + config_second = self.config_class.from_pretrained(tmpdirname) + + self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) + + with self.parent.assertRaises(OSError): + self.config_class.from_pretrained(f".{tmpdirname}") + + def create_and_test_config_from_and_save_pretrained_subfolder(self): + config_first = self.config_class(**self.inputs_dict) + + subfolder = "test" + with tempfile.TemporaryDirectory() as tmpdirname: + sub_tmpdirname = os.path.join(tmpdirname, subfolder) + config_first.save_pretrained(sub_tmpdirname) + config_second = self.config_class.from_pretrained(tmpdirname, subfolder=subfolder) + + self.parent.assertEqual(config_second.to_dict(), config_first.to_dict()) + + def create_and_test_config_from_and_save_pretrained_composite(self): + """ + Tests that composite or nested configs can be loaded and saved correctly. In case the config + has a sub-config, we should be able to call `sub_config.from_pretrained('general_config_file')` + and get a result same as if we loaded the whole config and obtained `config.sub_config` from it. + """ + config = self.config_class(**self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + config.save_pretrained(tmpdirname) + general_config_loaded = self.config_class.from_pretrained(tmpdirname) + general_config_dict = config.to_dict() + + # Iterate over all sub_configs if there are any and load them with their own classes + sub_configs = general_config_loaded.sub_configs + for sub_config_key, sub_class in sub_configs.items(): + if sub_class.__name__ == "AutoConfig": + sub_class = sub_class.for_model(**general_config_dict[sub_config_key]).__class__ + sub_config_loaded = sub_class.from_pretrained(tmpdirname) + else: + sub_config_loaded = sub_class.from_pretrained(tmpdirname) + + # Pop `transformers_version`, it never exists when a config is part of a general composite config + # Verify that loading with subconfig class results in same dict as if we loaded with general composite config class + sub_config_loaded_dict = sub_config_loaded.to_dict() + sub_config_loaded_dict.pop("transformers_version", None) + general_config_dict[sub_config_key].pop("transformers_version", None) + self.parent.assertEqual(sub_config_loaded_dict, general_config_dict[sub_config_key]) + + # Verify that the loaded config type is same as in the general config + type_from_general_config = type(getattr(general_config_loaded, sub_config_key)) + self.parent.assertTrue(isinstance(sub_config_loaded, type_from_general_config)) + + # Now save only the sub-config and load it back to make sure the whole load-save-load pipeline works + with tempfile.TemporaryDirectory() as tmpdirname2: + sub_config_loaded.save_pretrained(tmpdirname2) + sub_config_loaded_2 = sub_class.from_pretrained(tmpdirname2) + self.parent.assertEqual(sub_config_loaded.to_dict(), sub_config_loaded_2.to_dict()) + + def create_and_test_config_with_num_labels(self): + config = self.config_class(**self.inputs_dict, num_labels=5) + self.parent.assertEqual(len(config.id2label), 5) + self.parent.assertEqual(len(config.label2id), 5) + + config.num_labels = 3 + self.parent.assertEqual(len(config.id2label), 3) + self.parent.assertEqual(len(config.label2id), 3) + + def check_config_can_be_init_without_params(self): + if self.config_class.has_no_defaults_at_init: + with self.parent.assertRaises(ValueError): + config = self.config_class() + else: + config = self.config_class() + self.parent.assertIsNotNone(config) + + def check_config_arguments_init(self): + if self.config_class.sub_configs: + return # TODO: @raushan composite models are not consistent in how they set general params + + kwargs = copy.deepcopy(config_common_kwargs) + config = self.config_class(**kwargs) + wrong_values = [] + for key, value in config_common_kwargs.items(): + if key == "torch_dtype": + if not is_torch_available(): + continue + else: + import torch + + if config.torch_dtype != torch.float16: + wrong_values.append(("torch_dtype", config.torch_dtype, torch.float16)) + elif getattr(config, key) != value: + wrong_values.append((key, getattr(config, key), value)) + + if len(wrong_values) > 0: + errors = "\n".join([f"- {v[0]}: got {v[1]} instead of {v[2]}" for v in wrong_values]) + raise ValueError(f"The following keys were not properly set in the config:\n{errors}") + + def run_common_tests(self): + self.create_and_test_config_common_properties() + self.create_and_test_config_to_json_string() + self.create_and_test_config_to_json_file() + self.create_and_test_config_from_and_save_pretrained() + self.create_and_test_config_from_and_save_pretrained_subfolder() + self.create_and_test_config_from_and_save_pretrained_composite() + self.create_and_test_config_with_num_labels() + self.check_config_can_be_init_without_params() + self.check_config_arguments_init() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_executorch.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_executorch.py new file mode 100644 index 0000000000000000000000000000000000000000..0e33253c08f1a0fd0f782934d2ee19d34ac74a97 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_executorch.py @@ -0,0 +1,129 @@ +# Copyright 2025 HuggingFace 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. + +import unittest + +import torch + +from transformers import AutoModelForCausalLM, set_seed +from transformers.generation.configuration_utils import GenerationConfig +from transformers.integrations.executorch import ( + TorchExportableModuleForDecoderOnlyLM, + TorchExportableModuleWithHybridCache, + TorchExportableModuleWithStaticCache, +) +from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_3 +from transformers.testing_utils import require_torch + + +@require_torch +class ExecutorchTest(unittest.TestCase): + def setUp(self): + if not is_torch_greater_or_equal_than_2_3: + self.skipTest("torch >= 2.3 is required") + + set_seed(0) + self.model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM") + self.model.eval() + + # Create generation config with static cache for the model + self.model.generation_config = GenerationConfig( + use_cache=True, + cache_implementation="static", + cache_config={"batch_size": 1, "max_cache_len": 32, "device": "cpu"}, + ) + + self.input_ids = torch.tensor([[1, 2, 3]], dtype=torch.long) + self.inputs_embeds = torch.randn(1, 3, self.model.config.hidden_size) + self.cache_position = torch.arange(3, dtype=torch.long) + + def test_static_cache_module_forward(self): + """Test TorchExportableModuleWithStaticCache forward with both input types""" + generation_config = GenerationConfig( + use_cache=True, + cache_implementation="static", + cache_config={"batch_size": 1, "max_cache_len": 32, "device": "cpu"}, + ) + + # Set generation config on model + self.model.generation_config = generation_config + module = TorchExportableModuleWithStaticCache(self.model) + + # Test with input_ids + eager_output_ids = self.model(input_ids=self.input_ids, use_cache=False).logits + wrapped_output_ids = module.forward(input_ids=self.input_ids, cache_position=self.cache_position) + torch.testing.assert_close(eager_output_ids, wrapped_output_ids, atol=1e-4, rtol=1e-4) + + # Test with inputs_embeds + eager_output_embeds = self.model(inputs_embeds=self.inputs_embeds, use_cache=False).logits + wrapped_output_embeds = module.forward(inputs_embeds=self.inputs_embeds, cache_position=self.cache_position) + torch.testing.assert_close(eager_output_embeds, wrapped_output_embeds, atol=1e-4, rtol=1e-4) + + def test_hybrid_cache_module_forward(self): + """Test TorchExportableModuleWithHybridCache forward with both input types""" + config = self.model.config + config.sliding_window = 16 + config.layer_types = ["full_attention"] * config.num_hidden_layers + + generation_config = GenerationConfig( + use_cache=True, + cache_implementation="hybrid", + cache_config={"batch_size": 1, "max_cache_len": 32, "device": "cpu"}, + ) + + # Set generation config on model + self.model.generation_config = generation_config + module = TorchExportableModuleWithHybridCache(self.model) + + # Test with input_ids + eager_output_ids = self.model(input_ids=self.input_ids, use_cache=False).logits + wrapped_output_ids = module.forward(input_ids=self.input_ids, cache_position=self.cache_position) + torch.testing.assert_close(eager_output_ids, wrapped_output_ids, atol=1e-4, rtol=1e-4) + + # Test with inputs_embeds + eager_output_embeds = self.model(inputs_embeds=self.inputs_embeds, use_cache=False).logits + wrapped_output_embeds = module.forward(inputs_embeds=self.inputs_embeds, cache_position=self.cache_position) + torch.testing.assert_close(eager_output_embeds, wrapped_output_embeds, atol=1e-4, rtol=1e-4) + + def test_decoder_only_lm_export_validation(self): + """Test TorchExportableModuleForDecoderOnlyLM export validation""" + module = TorchExportableModuleForDecoderOnlyLM(self.model) + + # Should fail with both input_ids and inputs_embeds + with self.assertRaises(ValueError): + module.export(input_ids=self.input_ids, inputs_embeds=self.inputs_embeds) + + # Should fail with neither + with self.assertRaises(ValueError): + module.export() + + def test_decoder_only_lm_export(self): + """Test TorchExportableModuleForDecoderOnlyLM export with both input types""" + module = TorchExportableModuleForDecoderOnlyLM(self.model) + + # Test export with input_ids + exported_program_ids = module.export(input_ids=self.input_ids, cache_position=self.cache_position) + eager_output_ids = self.model(input_ids=self.input_ids, use_cache=False).logits + exported_output_ids = exported_program_ids.module()( + input_ids=self.input_ids, cache_position=self.cache_position + ) + torch.testing.assert_close(eager_output_ids, exported_output_ids, atol=1e-4, rtol=1e-4) + + # Test export with inputs_embeds + exported_program_embeds = module.export(inputs_embeds=self.inputs_embeds, cache_position=self.cache_position) + eager_output_embeds = self.model(inputs_embeds=self.inputs_embeds, use_cache=False).logits + exported_output_embeds = exported_program_embeds.module()( + inputs_embeds=self.inputs_embeds, cache_position=self.cache_position + ) + torch.testing.assert_close(eager_output_embeds, exported_output_embeds, atol=1e-4, rtol=1e-4) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_feature_extraction_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_feature_extraction_common.py new file mode 100644 index 0000000000000000000000000000000000000000..be90ee316e9aaae98eef7cbc796b3666972f4be0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_feature_extraction_common.py @@ -0,0 +1,54 @@ +# Copyright 2021 HuggingFace 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. + + +import json +import os +import tempfile + +from transformers.testing_utils import check_json_file_has_correct_format + + +class FeatureExtractionSavingTestMixin: + test_cast_dtype = None + + def test_feat_extract_to_json_string(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + obj = json.loads(feat_extract.to_json_string()) + for key, value in self.feat_extract_dict.items(): + self.assertEqual(obj[key], value) + + def test_feat_extract_to_json_file(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "feat_extract.json") + feat_extract_first.to_json_file(json_file_path) + feat_extract_second = self.feature_extraction_class.from_json_file(json_file_path) + + self.assertEqual(feat_extract_second.to_dict(), feat_extract_first.to_dict()) + + def test_feat_extract_from_and_save_pretrained(self): + feat_extract_first = self.feature_extraction_class(**self.feat_extract_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = feat_extract_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + feat_extract_second = self.feature_extraction_class.from_pretrained(tmpdirname) + + self.assertEqual(feat_extract_second.to_dict(), feat_extract_first.to_dict()) + + def test_init_without_params(self): + feat_extract = self.feature_extraction_class() + self.assertIsNotNone(feat_extract) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_image_processing_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_image_processing_common.py new file mode 100644 index 0000000000000000000000000000000000000000..635d6a35dc859fdefe1dda21fb04c1de97fe8be9 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_image_processing_common.py @@ -0,0 +1,712 @@ +# Copyright 2023 HuggingFace 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. + +import inspect +import json +import os +import pathlib +import tempfile +import time +import warnings +from copy import deepcopy + +import numpy as np +import pytest +import requests +from packaging import version + +from transformers import AutoImageProcessor, BatchFeature +from transformers.image_utils import AnnotationFormat, AnnotionFormat +from transformers.testing_utils import ( + check_json_file_has_correct_format, + is_flaky, + require_torch, + require_torch_accelerator, + require_vision, + slow, + torch_device, +) +from transformers.utils import is_torch_available, is_torchvision_available, is_vision_available + + +if is_torchvision_available(): + from transformers.image_processing_utils_fast import BaseImageProcessorFast + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + +def prepare_image_inputs( + batch_size, + min_resolution, + max_resolution, + num_channels, + size_divisor=None, + equal_resolution=False, + numpify=False, + torchify=False, +): + """This function prepares a list of PIL images, or a list of numpy arrays if one specifies numpify=True, + or a list of PyTorch tensors if one specifies torchify=True. + + One can specify whether the images are of the same resolution or not. + """ + + assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" + + image_inputs = [] + for i in range(batch_size): + if equal_resolution: + width = height = max_resolution + else: + # To avoid getting image width/height 0 + if size_divisor is not None: + # If `size_divisor` is defined, the image needs to have width/size >= `size_divisor` + min_resolution = max(size_divisor, min_resolution) + width, height = np.random.choice(np.arange(min_resolution, max_resolution), 2) + image_inputs.append(np.random.randint(255, size=(num_channels, width, height), dtype=np.uint8)) + + if not numpify and not torchify: + # PIL expects the channel dimension as last dimension + image_inputs = [Image.fromarray(np.moveaxis(image, 0, -1)) for image in image_inputs] + + if torchify: + image_inputs = [torch.from_numpy(image) for image in image_inputs] + + if numpify: + # Numpy images are typically in channels last format + image_inputs = [image.transpose(1, 2, 0) for image in image_inputs] + + return image_inputs + + +def prepare_video(num_frames, num_channels, width=10, height=10, numpify=False, torchify=False): + """This function prepares a video as a list of PIL images/NumPy arrays/PyTorch tensors.""" + + video = [] + for i in range(num_frames): + video.append(np.random.randint(255, size=(num_channels, width, height), dtype=np.uint8)) + + if not numpify and not torchify: + # PIL expects the channel dimension as last dimension + video = [Image.fromarray(np.moveaxis(frame, 0, -1)) for frame in video] + + if torchify: + video = [torch.from_numpy(frame) for frame in video] + + return video + + +def prepare_video_inputs( + batch_size, + num_frames, + num_channels, + min_resolution, + max_resolution, + equal_resolution=False, + numpify=False, + torchify=False, +): + """This function prepares a batch of videos: a list of list of PIL images, or a list of list of numpy arrays if + one specifies numpify=True, or a list of list of PyTorch tensors if one specifies torchify=True. + + One can specify whether the videos are of the same resolution or not. + """ + + assert not (numpify and torchify), "You cannot specify both numpy and PyTorch tensors at the same time" + + video_inputs = [] + for _ in range(batch_size): + if equal_resolution: + width = height = max_resolution + else: + width, height = np.random.choice(np.arange(min_resolution, max_resolution), 2) + video = prepare_video( + num_frames=num_frames, + num_channels=num_channels, + width=width, + height=height, + numpify=numpify, + torchify=torchify, + ) + video_inputs.append(video) + + return video_inputs + + +class ImageProcessingTestMixin: + test_cast_dtype = None + image_processing_class = None + fast_image_processing_class = None + image_processors_list = None + test_slow_image_processor = True + test_fast_image_processor = True + + def setUp(self): + image_processor_list = [] + + if self.test_slow_image_processor and self.image_processing_class: + image_processor_list.append(self.image_processing_class) + + if self.test_fast_image_processor and self.fast_image_processing_class: + image_processor_list.append(self.fast_image_processing_class) + + self.image_processor_list = image_processor_list + + def _assert_slow_fast_tensors_equivalence(self, slow_tensor, fast_tensor, atol=1e-1, rtol=1e-3, mean_atol=5e-3): + torch.testing.assert_close(slow_tensor, fast_tensor, atol=atol, rtol=rtol) + self.assertLessEqual(torch.mean(torch.abs(slow_tensor - fast_tensor)).item(), mean_atol) + + @require_vision + @require_torch + def test_slow_fast_equivalence(self): + if not self.test_slow_image_processor or not self.test_fast_image_processor: + self.skipTest(reason="Skipping slow/fast equivalence test") + + if self.image_processing_class is None or self.fast_image_processing_class is None: + self.skipTest(reason="Skipping slow/fast equivalence test as one of the image processors is not defined") + + dummy_image = Image.open( + requests.get("http://images.cocodataset.org/val2017/000000039769.jpg", stream=True).raw + ) + image_processor_slow = self.image_processing_class(**self.image_processor_dict) + image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) + + encoding_slow = image_processor_slow(dummy_image, return_tensors="pt") + encoding_fast = image_processor_fast(dummy_image, return_tensors="pt") + self._assert_slow_fast_tensors_equivalence(encoding_slow.pixel_values, encoding_fast.pixel_values) + + @require_vision + @require_torch + def test_slow_fast_equivalence_batched(self): + if not self.test_slow_image_processor or not self.test_fast_image_processor: + self.skipTest(reason="Skipping slow/fast equivalence test") + + if self.image_processing_class is None or self.fast_image_processing_class is None: + self.skipTest(reason="Skipping slow/fast equivalence test as one of the image processors is not defined") + + if hasattr(self.image_processor_tester, "do_center_crop") and self.image_processor_tester.do_center_crop: + self.skipTest( + reason="Skipping as do_center_crop is True and center_crop functions are not equivalent for fast and slow processors" + ) + + dummy_images = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + image_processor_slow = self.image_processing_class(**self.image_processor_dict) + image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) + + encoding_slow = image_processor_slow(dummy_images, return_tensors="pt") + encoding_fast = image_processor_fast(dummy_images, return_tensors="pt") + + self._assert_slow_fast_tensors_equivalence(encoding_slow.pixel_values, encoding_fast.pixel_values) + + @require_vision + @require_torch + @is_flaky() + def test_fast_is_faster_than_slow(self): + if not self.test_slow_image_processor or not self.test_fast_image_processor: + self.skipTest(reason="Skipping speed test") + + if self.image_processing_class is None or self.fast_image_processing_class is None: + self.skipTest(reason="Skipping speed test as one of the image processors is not defined") + + def measure_time(image_processor, image): + # Warmup + for _ in range(5): + _ = image_processor(image, return_tensors="pt") + all_times = [] + for _ in range(10): + start = time.time() + _ = image_processor(image, return_tensors="pt") + all_times.append(time.time() - start) + # Take the average of the fastest 3 runs + avg_time = sum(sorted(all_times[:3])) / 3.0 + return avg_time + + dummy_images = [torch.randint(0, 255, (3, 224, 224), dtype=torch.uint8) for _ in range(4)] + image_processor_slow = self.image_processing_class(**self.image_processor_dict) + image_processor_fast = self.fast_image_processing_class(**self.image_processor_dict) + + fast_time = measure_time(image_processor_fast, dummy_images) + slow_time = measure_time(image_processor_slow, dummy_images) + + self.assertLessEqual(fast_time, slow_time) + + def test_is_fast(self): + for image_processing_class in self.image_processor_list: + image_processor = image_processing_class(**self.image_processor_dict) + + # Check is_fast is set correctly + if is_torchvision_available() and issubclass(image_processing_class, BaseImageProcessorFast): + self.assertTrue(image_processor.is_fast) + else: + self.assertFalse(image_processor.is_fast) + + def test_image_processor_to_json_string(self): + for image_processing_class in self.image_processor_list: + image_processor = image_processing_class(**self.image_processor_dict) + obj = json.loads(image_processor.to_json_string()) + for key, value in self.image_processor_dict.items(): + self.assertEqual(obj[key], value) + + def test_image_processor_to_json_file(self): + for image_processing_class in self.image_processor_list: + image_processor_first = image_processing_class(**self.image_processor_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "image_processor.json") + image_processor_first.to_json_file(json_file_path) + image_processor_second = image_processing_class.from_json_file(json_file_path) + + self.assertEqual(image_processor_second.to_dict(), image_processor_first.to_dict()) + + def test_image_processor_from_and_save_pretrained(self): + for image_processing_class in self.image_processor_list: + image_processor_first = image_processing_class(**self.image_processor_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = image_processor_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + image_processor_second = image_processing_class.from_pretrained(tmpdirname) + + self.assertEqual(image_processor_second.to_dict(), image_processor_first.to_dict()) + + def test_image_processor_save_load_with_autoimageprocessor(self): + for i, image_processing_class in enumerate(self.image_processor_list): + image_processor_first = image_processing_class(**self.image_processor_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = image_processor_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + + use_fast = i == 1 or not self.test_slow_image_processor + image_processor_second = AutoImageProcessor.from_pretrained(tmpdirname, use_fast=use_fast) + + self.assertEqual(image_processor_second.to_dict(), image_processor_first.to_dict()) + + def test_save_load_fast_slow(self): + "Test that we can load a fast image processor from a slow one and vice-versa." + if self.image_processing_class is None or self.fast_image_processing_class is None: + self.skipTest("Skipping slow/fast save/load test as one of the image processors is not defined") + + image_processor_dict = self.image_processor_tester.prepare_image_processor_dict() + image_processor_slow_0 = self.image_processing_class(**image_processor_dict) + + # Load fast image processor from slow one + with tempfile.TemporaryDirectory() as tmpdirname: + image_processor_slow_0.save_pretrained(tmpdirname) + image_processor_fast_0 = self.fast_image_processing_class.from_pretrained(tmpdirname) + + image_processor_fast_1 = self.fast_image_processing_class(**image_processor_dict) + + # Load slow image processor from fast one + with tempfile.TemporaryDirectory() as tmpdirname: + image_processor_fast_1.save_pretrained(tmpdirname) + image_processor_slow_1 = self.image_processing_class.from_pretrained(tmpdirname) + + dict_slow_0 = image_processor_slow_0.to_dict() + dict_slow_1 = image_processor_slow_1.to_dict() + difference = { + key: dict_slow_0.get(key) if key in dict_slow_0 else dict_slow_1.get(key) + for key in set(dict_slow_0) ^ set(dict_slow_1) + } + dict_slow_0 = {key: dict_slow_0[key] for key in set(dict_slow_0) & set(dict_slow_1)} + dict_slow_1 = {key: dict_slow_1[key] for key in set(dict_slow_0) & set(dict_slow_1)} + # check that all additional keys are None, except for `default_to_square` and `data_format` which are only set in fast processors + self.assertTrue( + all(value is None for key, value in difference.items() if key not in ["default_to_square", "data_format"]) + ) + # check that the remaining keys are the same + self.assertEqual(dict_slow_0, dict_slow_1) + + dict_fast_0 = image_processor_fast_0.to_dict() + dict_fast_1 = image_processor_fast_1.to_dict() + difference = { + key: dict_fast_0.get(key) if key in dict_fast_0 else dict_fast_1.get(key) + for key in set(dict_fast_0) ^ set(dict_fast_1) + } + dict_fast_0 = {key: dict_fast_0[key] for key in set(dict_fast_0) & set(dict_fast_1)} + dict_fast_1 = {key: dict_fast_1[key] for key in set(dict_fast_0) & set(dict_fast_1)} + # check that all additional keys are None, except for `default_to_square` and `data_format` which are only set in fast processors + self.assertTrue( + all(value is None for key, value in difference.items() if key not in ["default_to_square", "data_format"]) + ) + # check that the remaining keys are the same + self.assertEqual(dict_fast_0, dict_fast_1) + + def test_save_load_fast_slow_auto(self): + "Test that we can load a fast image processor from a slow one and vice-versa using AutoImageProcessor." + if self.image_processing_class is None or self.fast_image_processing_class is None: + self.skipTest("Skipping slow/fast save/load test as one of the image processors is not defined") + + image_processor_dict = self.image_processor_tester.prepare_image_processor_dict() + image_processor_slow_0 = self.image_processing_class(**image_processor_dict) + + # Load fast image processor from slow one + with tempfile.TemporaryDirectory() as tmpdirname: + image_processor_slow_0.save_pretrained(tmpdirname) + image_processor_fast_0 = AutoImageProcessor.from_pretrained(tmpdirname, use_fast=True) + + image_processor_fast_1 = self.fast_image_processing_class(**image_processor_dict) + + # Load slow image processor from fast one + with tempfile.TemporaryDirectory() as tmpdirname: + image_processor_fast_1.save_pretrained(tmpdirname) + image_processor_slow_1 = AutoImageProcessor.from_pretrained(tmpdirname, use_fast=False) + + dict_slow_0 = image_processor_slow_0.to_dict() + dict_slow_1 = image_processor_slow_1.to_dict() + difference = { + key: dict_slow_0.get(key) if key in dict_slow_0 else dict_slow_1.get(key) + for key in set(dict_slow_0) ^ set(dict_slow_1) + } + dict_slow_0 = {key: dict_slow_0[key] for key in set(dict_slow_0) & set(dict_slow_1)} + dict_slow_1 = {key: dict_slow_1[key] for key in set(dict_slow_0) & set(dict_slow_1)} + # check that all additional keys are None, except for `default_to_square` and `data_format` which are only set in fast processors + self.assertTrue( + all(value is None for key, value in difference.items() if key not in ["default_to_square", "data_format"]) + ) + # check that the remaining keys are the same + self.assertEqual(dict_slow_0, dict_slow_1) + + dict_fast_0 = image_processor_fast_0.to_dict() + dict_fast_1 = image_processor_fast_1.to_dict() + difference = { + key: dict_fast_0.get(key) if key in dict_fast_0 else dict_fast_1.get(key) + for key in set(dict_fast_0) ^ set(dict_fast_1) + } + dict_fast_0 = {key: dict_fast_0[key] for key in set(dict_fast_0) & set(dict_fast_1)} + dict_fast_1 = {key: dict_fast_1[key] for key in set(dict_fast_0) & set(dict_fast_1)} + # check that all additional keys are None, except for `default_to_square` and `data_format` which are only set in fast processors + self.assertTrue( + all(value is None for key, value in difference.items() if key not in ["default_to_square", "data_format"]) + ) + # check that the remaining keys are the same + self.assertEqual(dict_fast_0, dict_fast_1) + + def test_init_without_params(self): + for image_processing_class in self.image_processor_list: + image_processor = image_processing_class() + self.assertIsNotNone(image_processor) + + @require_torch + @require_vision + def test_cast_dtype_device(self): + for image_processing_class in self.image_processor_list: + if self.test_cast_dtype is not None: + # Initialize image_processor + image_processor = image_processing_class(**self.image_processor_dict) + + # create random PyTorch tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + + encoding = image_processor(image_inputs, return_tensors="pt") + # for layoutLM compatibility + self.assertEqual(encoding.pixel_values.device, torch.device("cpu")) + self.assertEqual(encoding.pixel_values.dtype, torch.float32) + + encoding = image_processor(image_inputs, return_tensors="pt").to(torch.float16) + self.assertEqual(encoding.pixel_values.device, torch.device("cpu")) + self.assertEqual(encoding.pixel_values.dtype, torch.float16) + + encoding = image_processor(image_inputs, return_tensors="pt").to("cpu", torch.bfloat16) + self.assertEqual(encoding.pixel_values.device, torch.device("cpu")) + self.assertEqual(encoding.pixel_values.dtype, torch.bfloat16) + + with self.assertRaises(TypeError): + _ = image_processor(image_inputs, return_tensors="pt").to(torch.bfloat16, "cpu") + + # Try with text + image feature + encoding = image_processor(image_inputs, return_tensors="pt") + encoding.update({"input_ids": torch.LongTensor([[1, 2, 3], [4, 5, 6]])}) + encoding = encoding.to(torch.float16) + + self.assertEqual(encoding.pixel_values.device, torch.device("cpu")) + self.assertEqual(encoding.pixel_values.dtype, torch.float16) + self.assertEqual(encoding.input_ids.dtype, torch.long) + + def test_call_pil(self): + for image_processing_class in self.image_processor_list: + # Initialize image_processing + image_processing = image_processing_class(**self.image_processor_dict) + # create random PIL images + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False) + for image in image_inputs: + self.assertIsInstance(image, Image.Image) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Test batched + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) + self.assertEqual( + tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) + ) + + def test_call_numpy(self): + for image_processing_class in self.image_processor_list: + # Initialize image_processing + image_processing = image_processing_class(**self.image_processor_dict) + # create random numpy tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) + for image in image_inputs: + self.assertIsInstance(image, np.ndarray) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Test batched + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) + self.assertEqual( + tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) + ) + + def test_call_pytorch(self): + for image_processing_class in self.image_processor_list: + # Initialize image_processing + image_processing = image_processing_class(**self.image_processor_dict) + # create random PyTorch tensors + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, torchify=True) + + for image in image_inputs: + self.assertIsInstance(image, torch.Tensor) + + # Test not batched input + encoded_images = image_processing(image_inputs[0], return_tensors="pt").pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Test batched + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) + encoded_images = image_processing(image_inputs, return_tensors="pt").pixel_values + self.assertEqual( + tuple(encoded_images.shape), + (self.image_processor_tester.batch_size, *expected_output_image_shape), + ) + + def test_call_numpy_4_channels(self): + for image_processing_class in self.image_processor_list: + # Test that can process images which have an arbitrary number of channels + # Initialize image_processing + image_processor = image_processing_class(**self.image_processor_dict) + + # create random numpy tensors + self.image_processor_tester.num_channels = 4 + image_inputs = self.image_processor_tester.prepare_image_inputs(equal_resolution=False, numpify=True) + + # Test not batched input + encoded_images = image_processor( + image_inputs[0], + return_tensors="pt", + input_data_format="channels_last", + image_mean=0, + image_std=1, + ).pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape([image_inputs[0]]) + self.assertEqual(tuple(encoded_images.shape), (1, *expected_output_image_shape)) + + # Test batched + encoded_images = image_processor( + image_inputs, + return_tensors="pt", + input_data_format="channels_last", + image_mean=0, + image_std=1, + ).pixel_values + expected_output_image_shape = self.image_processor_tester.expected_output_image_shape(image_inputs) + self.assertEqual( + tuple(encoded_images.shape), (self.image_processor_tester.batch_size, *expected_output_image_shape) + ) + + def test_image_processor_preprocess_arguments(self): + is_tested = False + + for image_processing_class in self.image_processor_list: + image_processor = image_processing_class(**self.image_processor_dict) + + # validation done by _valid_processor_keys attribute + if hasattr(image_processor, "_valid_processor_keys") and hasattr(image_processor, "preprocess"): + preprocess_parameter_names = inspect.getfullargspec(image_processor.preprocess).args + preprocess_parameter_names.remove("self") + preprocess_parameter_names.sort() + valid_processor_keys = image_processor._valid_processor_keys + valid_processor_keys.sort() + self.assertEqual(preprocess_parameter_names, valid_processor_keys) + is_tested = True + + # validation done by @filter_out_non_signature_kwargs decorator + if hasattr(image_processor.preprocess, "_filter_out_non_signature_kwargs"): + if hasattr(self.image_processor_tester, "prepare_image_inputs"): + inputs = self.image_processor_tester.prepare_image_inputs() + elif hasattr(self.image_processor_tester, "prepare_video_inputs"): + inputs = self.image_processor_tester.prepare_video_inputs() + else: + self.skipTest(reason="No valid input preparation method found") + + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter("always") + image_processor(inputs, extra_argument=True) + + messages = " ".join([str(w.message) for w in raised_warnings]) + self.assertGreaterEqual(len(raised_warnings), 1) + self.assertIn("extra_argument", messages) + is_tested = True + + if not is_tested: + self.skipTest(reason="No validation found for `preprocess` method") + + def test_override_instance_attributes_does_not_affect_other_instances(self): + if self.fast_image_processing_class is None: + self.skipTest( + "Only testing fast image processor, as most slow processors break this test and are to be deprecated" + ) + + image_processing_class = self.fast_image_processing_class + image_processor_1 = image_processing_class() + image_processor_2 = image_processing_class() + if not (hasattr(image_processor_1, "size") and isinstance(image_processor_1.size, dict)) or not ( + hasattr(image_processor_1, "image_mean") and isinstance(image_processor_1.image_mean, list) + ): + self.skipTest( + reason="Skipping test as the image processor does not have dict size or list image_mean attributes" + ) + + original_size_2 = deepcopy(image_processor_2.size) + for key in image_processor_1.size: + image_processor_1.size[key] = -1 + modified_copied_size_1 = deepcopy(image_processor_1.size) + + original_image_mean_2 = deepcopy(image_processor_2.image_mean) + image_processor_1.image_mean[0] = -1 + modified_copied_image_mean_1 = deepcopy(image_processor_1.image_mean) + + # check that the original attributes of the second instance are not affected + self.assertEqual(image_processor_2.size, original_size_2) + self.assertEqual(image_processor_2.image_mean, original_image_mean_2) + + for key in image_processor_2.size: + image_processor_2.size[key] = -2 + image_processor_2.image_mean[0] = -2 + + # check that the modified attributes of the first instance are not affected by the second instance + self.assertEqual(image_processor_1.size, modified_copied_size_1) + self.assertEqual(image_processor_1.image_mean, modified_copied_image_mean_1) + + @slow + @require_torch_accelerator + @require_vision + @pytest.mark.torch_compile_test + def test_can_compile_fast_image_processor(self): + if self.fast_image_processing_class is None: + self.skipTest("Skipping compilation test as fast image processor is not defined") + if version.parse(torch.__version__) < version.parse("2.3"): + self.skipTest(reason="This test requires torch >= 2.3 to run.") + + torch.compiler.reset() + input_image = torch.randint(0, 255, (3, 224, 224), dtype=torch.uint8) + image_processor = self.fast_image_processing_class(**self.image_processor_dict) + output_eager = image_processor(input_image, device=torch_device, return_tensors="pt") + + image_processor = torch.compile(image_processor, mode="reduce-overhead") + output_compiled = image_processor(input_image, device=torch_device, return_tensors="pt") + self._assert_slow_fast_tensors_equivalence( + output_eager.pixel_values, output_compiled.pixel_values, atol=1e-4, rtol=1e-4, mean_atol=1e-5 + ) + + +class AnnotationFormatTestMixin: + # this mixin adds a test to assert that usages of the + # to-be-deprecated `AnnotionFormat` continue to be + # supported for the time being + + def test_processor_can_use_legacy_annotation_format(self): + image_processor_dict = self.image_processor_tester.prepare_image_processor_dict() + fixtures_path = pathlib.Path(__file__).parent / "fixtures" / "tests_samples" / "COCO" + + with open(fixtures_path / "coco_annotations.txt") as f: + detection_target = json.loads(f.read()) + + detection_annotations = {"image_id": 39769, "annotations": detection_target} + + detection_params = { + "images": Image.open(fixtures_path / "000000039769.png"), + "annotations": detection_annotations, + "return_tensors": "pt", + } + + with open(fixtures_path / "coco_panoptic_annotations.txt") as f: + panoptic_target = json.loads(f.read()) + + panoptic_annotations = {"file_name": "000000039769.png", "image_id": 39769, "segments_info": panoptic_target} + + masks_path = pathlib.Path(fixtures_path / "coco_panoptic") + + panoptic_params = { + "images": Image.open(fixtures_path / "000000039769.png"), + "annotations": panoptic_annotations, + "return_tensors": "pt", + "masks_path": masks_path, + } + + test_cases = [ + ("coco_detection", detection_params), + ("coco_panoptic", panoptic_params), + (AnnotionFormat.COCO_DETECTION, detection_params), + (AnnotionFormat.COCO_PANOPTIC, panoptic_params), + (AnnotationFormat.COCO_DETECTION, detection_params), + (AnnotationFormat.COCO_PANOPTIC, panoptic_params), + ] + + def _compare(a, b) -> None: + if isinstance(a, (dict, BatchFeature)): + self.assertEqual(a.keys(), b.keys()) + for k, v in a.items(): + _compare(v, b[k]) + elif isinstance(a, list): + self.assertEqual(len(a), len(b)) + for idx in range(len(a)): + _compare(a[idx], b[idx]) + elif isinstance(a, torch.Tensor): + torch.testing.assert_close(a, b, rtol=1e-3, atol=1e-3) + elif isinstance(a, str): + self.assertEqual(a, b) + + for annotation_format, params in test_cases: + with self.subTest(annotation_format): + image_processor_params = {**image_processor_dict, **{"format": annotation_format}} + image_processor_first = self.image_processing_class(**image_processor_params) + + with tempfile.TemporaryDirectory() as tmpdirname: + image_processor_first.save_pretrained(tmpdirname) + image_processor_second = self.image_processing_class.from_pretrained(tmpdirname) + + # check the 'format' key exists and that the dicts of the + # first and second processors are equal + self.assertIn("format", image_processor_first.to_dict().keys()) + self.assertEqual(image_processor_second.to_dict(), image_processor_first.to_dict()) + + # perform encoding using both processors and compare + # the resulting BatchFeatures + first_encoding = image_processor_first(**params) + second_encoding = image_processor_second(**params) + _compare(first_encoding, second_encoding) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_image_transforms.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_image_transforms.py new file mode 100644 index 0000000000000000000000000000000000000000..313dc099f1438004332f84f36f587e684a1cffba --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_image_transforms.py @@ -0,0 +1,647 @@ +# Copyright 2022 HuggingFace 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. + +import unittest + +import numpy as np +from parameterized import parameterized + +from transformers.testing_utils import require_torch, require_vision +from transformers.utils.import_utils import is_torch_available, is_vision_available + + +if is_torch_available(): + import torch + +if is_vision_available(): + import PIL.Image + + from transformers.image_transforms import ( + center_crop, + center_to_corners_format, + convert_to_rgb, + corners_to_center_format, + flip_channel_order, + get_resize_output_image_size, + id_to_rgb, + normalize, + pad, + resize, + rgb_to_id, + to_channel_dimension_format, + to_pil_image, + ) + + +def get_random_image(height, width, num_channels=3, channels_first=True): + shape = (num_channels, height, width) if channels_first else (height, width, num_channels) + random_array = np.random.randint(0, 256, shape, dtype=np.uint8) + return random_array + + +@require_vision +class ImageTransformsTester(unittest.TestCase): + @parameterized.expand( + [ + ("numpy_float_channels_first", (3, 4, 5), np.float32), + ("numpy_float_channels_last", (4, 5, 3), np.float32), + ("numpy_float_channels_first", (3, 4, 5), np.float64), + ("numpy_float_channels_last", (4, 5, 3), np.float64), + ("numpy_int_channels_first", (3, 4, 5), np.int32), + ("numpy_uint_channels_first", (3, 4, 5), np.uint8), + ] + ) + @require_vision + def test_to_pil_image(self, name, image_shape, dtype): + image = np.random.randint(0, 256, image_shape).astype(dtype) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + # make sure image is correctly rescaled + self.assertTrue(np.abs(np.asarray(pil_image)).sum() > 0) + + @parameterized.expand( + [ + ("numpy_float_channels_first", (3, 4, 5), np.float32), + ("numpy_float_channels_first", (3, 4, 5), np.float64), + ("numpy_float_channels_last", (4, 5, 3), np.float32), + ("numpy_float_channels_last", (4, 5, 3), np.float64), + ] + ) + @require_vision + def test_to_pil_image_from_float(self, name, image_shape, dtype): + image = np.random.rand(*image_shape).astype(dtype) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + # make sure image is correctly rescaled + self.assertTrue(np.abs(np.asarray(pil_image)).sum() > 0) + + # Make sure that an exception is raised if image is not in [0, 1] + image = np.random.randn(*image_shape).astype(dtype) + with self.assertRaises(ValueError): + to_pil_image(image) + + @require_vision + def test_to_pil_image_from_mask(self): + # Make sure binary mask remains a binary mask + image = np.random.randint(0, 2, (3, 4, 5)).astype(np.uint8) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + np_img = np.asarray(pil_image) + self.assertTrue(np_img.min() == 0) + self.assertTrue(np_img.max() == 1) + + image = np.random.randint(0, 2, (3, 4, 5)).astype(np.float32) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + np_img = np.asarray(pil_image) + self.assertTrue(np_img.min() == 0) + self.assertTrue(np_img.max() == 1) + + @require_torch + def test_to_pil_image_from_torch(self): + # channels first + image = torch.rand((3, 4, 5)) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + # channels last + image = torch.rand((4, 5, 3)) + pil_image = to_pil_image(image) + self.assertIsInstance(pil_image, PIL.Image.Image) + self.assertEqual(pil_image.size, (5, 4)) + + def test_to_channel_dimension_format(self): + # Test that function doesn't reorder if channel dim matches the input. + image = np.random.rand(3, 4, 5) + image = to_channel_dimension_format(image, "channels_first") + self.assertEqual(image.shape, (3, 4, 5)) + + image = np.random.rand(4, 5, 3) + image = to_channel_dimension_format(image, "channels_last") + self.assertEqual(image.shape, (4, 5, 3)) + + # Test that function reorders if channel dim doesn't match the input. + image = np.random.rand(3, 4, 5) + image = to_channel_dimension_format(image, "channels_last") + self.assertEqual(image.shape, (4, 5, 3)) + + image = np.random.rand(4, 5, 3) + image = to_channel_dimension_format(image, "channels_first") + self.assertEqual(image.shape, (3, 4, 5)) + + # Can pass in input_data_format and works if data format is ambiguous or unknown. + image = np.random.rand(4, 5, 6) + image = to_channel_dimension_format(image, "channels_first", input_channel_dim="channels_last") + self.assertEqual(image.shape, (6, 4, 5)) + + def test_get_resize_output_image_size(self): + image = np.random.randint(0, 256, (3, 224, 224)) + + # Test the output size defaults to (x, x) if an int is given. + self.assertEqual(get_resize_output_image_size(image, 10), (10, 10)) + self.assertEqual(get_resize_output_image_size(image, [10]), (10, 10)) + self.assertEqual(get_resize_output_image_size(image, (10,)), (10, 10)) + + # Test the output size is the same as the input if a two element tuple/list is given. + self.assertEqual(get_resize_output_image_size(image, (10, 20)), (10, 20)) + self.assertEqual(get_resize_output_image_size(image, [10, 20]), (10, 20)) + self.assertEqual(get_resize_output_image_size(image, (10, 20), default_to_square=True), (10, 20)) + # To match pytorch behaviour, max_size is only relevant if size is an int + self.assertEqual(get_resize_output_image_size(image, (10, 20), max_size=5), (10, 20)) + + # Test output size = (int(size * height / width), size) if size is an int and height > width + image = np.random.randint(0, 256, (3, 50, 40)) + self.assertEqual(get_resize_output_image_size(image, 20, default_to_square=False), (25, 20)) + + # Test output size = (size, int(size * width / height)) if size is an int and width <= height + image = np.random.randint(0, 256, (3, 40, 50)) + self.assertEqual(get_resize_output_image_size(image, 20, default_to_square=False), (20, 25)) + + # Test size is resized if longer size > max_size + image = np.random.randint(0, 256, (3, 50, 40)) + self.assertEqual(get_resize_output_image_size(image, 20, default_to_square=False, max_size=22), (22, 17)) + + # Test output size = (int(size * height / width), size) if size is an int and height > width and + # input has 4 channels + image = np.random.randint(0, 256, (4, 50, 40)) + self.assertEqual( + get_resize_output_image_size(image, 20, default_to_square=False, input_data_format="channels_first"), + (25, 20), + ) + + # Test correct channel dimension is returned if output size if height == 3 + # Defaults to input format - channels first + image = np.random.randint(0, 256, (3, 18, 97)) + resized_image = resize(image, (3, 20)) + self.assertEqual(resized_image.shape, (3, 3, 20)) + + # Defaults to input format - channels last + image = np.random.randint(0, 256, (18, 97, 3)) + resized_image = resize(image, (3, 20)) + self.assertEqual(resized_image.shape, (3, 20, 3)) + + image = np.random.randint(0, 256, (3, 18, 97)) + resized_image = resize(image, (3, 20), data_format="channels_last") + self.assertEqual(resized_image.shape, (3, 20, 3)) + + image = np.random.randint(0, 256, (18, 97, 3)) + resized_image = resize(image, (3, 20), data_format="channels_first") + self.assertEqual(resized_image.shape, (3, 3, 20)) + + def test_resize(self): + image = np.random.randint(0, 256, (3, 224, 224)) + + # Check the channel order is the same by default + resized_image = resize(image, (30, 40)) + self.assertIsInstance(resized_image, np.ndarray) + self.assertEqual(resized_image.shape, (3, 30, 40)) + + # Check channel order is changed if specified + resized_image = resize(image, (30, 40), data_format="channels_last") + self.assertIsInstance(resized_image, np.ndarray) + self.assertEqual(resized_image.shape, (30, 40, 3)) + + # Check PIL.Image.Image is returned if return_numpy=False + resized_image = resize(image, (30, 40), return_numpy=False) + self.assertIsInstance(resized_image, PIL.Image.Image) + # PIL size is in (width, height) order + self.assertEqual(resized_image.size, (40, 30)) + + # Check an image with float values between 0-1 is returned with values in this range + image = np.random.rand(3, 224, 224) + resized_image = resize(image, (30, 40)) + self.assertIsInstance(resized_image, np.ndarray) + self.assertEqual(resized_image.shape, (3, 30, 40)) + self.assertTrue(np.all(resized_image >= 0)) + self.assertTrue(np.all(resized_image <= 1)) + + # Check that an image with 4 channels is resized correctly + image = np.random.randint(0, 256, (4, 224, 224)) + resized_image = resize(image, (30, 40), input_data_format="channels_first") + self.assertIsInstance(resized_image, np.ndarray) + self.assertEqual(resized_image.shape, (4, 30, 40)) + + def test_normalize(self): + image = np.random.randint(0, 256, (224, 224, 3)) / 255 + + # Test that exception is raised if inputs are incorrect + # Not a numpy array image + with self.assertRaises(TypeError): + normalize(5, 5, 5) + + # Number of mean values != number of channels + with self.assertRaises(ValueError): + normalize(image, mean=(0.5, 0.6), std=1) + + # Number of std values != number of channels + with self.assertRaises(ValueError): + normalize(image, mean=1, std=(0.5, 0.6)) + + # Test result is correct - output data format is channels_first and normalization + # correctly computed + mean = (0.5, 0.6, 0.7) + std = (0.1, 0.2, 0.3) + expected_image = ((image - mean) / std).transpose((2, 0, 1)) + + normalized_image = normalize(image, mean=mean, std=std, data_format="channels_first") + self.assertIsInstance(normalized_image, np.ndarray) + self.assertEqual(normalized_image.shape, (3, 224, 224)) + self.assertTrue(np.allclose(normalized_image, expected_image, atol=1e-6)) + + # Test image with 4 channels is normalized correctly + image = np.random.randint(0, 256, (224, 224, 4)) / 255 + mean = (0.5, 0.6, 0.7, 0.8) + std = (0.1, 0.2, 0.3, 0.4) + expected_image = (image - mean) / std + self.assertTrue( + np.allclose( + normalize(image, mean=mean, std=std, input_data_format="channels_last"), expected_image, atol=1e-6 + ) + ) + + # Test float32 image input keeps float32 dtype + image = np.random.randint(0, 256, (224, 224, 3)).astype(np.float32) / 255 + mean = (0.5, 0.6, 0.7) + std = (0.1, 0.2, 0.3) + expected_image = ((image - mean) / std).astype(np.float32) + normalized_image = normalize(image, mean=mean, std=std) + self.assertEqual(normalized_image.dtype, np.float32) + self.assertTrue(np.allclose(normalized_image, expected_image, atol=1e-6)) + + # Test float16 image input keeps float16 dtype + image = np.random.randint(0, 256, (224, 224, 3)).astype(np.float16) / 255 + mean = np.array((0.5, 0.6, 0.7)) + std = np.array((0.1, 0.2, 0.3)) + + # The mean and std are cast to match the dtype of the input image + cast_mean = np.array(mean, dtype=np.float16) + cast_std = np.array(std, dtype=np.float16) + expected_image = (image - cast_mean) / cast_std + normalized_image = normalize(image, mean=mean, std=std) + self.assertEqual(normalized_image.dtype, np.float16) + self.assertTrue(np.allclose(normalized_image, expected_image, atol=1e-6)) + + # Test int image input is converted to float32 + image = np.random.randint(0, 2, (224, 224, 3), dtype=np.uint8) + mean = (0.5, 0.6, 0.7) + std = (0.1, 0.2, 0.3) + expected_image = (image.astype(np.float32) - mean) / std + normalized_image = normalize(image, mean=mean, std=std) + self.assertEqual(normalized_image.dtype, np.float32) + self.assertTrue(np.allclose(normalized_image, expected_image, atol=1e-6)) + + def test_center_crop(self): + image = np.random.randint(0, 256, (3, 224, 224)) + + # Test that exception is raised if inputs are incorrect + with self.assertRaises(ValueError): + center_crop(image, 10) + + # Test result is correct - output data format is channels_first and center crop + # correctly computed + expected_image = image[:, 52:172, 82:142].transpose(1, 2, 0) + cropped_image = center_crop(image, (120, 60), data_format="channels_last") + self.assertIsInstance(cropped_image, np.ndarray) + self.assertEqual(cropped_image.shape, (120, 60, 3)) + self.assertTrue(np.allclose(cropped_image, expected_image)) + + # Test that image is padded with zeros if crop size is larger than image size + expected_image = np.zeros((300, 260, 3)) + expected_image[38:262, 18:242, :] = image.transpose((1, 2, 0)) + cropped_image = center_crop(image, (300, 260), data_format="channels_last") + self.assertIsInstance(cropped_image, np.ndarray) + self.assertEqual(cropped_image.shape, (300, 260, 3)) + self.assertTrue(np.allclose(cropped_image, expected_image)) + + # Test that odd numbered padding requirement still leads to correct output dimensions + cropped_image = center_crop(image, (300, 259), data_format="channels_last") + self.assertEqual(cropped_image.shape, (300, 259, 3)) + + # Test image with 4 channels is cropped correctly + image = np.random.randint(0, 256, (224, 224, 4)) + expected_image = image[52:172, 82:142, :] + self.assertTrue(np.allclose(center_crop(image, (120, 60), input_data_format="channels_last"), expected_image)) + + def test_center_to_corners_format(self): + bbox_center = np.array([[10, 20, 4, 8], [15, 16, 3, 4]]) + expected = np.array([[8, 16, 12, 24], [13.5, 14, 16.5, 18]]) + self.assertTrue(np.allclose(center_to_corners_format(bbox_center), expected)) + + # Check that the function and inverse function are inverse of each other + self.assertTrue(np.allclose(corners_to_center_format(center_to_corners_format(bbox_center)), bbox_center)) + + def test_corners_to_center_format(self): + bbox_corners = np.array([[8, 16, 12, 24], [13.5, 14, 16.5, 18]]) + expected = np.array([[10, 20, 4, 8], [15, 16, 3, 4]]) + self.assertTrue(np.allclose(corners_to_center_format(bbox_corners), expected)) + + # Check that the function and inverse function are inverse of each other + self.assertTrue(np.allclose(center_to_corners_format(corners_to_center_format(bbox_corners)), bbox_corners)) + + def test_rgb_to_id(self): + # test list input + rgb = [125, 4, 255] + self.assertEqual(rgb_to_id(rgb), 16712829) + + # test numpy array input + color = np.array( + [ + [ + [213, 54, 165], + [88, 207, 39], + [156, 108, 128], + ], + [ + [183, 194, 46], + [137, 58, 88], + [114, 131, 233], + ], + ] + ) + expected = np.array([[10827477, 2608984, 8416412], [3064503, 5782153, 15303538]]) + self.assertTrue(np.allclose(rgb_to_id(color), expected)) + + def test_id_to_rgb(self): + # test int input + self.assertEqual(id_to_rgb(16712829), [125, 4, 255]) + + # test array input + id_array = np.array([[10827477, 2608984, 8416412], [3064503, 5782153, 15303538]]) + color = np.array( + [ + [ + [213, 54, 165], + [88, 207, 39], + [156, 108, 128], + ], + [ + [183, 194, 46], + [137, 58, 88], + [114, 131, 233], + ], + ] + ) + self.assertTrue(np.allclose(id_to_rgb(id_array), color)) + + def test_pad(self): + # fmt: off + image = np.array([[ + [0, 1], + [2, 3], + ]]) + # fmt: on + + # Test that exception is raised if unknown padding mode is specified + with self.assertRaises(ValueError): + pad(image, 10, mode="unknown") + + # Test that exception is raised if invalid padding is specified + with self.assertRaises(ValueError): + # Cannot pad on channel dimension + pad(image, (5, 10, 10)) + + # Test image is padded equally on all sides is padding is an int + # fmt: off + expected_image = np.array([ + [[0, 0, 0, 0], + [0, 0, 1, 0], + [0, 2, 3, 0], + [0, 0, 0, 0]], + ]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, 1))) + + # Test the left and right of each axis is padded (pad_left, pad_right) + # fmt: off + expected_image = np.array( + [[0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [0, 0, 0, 1, 0], + [0, 0, 2, 3, 0], + [0, 0, 0, 0, 0]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, (2, 1)))) + + # Test only one axis is padded (pad_left, pad_right) + # fmt: off + expected_image = np.array([[ + [9, 9], + [9, 9], + [0, 1], + [2, 3], + [9, 9] + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((2, 1), (0, 0)), constant_values=9))) + + # Test padding with a constant value + # fmt: off + expected_image = np.array([[ + [8, 8, 0, 1, 9], + [8, 8, 2, 3, 9], + [8, 8, 7, 7, 9], + [8, 8, 7, 7, 9] + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), constant_values=((6, 7), (8, 9))))) + + # fmt: off + image = np.array([[ + [0, 1, 2], + [3, 4, 5], + [6, 7, 8], + ]]) + # fmt: on + + # Test padding with PaddingMode.REFLECT + # fmt: off + expected_image = np.array([[ + [2, 1, 0, 1, 2, 1], + [5, 4, 3, 4, 5, 4], + [8, 7, 6, 7, 8, 7], + [5, 4, 3, 4, 5, 4], + [2, 1, 0, 1, 2, 1], + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), mode="reflect"))) + + # Test padding with PaddingMode.REPLICATE + # fmt: off + expected_image = np.array([[ + [0, 0, 0, 1, 2, 2], + [3, 3, 3, 4, 5, 5], + [6, 6, 6, 7, 8, 8], + [6, 6, 6, 7, 8, 8], + [6, 6, 6, 7, 8, 8], + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), mode="replicate"))) + + # Test padding with PaddingMode.SYMMETRIC + # fmt: off + expected_image = np.array([[ + [1, 0, 0, 1, 2, 2], + [4, 3, 3, 4, 5, 5], + [7, 6, 6, 7, 8, 8], + [7, 6, 6, 7, 8, 8], + [4, 3, 3, 4, 5, 5], + ]]) + # fmt: on + self.assertTrue(np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), mode="symmetric"))) + + # Test we can specify the output data format + # Test padding with PaddingMode.REFLECT + # fmt: off + image = np.array([[ + [0, 1], + [2, 3], + ]]) + expected_image = np.array([ + [[0], [1], [0], [1], [0]], + [[2], [3], [2], [3], [2]], + [[0], [1], [0], [1], [0]], + [[2], [3], [2], [3], [2]] + ]) + # fmt: on + self.assertTrue( + np.allclose(expected_image, pad(image, ((0, 2), (2, 1)), mode="reflect", data_format="channels_last")) + ) + + # Test we can pad on an image with 2 channels + # fmt: off + image = np.array([ + [[0, 1], [2, 3]], + ]) + expected_image = np.array([ + [[0, 0], [0, 1], [2, 3]], + [[0, 0], [0, 0], [0, 0]], + ]) + # fmt: on + self.assertTrue( + np.allclose( + expected_image, pad(image, ((0, 1), (1, 0)), mode="constant", input_data_format="channels_last") + ) + ) + + # Test that padding works on batched images + image = np.array( + [ + [[0, 1], [2, 3]], + ] + )[None, ...] + expected_image = np.array( + [ + [[0, 0], [0, 1], [2, 3]], + [[0, 0], [0, 0], [0, 0]], + ] + )[None, ...] + # fmt: on + self.assertTrue( + np.allclose( + expected_image, pad(image, ((0, 1), (1, 0)), mode="constant", input_data_format="channels_last") + ) + ) + + @require_vision + def test_convert_to_rgb(self): + # Test that an RGBA image is converted to RGB + image = np.array([[[1, 2, 3, 4], [5, 6, 7, 8]]], dtype=np.uint8) + pil_image = PIL.Image.fromarray(image) + self.assertEqual(pil_image.mode, "RGBA") + self.assertEqual(pil_image.size, (2, 1)) + + # For the moment, numpy images are returned as is + rgb_image = convert_to_rgb(image) + self.assertEqual(rgb_image.shape, (1, 2, 4)) + self.assertTrue(np.allclose(rgb_image, image)) + + # And PIL images are converted + rgb_image = convert_to_rgb(pil_image) + self.assertEqual(rgb_image.mode, "RGB") + self.assertEqual(rgb_image.size, (2, 1)) + self.assertTrue(np.allclose(np.array(rgb_image), np.array([[[1, 2, 3], [5, 6, 7]]], dtype=np.uint8))) + + # Test that a grayscale image is converted to RGB + image = np.array([[0, 255]], dtype=np.uint8) + pil_image = PIL.Image.fromarray(image) + self.assertEqual(pil_image.mode, "L") + self.assertEqual(pil_image.size, (2, 1)) + rgb_image = convert_to_rgb(pil_image) + self.assertEqual(rgb_image.mode, "RGB") + self.assertEqual(rgb_image.size, (2, 1)) + self.assertTrue(np.allclose(np.array(rgb_image), np.array([[[0, 0, 0], [255, 255, 255]]], dtype=np.uint8))) + + def test_flip_channel_order(self): + # fmt: off + img_channels_first = np.array([ + [[ 0, 1, 2, 3], + [ 4, 5, 6, 7]], + + [[ 8, 9, 10, 11], + [12, 13, 14, 15]], + + [[16, 17, 18, 19], + [20, 21, 22, 23]], + ]) + # fmt: on + img_channels_last = np.moveaxis(img_channels_first, 0, -1) + # fmt: off + flipped_img_channels_first = np.array([ + [[16, 17, 18, 19], + [20, 21, 22, 23]], + + [[ 8, 9, 10, 11], + [12, 13, 14, 15]], + + [[ 0, 1, 2, 3], + [ 4, 5, 6, 7]], + ]) + # fmt: on + flipped_img_channels_last = np.moveaxis(flipped_img_channels_first, 0, -1) + + self.assertTrue(np.allclose(flip_channel_order(img_channels_first), flipped_img_channels_first)) + self.assertTrue( + np.allclose(flip_channel_order(img_channels_first, "channels_last"), flipped_img_channels_last) + ) + + self.assertTrue(np.allclose(flip_channel_order(img_channels_last), flipped_img_channels_last)) + self.assertTrue( + np.allclose(flip_channel_order(img_channels_last, "channels_first"), flipped_img_channels_first) + ) + + # Can flip when the image has 2 channels + # fmt: off + img_channels_first = np.array([ + [[ 0, 1, 2, 3], + [ 4, 5, 6, 7]], + + [[ 8, 9, 10, 11], + [12, 13, 14, 15]], + ]) + # fmt: on + flipped_img_channels_first = img_channels_first[::-1, :, :] + self.assertTrue( + np.allclose( + flip_channel_order(img_channels_first, input_data_format="channels_first"), flipped_img_channels_first + ) + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_modeling_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_modeling_common.py new file mode 100644 index 0000000000000000000000000000000000000000..a4022b9a83e148fd62b804042951ab4f264673bf --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_modeling_common.py @@ -0,0 +1,5125 @@ +# Copyright 2019 HuggingFace 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. +import collections +import copy +import gc +import inspect +import math +import os +import os.path +import random +import re +import tempfile +import unittest +import warnings +from collections import defaultdict +from contextlib import contextmanager + +import numpy as np +import pytest +from packaging import version +from parameterized import parameterized +from pytest import mark + +from transformers import ( + AutoModel, + AutoModelForCausalLM, + AutoModelForSequenceClassification, + DataCollatorWithFlattening, + PretrainedConfig, + PreTrainedModel, + is_torch_available, + logging, + set_seed, +) +from transformers.integrations import HfDeepSpeedConfig +from transformers.integrations.deepspeed import ( + is_deepspeed_available, + is_deepspeed_zero3_enabled, + unset_hf_deepspeed_config, +) +from transformers.modeling_utils import _get_tied_weight_keys +from transformers.models.auto import get_values +from transformers.models.auto.modeling_auto import ( + MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES, + MODEL_FOR_BACKBONE_MAPPING_NAMES, + MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES, + MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES, + MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES, + MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES, + MODEL_FOR_MASKED_LM_MAPPING_NAMES, + MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES, + MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES, + MODEL_FOR_PRETRAINING_MAPPING_NAMES, + MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES, + MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES, + MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES, + MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES, + MODEL_MAPPING_NAMES, +) +from transformers.testing_utils import ( + CaptureLogger, + backend_device_count, + backend_empty_cache, + backend_memory_allocated, + backend_torch_accelerator_module, + get_device_properties, + hub_retry, + is_flaky, + require_accelerate, + require_bitsandbytes, + require_deepspeed, + require_flash_attn, + require_flash_attn_3, + require_kernels, + require_non_hpu, + require_safetensors, + require_torch, + require_torch_accelerator, + require_torch_gpu, + require_torch_greater_or_equal, + require_torch_mps, + require_torch_multi_accelerator, + require_torch_multi_gpu, + require_torch_sdpa, + run_first, + run_test_using_subprocess, + set_config_for_less_flaky_test, + set_model_for_less_flaky_test, + set_model_tester_for_less_flaky_test, + slow, + torch_device, +) +from transformers.utils import ( + CONFIG_NAME, + GENERATION_CONFIG_NAME, + SAFE_WEIGHTS_NAME, + is_accelerate_available, + is_torch_bf16_available_on_device, + is_torch_fp16_available_on_device, + is_torch_sdpa_available, +) +from transformers.utils.generic import ContextManagers + +from .generation.test_utils import GenerationTesterMixin + + +if is_accelerate_available(): + from accelerate.utils import compute_module_sizes + + +if is_torch_available(): + import torch + import torch.nn.functional as F + from safetensors.torch import load_file as safe_load_file + from safetensors.torch import save_file as safe_save_file + from torch import nn + + from transformers import MODEL_MAPPING + from transformers.cache_utils import Cache, DynamicCache + from transformers.modeling_utils import load_state_dict, no_init_weights + from transformers.pytorch_utils import id_tensor_storage + +from transformers.utils.fx import _FX_SUPPORTED_MODELS_WITH_KV_CACHE, symbolic_trace + + +if is_deepspeed_available(): + import deepspeed + + +# used in other test files e.g. when overwriting the test +TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION = [ + ( + # test name for the test runner + f"{dtype}_pad_{padding_side}{'' if use_attention_mask else '_no_attn_mask'}" + f"{'_sdpa_kernels' if enable_kernels else ''}", + # parameterization + *(dtype, padding_side, use_attention_mask, False, enable_kernels), + ) + for dtype in ("fp16", "fp32", "bf16") + for padding_side in ("left", "right") + for use_attention_mask in (True, False) + for enable_kernels in (True, False) + # Extra test case: `output_attentions=True` has special attention mask handling and sdpa reverts to eager +] + [("fp32_pad_left_output_attentions", "fp32", "left", True, True, False)] + + +def _test_eager_matches_sdpa_inference( + self, + name, + torch_dtype, + padding_side, + use_attention_mask, + output_attentions, + enable_kernels, + atols=None, + rtols=None, +): + """ + This test is written as a regular function to be able to overload it easily with different tolerances. + Otherwise, `paramterezie.expand` prevents it as it removes the original function from the namespace. + """ + # TODO: we shouldn't need to do this skip, i.e. the test would be composable from the model tester. CLIP-like + # models have a custom mixin, which we detect to skip this test. + if any(".CLIPModelTesterMixin" in str(base) for base in self.__class__.__bases__): + self.skipTest(reason="CLIP-like models have a different `test_eager_matches_sdpa_inference`") + + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + if not self.all_model_classes[0]._supports_sdpa: + self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA") + + # convert shorthand name to torch.dtype + if torch_dtype == "fp16": + torch_dtype = torch.float16 + elif torch_dtype == "bf16": + torch_dtype = torch.bfloat16 + elif torch_dtype == "fp32": + torch_dtype = torch.float32 + + if not is_torch_fp16_available_on_device(torch_device) and torch_dtype == torch.float16: + self.skipTest(f"float16 not supported on {torch_device} (on the specific device currently used)") + + if not is_torch_bf16_available_on_device(torch_device) and torch_dtype == torch.bfloat16: + self.skipTest( + f"bfloat16 not supported on {torch_device} (on the specific device currently used, e.g. Nvidia T4 GPU)" + ) + + # Dictionary of tolerances for eager <> sdpa tests. Key = (device, sdpa_kernels_enabled, dtype) + if atols is None: + atols = { + ("cpu", False, torch.float32): 1e-6, + ("cpu", False, torch.float16): 5e-3, + ("cpu", False, torch.bfloat16): 1e-2, + ("cpu", True, torch.float32): 1e-6, + ("cpu", True, torch.float16): 5e-3, + ("cpu", True, torch.bfloat16): 1e-2, + ("cuda", False, torch.float32): 1e-6, + ("cuda", False, torch.bfloat16): 1e-2, + ("cuda", False, torch.float16): 5e-3, + ("cuda", True, torch.float32): 1e-6, + ("cuda", True, torch.bfloat16): 1e-2, + ("cuda", True, torch.float16): 5e-3, + } + if rtols is None: + rtols = { + ("cpu", False, torch.float32): 1e-4, + ("cpu", False, torch.float16): 5e-3, + ("cpu", False, torch.bfloat16): 1e-2, + ("cpu", True, torch.float32): 1e-4, + ("cpu", True, torch.float16): 5e-3, + ("cpu", True, torch.bfloat16): 1e-2, + ("cuda", False, torch.float32): 1e-4, + ("cuda", False, torch.bfloat16): 1e-2, + ("cuda", False, torch.float16): 5e-3, + ("cuda", True, torch.float32): 1e-4, + ("cuda", True, torch.bfloat16): 3e-2, # (different from others) + ("cuda", True, torch.float16): 5e-3, + } + + set_model_tester_for_less_flaky_test(self) + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + set_config_for_less_flaky_test(config) + model = model_class(config) + # TODO: standardize the interfaces for musicgen models, see other todo in this test + if model.__class__.__name__ == "MusicgenMelodyForConditionalGeneration": + is_encoder_decoder = True + else: + is_encoder_decoder = model.config.is_encoder_decoder + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_from_pretrained_kwargs = { + "pretrained_model_name_or_path": tmpdirname, + "torch_dtype": torch_dtype, + } + + if hasattr(config, "use_mask_token") or "use_mask_token" in inspect.signature(model.__init__).parameters: + model_from_pretrained_kwargs["use_mask_token"] = True + + # TODO: remove this try/except, models should have a shared API + try: + model_sdpa = model_class.from_pretrained(**model_from_pretrained_kwargs, attn_implementation="sdpa") + except ValueError: + model_sdpa = model_class.from_pretrained(**model_from_pretrained_kwargs) + model_sdpa = model_sdpa.eval().to(torch_device) + + model_eager = model_class.from_pretrained(**model_from_pretrained_kwargs, attn_implementation="eager") + model_eager = model_eager.eval().to(torch_device) + + set_model_for_less_flaky_test(model_eager) + set_model_for_less_flaky_test(model_sdpa) + + can_output_attn = "output_attentions" in inspect.signature(model_sdpa.forward).parameters + if not (self.has_attentions and can_output_attn) and output_attentions: + self.skipTest(reason="Model does not support output_attentions") + + # TODO: if we can also check with `batch_size=1` without being flaky? + for batch_size in [7]: + # musicgen decoder models; TODO: find better abstraction + if ( + model.__class__.__name__.startswith("Musicgen") + and hasattr(self.model_tester, "num_codebooks") + and not hasattr(model_eager, "text_encoder") + ): + input_data_batch_size = batch_size * self.model_tester.num_codebooks + else: + input_data_batch_size = batch_size + + processed_inputs = {} + processed_inputs[model.main_input_name] = inputs_dict[model.main_input_name] + + for key in getattr(self, "additional_model_inputs", []): + # Some models don't have all `additional_model_inputs`, especially when we + # craft cases to test model in different settings + if key in inputs_dict: + processed_inputs[key] = inputs_dict[key] + + for key, value in processed_inputs.items(): + if torch.is_floating_point(value): + value = value.to(torch_dtype) + + # extend value to have at least `input_data_batch_size` elements + if value.shape[0] < input_data_batch_size: + size = (input_data_batch_size - value.shape[0], *value.shape[1:]) + if torch.is_floating_point(value): + extension = torch.rand(size=size, dtype=value.dtype, device=torch_device) + else: + extension = torch.randint(high=5, size=size, dtype=value.dtype, device=torch_device) + value = torch.cat((value, extension), dim=0).to(torch_device) + + processed_inputs[key] = value[:input_data_batch_size] + + if not use_attention_mask: + dummy_attention_mask = None + else: + dummy_attention_mask = inputs_dict.get("attention_mask", None) + if dummy_attention_mask is None: + if is_encoder_decoder: + seqlen = inputs_dict.get("decoder_input_ids", processed_inputs[model.main_input_name]).shape[ + -1 + ] + else: + seqlen = processed_inputs[model.main_input_name].shape[-1] + dummy_attention_mask = torch.ones(batch_size, seqlen).to(torch.int64).to(torch_device) + + # extend dummy_attention_mask to have at least `batch_size` elements + if dummy_attention_mask.shape[0] < batch_size: + size = (batch_size - dummy_attention_mask.shape[0], *dummy_attention_mask.shape[1:]) + extension = torch.ones(size=size, dtype=dummy_attention_mask.dtype, device=torch_device) + dummy_attention_mask = torch.cat((dummy_attention_mask, extension), dim=0) + + dummy_attention_mask = dummy_attention_mask[:batch_size].to(torch_device) + + dummy_attention_mask[:] = 1 + if padding_side == "left": + dummy_attention_mask[-1, :2] = 0 + dummy_attention_mask[-1, 2:] = 1 + elif padding_side == "right": + dummy_attention_mask[-1, -2:] = 0 + dummy_attention_mask[-1, :-2] = 1 + + if is_encoder_decoder: + # musicgen encoder-decoder models; TODO: find better abstraction + if model.__class__.__name__.startswith("Musicgen") and hasattr(self.model_tester, "num_codebooks"): + input_data_batch_size = batch_size * self.model_tester.num_codebooks + else: + input_data_batch_size = batch_size + + decoder_input_ids = inputs_dict.get("decoder_input_ids", processed_inputs[model.main_input_name]) + decoder_input_ids = decoder_input_ids[:input_data_batch_size] + if decoder_input_ids.shape[0] != input_data_batch_size: + extension = torch.ones( + input_data_batch_size - decoder_input_ids.shape[0], + *decoder_input_ids.shape[1:], + dtype=decoder_input_ids.dtype, + device=torch_device, + ) + decoder_input_ids = torch.cat((decoder_input_ids, extension), dim=0) + decoder_input_ids = decoder_input_ids.to(torch_device) + + # TODO: never an `attention_mask` arg here? + processed_inputs.update( + { + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": dummy_attention_mask, + "output_hidden_states": True, + } + ) + else: + processed_inputs.update( + { + "output_hidden_states": True, + } + ) + + # Otherwise fails for e.g. WhisperEncoderModel + if "attention_mask" in inspect.signature(model_eager.forward).parameters: + processed_inputs["attention_mask"] = dummy_attention_mask + + if self.has_attentions and "output_attentions" in inspect.signature(model_sdpa.forward).parameters: + processed_inputs["output_attentions"] = output_attentions + if "bool_masked_pos" in inspect.signature(model_eager.forward).parameters: + dummy_mask = torch.ones((self.model_tester.num_masks,)) + + # In case of additional token (like class) we define a custom `mask_length` + if hasattr(self.model_tester, "mask_length"): + mask_length = self.model_tester.mask_length - dummy_mask.size(0) + else: + mask_length = self.model_tester.seq_length - dummy_mask.size(0) + dummy_mask = torch.cat([dummy_mask, torch.zeros(mask_length)]) + dummy_bool_masked_pos = dummy_mask.expand(batch_size, -1).bool() + processed_inputs["bool_masked_pos"] = dummy_bool_masked_pos.to(torch_device) + + if "noise" in inspect.signature(model_eager.forward).parameters: + np.random.seed(2) + num_patches = int((self.model_tester.image_size // self.model_tester.patch_size) ** 2) + noise = np.random.uniform(size=(batch_size, num_patches)) + processed_inputs["noise"] = torch.from_numpy(noise) + + # TODO: test gradients as well (& for FA2 as well!) + with torch.no_grad(): + with sdpa_kernel( + enable_flash=enable_kernels, + enable_math=True, + enable_mem_efficient=enable_kernels, + ): + prepared_inputs = self._prepare_for_class(processed_inputs, model_class) + prepared_inputs = { + k: v.to(torch_device) if isinstance(v, torch.Tensor) else v for k, v in prepared_inputs.items() + } + outputs_eager = model_eager(**prepared_inputs) + outputs_sdpa = model_sdpa(**prepared_inputs) + + if "logits_per_text" in outputs_eager: + key = "logits_per_text" + elif "vision_hidden_states" in outputs_eager: + key = "vision_hidden_states" + elif "audio_values" in outputs_eager: + key = "audio_values" + elif "decoder_hidden_states" in outputs_eager: + key = "decoder_hidden_states" + elif "logits" in outputs_eager and "Classification" in model_class.__name__: + key = "logits" + elif "language_model_outputs" in outputs_eager and "blip" in model_class.__name__.lower(): + outputs_eager = outputs_eager["language_model_outputs"] + outputs_sdpa = outputs_sdpa["language_model_outputs"] + key = "hidden_states" if "hidden_states" in outputs_eager else "decoder_hidden_states" + else: + key = "hidden_states" + + # TODO: rename logits -> hidden_states + logits_eager = outputs_eager[key] + logits_sdpa = outputs_sdpa[key] + + if key in ["vision_hidden_states", "decoder_hidden_states", "hidden_states"]: + logits_eager = logits_eager[-1] + logits_sdpa = logits_sdpa[-1] + + if key == "logits_per_text": + nan_mask = torch.isnan(logits_eager) + logits_eager[nan_mask] = 0 + logits_sdpa[nan_mask] = 0 + + if torch_device in ["cpu", "cuda"]: + atol = atols[torch_device, enable_kernels, torch_dtype] + rtol = rtols[torch_device, enable_kernels, torch_dtype] + elif torch_device == "hpu": + atol = atols["cuda", enable_kernels, torch_dtype] + rtol = rtols["cuda", enable_kernels, torch_dtype] + elif torch_device == "xpu": + # As of PyTorch 2.5 XPU backend supports only torch.nn.attention.SDPBackend.MATH + # which is implemented on PyTorch level using aten operators and is + # device agnostic with respect to implementation of each aten operator. + atol = atols["cuda", False, torch_dtype] + rtol = rtols["cuda", False, torch_dtype] + else: + atol = 1e-7 + rtol = 1e-4 + + # Masked tokens output slightly deviates - we don't mind that. + if use_attention_mask: + _logits_sdpa = torch.zeros_like(input=logits_sdpa) + _logits_eager = torch.zeros_like(input=logits_eager) + + _logits_sdpa[:-1] = logits_sdpa[:-1] + _logits_eager[:-1] = logits_eager[:-1] + + if padding_side == "left": + _logits_sdpa[-1:, 2:] = logits_sdpa[-1:, 2:] + _logits_eager[-1:, 2:] = logits_eager[-1:, 2:] + + elif padding_side == "right": + _logits_sdpa[-1:, 2:] = logits_sdpa[-1:, :-2] + _logits_eager[-1:, 2:] = logits_eager[-1:, :-2] + + logits_sdpa = _logits_sdpa + logits_eager = _logits_eager + + results = [ + torch.allclose(_logits_sdpa, _logits_eager, atol=atol, rtol=rtol) + for (_logits_sdpa, _logits_eager) in zip(logits_sdpa, logits_eager) + ] + # If 80% batch elements have matched results, it's fine + if np.mean(results) < 0.8: + mean_relative_diff = ((logits_sdpa - logits_eager).abs() / (logits_eager.abs() + 1e-12)).mean() + raise ValueError( + f"mean relative difference for {key}: {mean_relative_diff:.3e}, torch atol = {atol}, torch rtol = " + f"{rtol}" + ) + + +def _config_zero_init(config): + configs_no_init = copy.deepcopy(config) + for key in configs_no_init.__dict__: + if "_range" in key or "_std" in key or "initializer_factor" in key or "layer_scale" in key: + setattr(configs_no_init, key, 1e-10) + if isinstance(getattr(configs_no_init, key, None), PretrainedConfig): + no_init_subconfig = _config_zero_init(getattr(configs_no_init, key)) + setattr(configs_no_init, key, no_init_subconfig) + return configs_no_init + + +def _mock_init_weights(self, module): + for name, param in module.named_parameters(recurse=False): + # Use the first letter of the name to get a value and go from a <> -13 to z <> 12 + value = ord(name[0].lower()) - 110 + param.data.fill_(value) + + +def _mock_all_init_weights(self): + # Prune heads if needed + if self.config.pruned_heads: + self.prune_heads(self.config.pruned_heads) + + import transformers.modeling_utils + + if transformers.modeling_utils._init_weights: + for module in self.modules(): + module._is_hf_initialized = False + # Initialize weights + self.apply(self._initialize_weights) + + # Tie weights should be skipped when not initializing all weights + # since from_pretrained(...) calls tie weights anyways + self.tie_weights() + + +@contextmanager +def _deepspeed_zero3(ds_config): + dschf = HfDeepSpeedConfig(ds_config) + try: + yield dschf + finally: + unset_hf_deepspeed_config() + + +def sdpa_kernel(enable_flash, enable_math, enable_mem_efficient): + if version.parse(torch.__version__).release < version.parse("2.3").release: + return torch.backends.cuda.sdp_kernel( + enable_flash=enable_flash, enable_math=enable_math, enable_mem_efficient=enable_mem_efficient + ) + + backends = [] + if enable_flash: + backends += [torch.nn.attention.SDPBackend.FLASH_ATTENTION] + if enable_math: + backends += [torch.nn.attention.SDPBackend.MATH] + if enable_mem_efficient: + backends += [torch.nn.attention.SDPBackend.EFFICIENT_ATTENTION] + return torch.nn.attention.sdpa_kernel(backends) + + +@require_torch +class ModelTesterMixin: + model_tester = None + all_model_classes = () + fx_compatible = False + test_torchscript = True + test_pruning = True + test_resize_embeddings = True + test_resize_position_embeddings = False + test_head_masking = True + test_mismatched_shapes = True + test_missing_keys = True + test_model_parallel = False + test_torch_exportable = False + # Used in `check_training_gradient_checkpointing` to NOT check all params having gradient (e.g. for some MOE models) + test_all_params_have_gradient = True + is_encoder_decoder = False + has_attentions = True + _is_composite = False + model_split_percents = [0.5, 0.7, 0.9] + + # Note: for all mixins that utilize the Hub in some way, we should ensure that + # they contain the `hub_retry` decorator in case of failures. + def __init_subclass__(cls, **kwargs): + super().__init_subclass__(**kwargs) + for attr_name in dir(cls): + if attr_name.startswith("test_"): + attr = getattr(cls, attr_name) + if callable(attr): + setattr(cls, attr_name, hub_retry()(attr)) + + @property + def all_generative_model_classes(self): + return tuple(model_class for model_class in self.all_model_classes if model_class.can_generate()) + + def _prepare_for_class(self, inputs_dict, model_class, return_labels=False): + inputs_dict = copy.deepcopy(inputs_dict) + if model_class.__name__ in get_values(MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES): + inputs_dict = { + k: v.unsqueeze(1).expand(-1, self.model_tester.num_choices, -1).contiguous() + if isinstance(v, torch.Tensor) and v.ndim > 1 + else v + for k, v in inputs_dict.items() + } + elif model_class.__name__ in get_values(MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES): + inputs_dict.pop("attention_mask") + elif model_class.__name__ == MODEL_FOR_PRETRAINING_MAPPING_NAMES["hiera"]: + config = self.model_tester.get_config() + mask_spatial_shape = [ + i // s // ms for i, s, ms in zip(config.image_size, config.patch_stride, config.masked_unit_size) + ] + num_windows = math.prod(mask_spatial_shape) + torch.manual_seed(0) + inputs_dict["noise"] = torch.rand(self.model_tester.batch_size, num_windows) + + if return_labels: + if model_class.__name__ in get_values(MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES): + inputs_dict["labels"] = torch.ones(self.model_tester.batch_size, dtype=torch.long, device=torch_device) + elif model_class.__name__ in [ + *get_values(MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES), + *get_values(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES), + ]: + inputs_dict["start_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + inputs_dict["end_positions"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + elif model_class.__name__ in [ + *get_values(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES), + *get_values(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES), + ]: + inputs_dict["labels"] = torch.zeros( + self.model_tester.batch_size, dtype=torch.long, device=torch_device + ) + elif model_class.__name__ in [ + *get_values(MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_CAUSAL_LM_MAPPING_NAMES), + *get_values(MODEL_FOR_CAUSAL_IMAGE_MODELING_MAPPING_NAMES), + *get_values(MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES), + *get_values(MODEL_FOR_MASKED_LM_MAPPING_NAMES), + *get_values(MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES), + *get_values(MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES), + ]: + inputs_dict["labels"] = torch.zeros( + (self.model_tester.batch_size, self.model_tester.seq_length), dtype=torch.long, device=torch_device + ) + elif model_class.__name__ in get_values(MODEL_FOR_MASKED_IMAGE_MODELING_MAPPING_NAMES): + num_patches = self.model_tester.image_size // self.model_tester.patch_size + inputs_dict["bool_masked_pos"] = torch.zeros( + (self.model_tester.batch_size, num_patches**2), dtype=torch.long, device=torch_device + ) + elif model_class.__name__ in get_values(MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING_NAMES): + batch_size, num_channels, height, width = inputs_dict["pixel_values"].shape + inputs_dict["labels"] = torch.zeros( + [self.model_tester.batch_size, height, width], device=torch_device + ).long() + + return inputs_dict + + def test_save_load(self): + def check_save_load(out1, out2): + # make sure we don't have nans + out_2 = out2.cpu().numpy() + out_2[np.isnan(out_2)] = 0 + out_2 = out_2[~np.isneginf(out_2)] + + out_1 = out1.cpu().numpy() + out_1[np.isnan(out_1)] = 0 + out_1 = out_1[~np.isneginf(out_1)] + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + first = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + # the config file (and the generation config file, if it can generate) should be saved + self.assertTrue(os.path.exists(os.path.join(tmpdirname, CONFIG_NAME))) + self.assertEqual( + model.can_generate(), os.path.exists(os.path.join(tmpdirname, GENERATION_CONFIG_NAME)) + ) + + model = model_class.from_pretrained(tmpdirname) + model.to(torch_device) + with torch.no_grad(): + second = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + # Save and load second time because `from_pretrained` adds a bunch of new config fields + # so we need to make sure those fields can be loaded back after saving + # Simply init as `model(config)` doesn't add those fields + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained(tmpdirname) + + if isinstance(first, tuple) and isinstance(second, tuple): + for tensor1, tensor2 in zip(first, second): + check_save_load(tensor1, tensor2) + else: + check_save_load(first, second) + + def test_from_pretrained_no_checkpoint(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + model = model_class(copy.deepcopy(config)) + state_dict = model.state_dict() + + new_model = model_class.from_pretrained( + pretrained_model_name_or_path=None, config=config, state_dict=state_dict + ) + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + def test_keep_in_fp32_modules(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + if model_class._keep_in_fp32_modules is None: + self.skipTest(reason="Model class has no _keep_in_fp32_modules attribute defined") + + model = model_class(copy.deepcopy(config)) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16) + + for name, param in model.named_parameters(): + if any(n in model_class._keep_in_fp32_modules for n in name.split(".")): + self.assertTrue(param.dtype == torch.float32) + else: + self.assertTrue(param.dtype == torch.float16, name) + + def test_save_load_keys_to_ignore_on_save(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(copy.deepcopy(config)) + _keys_to_ignore_on_save = getattr(model, "_keys_to_ignore_on_save", None) + if _keys_to_ignore_on_save is None: + continue + + # check the keys are in the original state_dict + for k in _keys_to_ignore_on_save: + self.assertIn(k, model.state_dict().keys(), "\n".join(model.state_dict().keys())) + + # check that certain keys didn't get saved with the model + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + output_model_file = os.path.join(tmpdirname, SAFE_WEIGHTS_NAME) + state_dict_saved = safe_load_file(output_model_file) + + for k in _keys_to_ignore_on_save: + self.assertNotIn(k, state_dict_saved.keys(), "\n".join(state_dict_saved.keys())) + + # Test we can load the state dict in the model, necessary for the checkpointing API in Trainer. + load_result = model.load_state_dict(state_dict_saved, strict=False) + keys_to_ignore = set(model._keys_to_ignore_on_save) + + if hasattr(model, "_tied_weights_keys"): + keys_to_ignore.update(set(model._tied_weights_keys)) + + self.assertTrue(len(load_result.missing_keys) == 0 or set(load_result.missing_keys) == keys_to_ignore) + self.assertTrue(len(load_result.unexpected_keys) == 0) + + def test_gradient_checkpointing_backward_compatibility(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if not model_class.supports_gradient_checkpointing: + continue + + config.gradient_checkpointing = True + model = model_class(copy.deepcopy(config)) + self.assertTrue(model.is_gradient_checkpointing) + + def test_gradient_checkpointing_enable_disable(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if not model_class.supports_gradient_checkpointing: + continue + + # at init model should have gradient checkpointing disabled + model = model_class(copy.deepcopy(config)) + self.assertFalse(model.is_gradient_checkpointing) + + # check enable works + model.gradient_checkpointing_enable() + self.assertTrue(model.is_gradient_checkpointing) + + # Loop over all modules and check that relevant modules have gradient_checkpointing set to True + for n, m in model.named_modules(): + if hasattr(m, "gradient_checkpointing"): + self.assertTrue( + m.gradient_checkpointing, f"Module {n} does not have gradient_checkpointing set to True" + ) + + # check disable works + model.gradient_checkpointing_disable() + self.assertFalse(model.is_gradient_checkpointing) + + # Loop over all modules and check that relevant modules have gradient_checkpointing set to False + for n, m in model.named_modules(): + if hasattr(m, "gradient_checkpointing"): + self.assertFalse( + m.gradient_checkpointing, f"Module {n} does not have gradient_checkpointing set to False" + ) + + def test_peft_gradient_checkpointing_enable_disable(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if not model_class.supports_gradient_checkpointing: + continue + + # at init model should have gradient checkpointing disabled + model = model_class(copy.deepcopy(config)) + self.assertFalse(model.is_gradient_checkpointing) + + # check enable works + model._hf_peft_config_loaded = True + try: + model.gradient_checkpointing_enable() + except NotImplementedError: + continue + + self.assertTrue(model.is_gradient_checkpointing) + + # Loop over all modules and check that relevant modules have gradient_checkpointing set to True + for n, m in model.named_modules(): + if hasattr(m, "gradient_checkpointing"): + self.assertTrue( + m.gradient_checkpointing, f"Module {n} does not have gradient_checkpointing set to True" + ) + + # check disable works + model.gradient_checkpointing_disable() + self.assertFalse(model.is_gradient_checkpointing) + + # Loop over all modules and check that relevant modules have gradient_checkpointing set to False + for n, m in model.named_modules(): + if hasattr(m, "gradient_checkpointing"): + self.assertFalse( + m.gradient_checkpointing, f"Module {n} does not have gradient_checkpointing set to False" + ) + + def test_can_init_all_missing_weights(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + # This is used to get the addition year of the model + filename = inspect.getfile(config.__class__) + # No easy way to get model addition date -> check copyright year on top of file + with open(filename) as file: + source_code = file.read() + addition_year = 0 # if we cannot find it, set it to 0 (i.e. oldest) + if match_object := re.search(r"^# Copyright (\d{4})", source_code, re.MULTILINE | re.IGNORECASE): + addition_year = int(match_object.group(1)) + + for model_class in self.all_model_classes: + # For now, skip everything older than 2024 and "important models" (too much models to patch otherwise) + # TODO: relax this as we patch more and more models + if addition_year < 2023: + self.skipTest(reason=f"{model_class} is not a priorited model for now.") + + # Monkey patch the method to add a seed (we do it on PreTrainedModel._initialize_weights, which wraps + # `_init_weights` so that it can add the seed for composite models as well) + original_initialize_weights = PreTrainedModel._initialize_weights + + def seeded_initialize_weights(self, module): + set_seed(0) + original_initialize_weights(self, module) + + PreTrainedModel._initialize_weights = seeded_initialize_weights + + # First, initialize the model from config -> this ensure everything is correctly initialized, even if + # _init_weights() does not take all weights into account correctly + model_from_config = model_class(copy.deepcopy(config)) + # Here, passing an empty state dict will force all weights to be moved from meta to cpu, then be initialized + # by _init_weights() + model_from_pretrained = model_class.from_pretrained(None, config=config, state_dict={}) + + # Back to original method to avoid issues if running several other tests + PreTrainedModel._initialize_weights = original_initialize_weights + + # First, check if any parameters are still on meta -> this is usually an issue with tied weights + params_on_meta = [] + for k, v in model_from_pretrained.named_parameters(): + if v.device.type == "meta": + params_on_meta.append(k) + + self.assertTrue( + len(params_on_meta) == 0, + f"The following keys are still on the meta device, it probably comes from an issue in the tied weights:\n{params_on_meta}", + ) + + # Everything must be exactly the same as we set the same seed for each init + different_weights = [] + for (k1, v1), (k2, v2) in zip( + model_from_config.state_dict().items(), model_from_pretrained.state_dict().items() + ): + self.assertEqual(k1, k2, "The keys from each model should be the same") + + # In case using torch.nn.utils.parametrizations on a module, we should skip the resulting keys + if re.search(r"\.parametrizations\..*?\.original[01]", k1): + continue + + # Since we added the seed, they should be exactly the same (i.e. using allclose maybe be wrong due + # to very low std in init function) + if not (v1 == v2).all(): + different_weights.append(k1) + + # Buffers that are initialized randomly are ignored as they are not initialized on meta device anyway + buffer_names = {name for name, _ in model_from_config.named_buffers()} + different_weights = [k for k in different_weights if k not in buffer_names] + + self.assertTrue( + len(different_weights) == 0, + f"The following keys are not properly handled by `_init_weights()`:\n{different_weights}", + ) + + def test_torch_save_load(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if config.__class__ not in MODEL_MAPPING: + self.skipTest(reason=f"{config.__class__.__name__} not in MODEL_MAPPING") + + base_class = MODEL_MAPPING[config.__class__] + + if isinstance(base_class, tuple): + base_class = base_class[0] + + for model_class in self.all_model_classes: + if model_class == base_class: + continue + + # make a copy of model class to not break future tests + # from https://stackoverflow.com/questions/9541025/how-to-copy-a-python-class + class CopyClass(base_class): + pass + + base_class_copy = CopyClass + + # make sure that all keys are expected for test + base_class_copy._keys_to_ignore_on_load_missing = [] + + # make init deterministic, but make sure that + # non-initialized weights throw errors nevertheless + base_class_copy._init_weights = _mock_init_weights + base_class_copy.init_weights = _mock_all_init_weights + + model = model_class(copy.deepcopy(config)) + state_dict = model.state_dict() + + def check_equal(loaded): + for key in state_dict: + max_diff = torch.max( + state_dict()[key] ^ loaded[key] + if isinstance(state_dict[key], torch.BoolTensor) + else torch.abs(state_dict[key] - loaded[key]) + ).item() + self.assertLessEqual(max_diff, 1e-6, msg=f"{key} not identical") + + # check that certain keys didn't get saved with the model + with tempfile.TemporaryDirectory() as tmpdirname: + pt_checkpoint_path = os.path.join(tmpdirname, "pytorch_model.bin") + torch.save(state_dict, pt_checkpoint_path, _use_new_zipfile_serialization=True) + check_equal(load_state_dict(pt_checkpoint_path)) + torch.save(state_dict, pt_checkpoint_path, _use_new_zipfile_serialization=False) + check_equal(load_state_dict(pt_checkpoint_path)) + + def test_initialization(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + for model_class in self.all_model_classes: + model = model_class(config=copy.deepcopy(configs_no_init)) + for name, param in model.named_parameters(): + if param.requires_grad: + data = torch.flatten(param.data) + n_elements = torch.numel(data) + # skip 2.5% of elements on each side to avoid issues caused by `nn.init.trunc_normal_` described in + # https://github.com/huggingface/transformers/pull/27906#issuecomment-1846951332 + n_elements_to_skip_on_each_side = int(n_elements * 0.025) + data_to_check = torch.sort(data).values + if n_elements_to_skip_on_each_side > 0: + data_to_check = data_to_check[n_elements_to_skip_on_each_side:-n_elements_to_skip_on_each_side] + self.assertIn( + ((data_to_check.mean() * 1e9).round() / 1e9).item(), + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def test_determinism(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_determinism(first, second): + out_1 = first.cpu().numpy() + out_2 = second.cpu().numpy() + out_1 = out_1[~np.isnan(out_1)] + out_2 = out_2[~np.isnan(out_2)] + out_1 = out_1[~np.isneginf(out_1)] + out_2 = out_2[~np.isneginf(out_2)] + max_diff = np.amax(np.abs(out_1 - out_2)) + self.assertLessEqual(max_diff, 1e-5) + + for model_class in self.all_model_classes: + model = model_class(copy.deepcopy(config)) + model.to(torch_device) + model.eval() + with torch.no_grad(): + first = model(**self._prepare_for_class(inputs_dict, model_class))[0] + second = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + if isinstance(first, tuple) and isinstance(second, tuple): + for tensor1, tensor2 in zip(first, second): + check_determinism(tensor1, tensor2) + else: + check_determinism(first, second) + + def test_batching_equivalence(self, atol=1e-5, rtol=1e-5): + """ + Tests that the model supports batching and that the output is the nearly the same for the same input in + different batch sizes. + (Why "nearly the same" not "exactly the same"? Batching uses different matmul shapes, which often leads to + different results: https://github.com/huggingface/transformers/issues/25420#issuecomment-1775317535) + """ + + def recursive_check(batched_object, single_row_object, model_name, key): + if isinstance(batched_object, (list, tuple)): + for batched_object_value, single_row_object_value in zip(batched_object, single_row_object): + recursive_check(batched_object_value, single_row_object_value, model_name, key) + elif isinstance(batched_object, dict): + for batched_object_value, single_row_object_value in zip( + batched_object.values(), single_row_object.values() + ): + recursive_check(batched_object_value, single_row_object_value, model_name, key) + # do not compare returned loss (0-dim tensor) / codebook ids (int) / caching objects + elif batched_object is None or not isinstance(batched_object, torch.Tensor): + return + elif batched_object.dim() == 0: + return + # do not compare int or bool outputs as they are mostly computed with max/argmax/topk methods which are + # very sensitive to the inputs (e.g. tiny differences may give totally different results) + elif not torch.is_floating_point(batched_object): + return + else: + # indexing the first element does not always work + # e.g. models that output similarity scores of size (N, M) would need to index [0, 0] + slice_ids = [slice(0, index) for index in single_row_object.shape] + batched_row = batched_object[slice_ids] + self.assertFalse( + torch.isnan(batched_row).any(), f"Batched output has `nan` in {model_name} for key={key}" + ) + self.assertFalse( + torch.isinf(batched_row).any(), f"Batched output has `inf` in {model_name} for key={key}" + ) + self.assertFalse( + torch.isnan(single_row_object).any(), f"Single row output has `nan` in {model_name} for key={key}" + ) + self.assertFalse( + torch.isinf(single_row_object).any(), f"Single row output has `inf` in {model_name} for key={key}" + ) + try: + torch.testing.assert_close(batched_row, single_row_object, atol=atol, rtol=rtol) + except AssertionError as e: + msg = f"Batched and Single row outputs are not equal in {model_name} for key={key}.\n\n" + msg += str(e) + raise AssertionError(msg) + + set_model_tester_for_less_flaky_test(self) + + config, batched_input = self.model_tester.prepare_config_and_inputs_for_common() + set_config_for_less_flaky_test(config) + + for model_class in self.all_model_classes: + config.output_hidden_states = True + + model_name = model_class.__name__ + if hasattr(self.model_tester, "prepare_config_and_inputs_for_model_class"): + config, batched_input = self.model_tester.prepare_config_and_inputs_for_model_class(model_class) + batched_input_prepared = self._prepare_for_class(batched_input, model_class) + model = model_class(copy.deepcopy(config)).to(torch_device).eval() + set_model_for_less_flaky_test(model) + + batch_size = self.model_tester.batch_size + single_row_input = {} + for key, value in batched_input_prepared.items(): + if isinstance(value, torch.Tensor) and value.shape[0] % batch_size == 0: + # e.g. musicgen has inputs of size (bs*codebooks). in most cases value.shape[0] == batch_size + single_batch_shape = value.shape[0] // batch_size + single_row_input[key] = value[:single_batch_shape] + else: + single_row_input[key] = value + + with torch.no_grad(): + model_batched_output = model(**batched_input_prepared) + model_row_output = model(**single_row_input) + + if isinstance(model_batched_output, torch.Tensor): + model_batched_output = {"model_output": model_batched_output} + model_row_output = {"model_output": model_row_output} + + for key in model_batched_output: + # DETR starts from zero-init queries to decoder, leading to cos_similarity = `nan` + if hasattr(self, "zero_init_hidden_state") and "decoder_hidden_states" in key: + model_batched_output[key] = model_batched_output[key][1:] + model_row_output[key] = model_row_output[key][1:] + recursive_check(model_batched_output[key], model_row_output[key], model_name, key) + + def check_training_gradient_checkpointing(self, gradient_checkpointing_kwargs=None): + if not self.model_tester.is_training: + self.skipTest(reason="ModelTester is not configured to run training tests") + + for model_class in self.all_model_classes: + with self.subTest(model_class.__name__): + if ( + model_class.__name__ + in [ + *get_values(MODEL_MAPPING_NAMES), + *get_values(MODEL_FOR_BACKBONE_MAPPING_NAMES), + ] + or not model_class.supports_gradient_checkpointing + ): + # TODO (ydshieh): use `skipTest` once pytest-dev/pytest-subtests/pull/169 is merged + # self.skipTest(reason=f"`supports_gradient_checkpointing` is False for {model_class.__name__}.") + continue + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.use_cache = False + config.return_dict = True + model = model_class(config) + + model.to(torch_device) + model.gradient_checkpointing_enable(gradient_checkpointing_kwargs=gradient_checkpointing_kwargs) + model.train() + + # unfreeze additional layers + for p in model.parameters(): + p.requires_grad_(True) + + optimizer = torch.optim.SGD(model.parameters(), lr=0.01) + + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + loss = model(**inputs).loss + loss.backward() + optimizer.step() + + if self.test_all_params_have_gradient: + for k, v in model.named_parameters(): + if v.requires_grad: + self.assertTrue(v.grad is not None, f"{k} in {model_class.__name__} has no gradient!") + + def test_training(self): + if not self.model_tester.is_training: + self.skipTest(reason="ModelTester is not configured to run training tests") + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + + if model_class.__name__ in [ + *get_values(MODEL_MAPPING_NAMES), + *get_values(MODEL_FOR_BACKBONE_MAPPING_NAMES), + ]: + continue + + model = model_class(config) + model.to(torch_device) + model.train() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + loss = model(**inputs).loss + loss.backward() + + def test_causal_lm_can_accept_kwargs(self): + if not getattr(self.model_tester, "is_training", False): + self.skipTest(reason="ModelTester is not configured to run training tests") + + valid_model_class = False + incompatible_models = ( + "MusicgenForCausalLM", + "MusicgenMelodyForCausalLM", + "MllamaForCausalLM", + "CpmAntForCausalLM", + "GotOcr2ForConditionalGeneration", + ) + for model_class in self.all_model_classes: + if ( + model_class.__name__ in get_values(MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) + and model_class.__name__ not in incompatible_models + ): + valid_model_class = True + if not valid_model_class: + self.skipTest(reason="No causal lm model classes found") + for model_class in self.all_model_classes: + model_name = model_class.__name__ + if model_name in get_values(MODEL_FOR_CAUSAL_LM_MAPPING_NAMES) and model_name not in incompatible_models: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + with tempfile.TemporaryDirectory() as tmpdir: + with torch.device(torch_device): + model_eager = AutoModelForCausalLM.from_config(config, torch_dtype=torch.float32) + + model_eager.save_pretrained(tmpdir) + model = AutoModelForCausalLM.from_pretrained( + tmpdir, torch_dtype=torch.float32, device_map=torch_device + ) + inputs_dict["num_items_in_batch"] = torch.tensor(inputs_dict["input_ids"].shape[0]) + inputs_dict["labels"] = inputs_dict["input_ids"] + _ = model(**inputs_dict, return_dict=False) + + def test_training_gradient_checkpointing(self): + # Scenario - 1 default behaviour + self.check_training_gradient_checkpointing() + + def test_training_gradient_checkpointing_use_reentrant(self): + # Scenario - 2 with `use_reentrant=True` - this is the default value that is used in pytorch's + # torch.utils.checkpoint.checkpoint + self.check_training_gradient_checkpointing(gradient_checkpointing_kwargs={"use_reentrant": True}) + + def test_training_gradient_checkpointing_use_reentrant_false(self): + # Scenario - 3 with `use_reentrant=False` pytorch suggests users to use this value for + # future releases: https://pytorch.org/docs/stable/checkpoint.html + self.check_training_gradient_checkpointing(gradient_checkpointing_kwargs={"use_reentrant": False}) + + def test_attention_outputs(self): + if not self.has_attentions: + self.skipTest(reason="Model does not output attentions") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.return_dict = True + # force eager attention to support output attentions + config._attn_implementation = "eager" + + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + encoder_seq_length = getattr(self.model_tester, "encoder_seq_length", seq_len) + decoder_key_length = getattr(self.model_tester, "decoder_key_length", decoder_seq_length) + encoder_key_length = getattr(self.model_tester, "key_length", encoder_seq_length) + chunk_length = getattr(self.model_tester, "chunk_length", None) + if chunk_length is not None and hasattr(self.model_tester, "num_hashes"): + encoder_seq_length = encoder_seq_length * self.model_tester.num_hashes + + for model_class in self.all_model_classes: + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = False + config.return_dict = True + model = model_class._from_config(config, attn_implementation="eager") + config = model.config + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + # check that output_attentions also work using config + del inputs_dict["output_attentions"] + config.output_attentions = True + for k in config.sub_configs: + getattr(config, k).output_attentions = True + + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + self.assertEqual(len(attentions), self.model_tester.num_hidden_layers) + + if chunk_length is not None: + self.assertListEqual( + list(attentions[0].shape[-4:]), + [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length], + ) + else: + self.assertListEqual( + list(attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + out_len = len(outputs) + + if self.is_encoder_decoder: + correct_outlen = 5 + + # loss is at first position + if "labels" in inputs_dict: + correct_outlen += 1 # loss is added to beginning + # Question Answering model returns start_logits and end_logits + if model_class.__name__ in [ + *get_values(MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES), + *get_values(MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES), + ]: + correct_outlen += 1 # start_logits and end_logits instead of only 1 output + if "past_key_values" in outputs: + correct_outlen += 1 # past_key_values have been returned + + self.assertEqual(out_len, correct_outlen) + + # decoder attentions + decoder_attentions = outputs.decoder_attentions + self.assertIsInstance(decoder_attentions, (list, tuple)) + self.assertEqual(len(decoder_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(decoder_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, decoder_seq_length, decoder_key_length], + ) + + # cross attentions + cross_attentions = outputs.cross_attentions + self.assertIsInstance(cross_attentions, (list, tuple)) + self.assertEqual(len(cross_attentions), self.model_tester.num_hidden_layers) + self.assertListEqual( + list(cross_attentions[0].shape[-3:]), + [ + self.model_tester.num_attention_heads, + decoder_seq_length, + encoder_key_length, + ], + ) + + # Check attention is always last and order is fine + inputs_dict["output_attentions"] = True + inputs_dict["output_hidden_states"] = True + model = model_class(config) + model.to(torch_device) + model.eval() + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + if hasattr(self.model_tester, "num_hidden_states_types"): + added_hidden_states = self.model_tester.num_hidden_states_types + elif self.is_encoder_decoder: + added_hidden_states = 2 + else: + added_hidden_states = 1 + self.assertEqual(out_len + added_hidden_states, len(outputs)) + + self_attentions = outputs.encoder_attentions if config.is_encoder_decoder else outputs.attentions + + self.assertEqual(len(self_attentions), self.model_tester.num_hidden_layers) + if chunk_length is not None: + self.assertListEqual( + list(self_attentions[0].shape[-4:]), + [self.model_tester.num_attention_heads, encoder_seq_length, chunk_length, encoder_key_length], + ) + else: + self.assertListEqual( + list(self_attentions[0].shape[-3:]), + [self.model_tester.num_attention_heads, encoder_seq_length, encoder_key_length], + ) + + @unittest.skip("many failing tests after #39120. Will fix when the community ask for it.") + @slow + def test_torchscript_simple(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + self._create_and_check_torchscript(config, inputs_dict) + + @unittest.skip("many failing tests after #39120. Will fix when the community ask for it.") + @slow + def test_torchscript_output_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_attentions = True + self._create_and_check_torchscript(config, inputs_dict) + + @unittest.skip("many failing tests after #39120. Will fix when the community ask for it.") + @slow + def test_torchscript_output_hidden_state(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config.output_hidden_states = True + self._create_and_check_torchscript(config, inputs_dict) + + # This is copied from `torch/testing/_internal/jit_utils.py::clear_class_registry` + def clear_torch_jit_class_registry(self): + torch._C._jit_clear_class_registry() + torch.jit._recursive.concrete_type_store = torch.jit._recursive.ConcreteTypeStore() + # torch 1.8 has no `_clear_class_state` in `torch.jit._state` + if hasattr(torch.jit._state, "_clear_class_state"): + torch.jit._state._clear_class_state() + + def _create_and_check_torchscript(self, config, inputs_dict): + if not self.test_torchscript: + self.skipTest(reason="test_torchscript is set to `False`") + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.torchscript = True + for model_class in self.all_model_classes: + for attn_implementation in ["eager", "sdpa"]: + if ( + attn_implementation == "sdpa" + and (not model_class._supports_sdpa or not is_torch_sdpa_available()) + or config.output_attentions + ): + continue + + configs_no_init._attn_implementation = attn_implementation + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class) + + main_input_name = model_class.main_input_name + + try: + if model.config.is_encoder_decoder: + model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward + main_input = inputs[main_input_name] + attention_mask = inputs["attention_mask"] + decoder_input_ids = inputs["decoder_input_ids"] + decoder_attention_mask = inputs["decoder_attention_mask"] + outputs = model(main_input, attention_mask, decoder_input_ids, decoder_attention_mask) + # `torchscript` doesn't work with outputs containing `Cache` object. However, #35235 makes + # several models to use `Cache` by default instead of the legacy cache (tuple), and + # their `torchscript` tests are failing. We won't support them anyway, but we still want to keep + # the tests for encoder models like `BERT`. So we skip the checks if the model's output contains + # a `Cache` object. + if any(isinstance(x, Cache) for x in outputs): + continue + traced_model = torch.jit.trace( + model, (main_input, attention_mask, decoder_input_ids, decoder_attention_mask) + ) + elif "bbox" in inputs and "image" in inputs: # LayoutLMv2 requires additional inputs + input_ids = inputs["input_ids"] + bbox = inputs["bbox"] + image = inputs["image"].tensor + outputs = model(input_ids, bbox, image) + if any(isinstance(x, Cache) for x in outputs): + continue + traced_model = torch.jit.trace( + model, (input_ids, bbox, image), check_trace=False + ) # when traced model is checked, an error is produced due to name mangling + elif "bbox" in inputs: # Bros requires additional inputs (bbox) + input_ids = inputs["input_ids"] + bbox = inputs["bbox"] + outputs = model(input_ids, bbox) + if any(isinstance(x, Cache) for x in outputs): + continue + traced_model = torch.jit.trace( + model, (input_ids, bbox), check_trace=False + ) # when traced model is checked, an error is produced due to name mangling + elif ( + "pixel_values" in inputs and "prompt_pixel_values" in inputs and "prompt_masks" in inputs + ): # SegGpt requires additional inputs + pixel_values = inputs["pixel_values"] + prompt_pixel_values = inputs["prompt_pixel_values"] + prompt_masks = inputs["prompt_masks"] + outputs = model(pixel_values, prompt_pixel_values, prompt_masks) + if any(isinstance(x, Cache) for x in outputs): + continue + traced_model = torch.jit.trace( + model, (pixel_values, prompt_pixel_values, prompt_masks), check_trace=False + ) # when traced model is checked, an error is produced due to name mangling + elif "Siglip2" in model_class.__name__: + outputs = model(**inputs) + example_inputs = [t for t in inputs.values() if isinstance(t, torch.Tensor)] + traced_model = torch.jit.trace(model, example_inputs, check_trace=False) + else: + main_input = inputs[main_input_name] + outputs = model(main_input) + if any(isinstance(x, Cache) for x in outputs): + continue + traced_model = torch.jit.trace(model, (main_input,)) + except RuntimeError: + self.fail("Couldn't trace module.") + + with tempfile.TemporaryDirectory() as tmp_dir_name: + pt_file_name = os.path.join(tmp_dir_name, "traced_model.pt") + + try: + torch.jit.save(traced_model, pt_file_name) + except Exception: + self.fail("Couldn't save module.") + + try: + loaded_model = torch.jit.load(pt_file_name) + except Exception: + self.fail("Couldn't load module.") + + model.to(torch_device) + model.eval() + + loaded_model.to(torch_device) + loaded_model.eval() + + model_state_dict = model.state_dict() + loaded_model_state_dict = loaded_model.state_dict() + + non_persistent_buffers = {} + for key in loaded_model_state_dict: + if key not in model_state_dict: + non_persistent_buffers[key] = loaded_model_state_dict[key] + + loaded_model_state_dict = { + key: value for key, value in loaded_model_state_dict.items() if key not in non_persistent_buffers + } + + self.assertEqual(set(model_state_dict.keys()), set(loaded_model_state_dict.keys())) + + model_buffers = list(model.buffers()) + for non_persistent_buffer in non_persistent_buffers.values(): + found_buffer = False + for i, model_buffer in enumerate(model_buffers): + if torch.equal(non_persistent_buffer, model_buffer): + found_buffer = True + break + + self.assertTrue(found_buffer) + model_buffers.pop(i) + + models_equal = True + for layer_name, p1 in model_state_dict.items(): + if layer_name in loaded_model_state_dict: + p2 = loaded_model_state_dict[layer_name] + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + # Avoid memory leak. Without this, each call increase RAM usage by ~20MB. + # (Even with this call, there are still memory leak by ~0.04MB) + self.clear_torch_jit_class_registry() + + def test_torch_fx(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + self._create_and_check_torch_fx_tracing(config, inputs_dict) + + def test_torch_fx_output_loss(self): + if self.all_model_classes[0].__name__ == "BloomModel": + self.skipTest(reason="Bloom currently has issues, @michaelbenayoun") + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + self._create_and_check_torch_fx_tracing(config, inputs_dict, output_loss=True) + + def _create_and_check_torch_fx_tracing(self, config, inputs_dict, output_loss=False): + if not self.fx_compatible: + self.skipTest(f"The model type {config.model_type} is not compatible with torch.fx") + + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init.return_dict = False + + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=output_loss) + + # We may want to test several inputs (various shapes, etc.). + inputs_to_test = [inputs] + + if model.config.is_encoder_decoder: + model.config.use_cache = False # FSTM still requires this hack -> FSTM should probably be refactored similar to BART afterward + labels = inputs.get("labels", None) + input_names = [ + "attention_mask", + "decoder_attention_mask", + "decoder_input_ids", + "input_features", + "input_ids", + "input_values", + ] + if labels is not None: + input_names.append("labels") + else: + input_names = [ + "attention_mask", + "bbox", + "input_features", + "input_ids", + "input_values", + "inputs_embeds", + "pixel_values", + "pixel_values_videos", + "token_type_ids", + "visual_feats", + "visual_pos", + "noise", + ] + + labels = inputs.get("labels", None) + start_positions = inputs.get("start_positions", None) + end_positions = inputs.get("end_positions", None) + if labels is not None: + input_names.append("labels") + if start_positions is not None: + input_names.append("start_positions") + if end_positions is not None: + input_names.append("end_positions") + + if model.config.model_type in _FX_SUPPORTED_MODELS_WITH_KV_CACHE: + input_names.append("past_key_values") + + # Generally model_tester.prepare_config_and_inputs_for_common seem not to generate past key values inputs. + if "past_key_values" not in inputs: + batch_size = inputs[next(iter(inputs))].shape[0] + num_heads = model.config.num_attention_heads + head_dim = model.config.hidden_size // model.config.num_attention_heads + + cache_shape = (batch_size, num_heads, 0, head_dim) + empty_pkv = DynamicCache() + + cache_length = 9 + cache_shape = (batch_size, num_heads, cache_length, head_dim) + non_empty_pkv = tuple( + ( + torch.rand(cache_shape, dtype=torch.float, device=torch_device), + torch.rand(cache_shape, dtype=torch.float, device=torch_device), + ) + for i in range(model.config.num_hidden_layers) + ) + non_empty_pkv = DynamicCache.from_legacy_cache(non_empty_pkv) + + inps = copy.deepcopy(inputs_to_test[0]) + + inputs_to_test[0]["past_key_values"] = empty_pkv + + inps["past_key_values"] = non_empty_pkv + inputs_to_test.append(inps) + + past_mask = torch.ones(batch_size, cache_length, device=torch_device, dtype=torch.float) + inputs_to_test[1]["attention_mask"] = torch.cat( + (past_mask, inputs_to_test[1]["attention_mask"]), dim=1 + ) + + forward_parameters = inspect.signature(model.forward).parameters + if "input_ids" in forward_parameters and "inputs_embeds" in forward_parameters: + inps = copy.deepcopy(inputs_to_test[0]) + + embedding_size = ( + model.config.embedding_size + if getattr(model.config, "embedding_size", None) is not None + and model.config.model_type != "megatron-bert" + else model.config.hidden_size + ) + + if ( + model.config.model_type in MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES + and model.__class__.__name__ + == MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES[model.config.model_type] + ): + batch_size, num_choices, sequence_length = inputs["input_ids"].shape + shape = (batch_size, num_choices, sequence_length, embedding_size) + elif inps["input_ids"].ndim == 2: + batch_size, sequence_length = inputs["input_ids"].shape + shape = (batch_size, sequence_length, embedding_size) + else: + self.skipTest("Unknown case") + + del inps["input_ids"] + inps["inputs_embeds"] = torch.rand(shape, dtype=torch.float, device=torch_device) + inputs_to_test.append(inps) + + for inps in inputs_to_test: + filtered_inputs = {k: v for (k, v) in inps.items() if k in input_names} + input_names_to_trace = list(filtered_inputs.keys()) + + if model.__class__.__name__ in set(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES.values()) and ( + not hasattr(model.config, "problem_type") or model.config.problem_type is None + ): + model.config.problem_type = "single_label_classification" + + model.config.use_cache = "past_key_values" in input_names_to_trace + + traced_model = symbolic_trace(model, input_names_to_trace) + + with torch.no_grad(): + traced_output = traced_model(**filtered_inputs) + model_output = model(**filtered_inputs) + + def flatten_output(output): + flatten = [] + for x in output: + if isinstance(x, (tuple, list)): + flatten += flatten_output(x) + elif not isinstance(x, torch.Tensor): + continue + else: + flatten.append(x) + return flatten + + model_output = flatten_output(model_output) + traced_output = flatten_output(traced_output) + num_outputs = len(model_output) + + for i in range(num_outputs): + self.assertTrue( + torch.allclose(model_output[i], traced_output[i]), + f"traced {i}th output doesn't match model {i}th output for {model_class}", + ) + + # Avoid memory leak. Without this, each call increase RAM usage by ~20MB. + # (Even with this call, there are still memory leak by ~0.04MB) + self.clear_torch_jit_class_registry() + + def test_headmasking(self): + if not self.test_head_masking: + self.skipTest(reason="Model does not support head masking") + + global_rng.seed(42) + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + global_rng.seed() + + inputs_dict["output_attentions"] = True + config.output_hidden_states = True + configs_no_init = _config_zero_init(config) # To be sure we have no Nan + configs_no_init._attn_implementation = "eager" # head mask works only in eager mode and will be removed soon + for model_class in self.all_model_classes: + model = model_class(config=configs_no_init) + model.to(torch_device) + model.eval() + + # Prepare head_mask + # Set require_grad after having prepared the tensor to avoid error (leaf variable has been moved into the graph interior) + head_mask = torch.ones( + self.model_tester.num_hidden_layers, + self.model_tester.num_attention_heads, + device=torch_device, + ) + head_mask[0, 0] = 0 + head_mask[-1, :-1] = 0 + head_mask.requires_grad_(requires_grad=True) + inputs = self._prepare_for_class(inputs_dict, model_class).copy() + inputs["head_mask"] = head_mask + if model.config.is_encoder_decoder: + signature = inspect.signature(model.forward) + arg_names = [*signature.parameters.keys()] + if "decoder_head_mask" in arg_names: # necessary differentiation because of T5 model + inputs["decoder_head_mask"] = head_mask + if "cross_attn_head_mask" in arg_names: + inputs["cross_attn_head_mask"] = head_mask + outputs = model(**inputs, return_dict=True) + + # Test that we can get a gradient back for importance score computation + output = sum(t.sum() for t in outputs[0]) + output = output.sum() + output.backward() + multihead_outputs = head_mask.grad + + self.assertIsNotNone(multihead_outputs) + self.assertEqual(len(multihead_outputs), self.model_tester.num_hidden_layers) + + def check_attentions_validity(attentions): + # Remove Nan + for t in attentions: + self.assertLess( + torch.sum(torch.isnan(t)), t.numel() / 4 + ) # Check we don't have more than 25% nans (arbitrary) + attentions = [ + t.masked_fill(torch.isnan(t), 0.0) for t in attentions + ] # remove them (the test is less complete) + + self.assertAlmostEqual(attentions[0][..., 0, :, :].flatten().sum().item(), 0.0) + self.assertNotEqual(attentions[0][..., -1, :, :].flatten().sum().item(), 0.0) + if len(attentions) > 2: # encoder-decoder models have only 2 layers in each module + self.assertNotEqual(attentions[1][..., 0, :, :].flatten().sum().item(), 0.0) + self.assertAlmostEqual(attentions[-1][..., -2, :, :].flatten().sum().item(), 0.0) + self.assertNotEqual(attentions[-1][..., -1, :, :].flatten().sum().item(), 0.0) + + if model.config.is_encoder_decoder: + check_attentions_validity(outputs.encoder_attentions) + check_attentions_validity(outputs.decoder_attentions) + check_attentions_validity(outputs.cross_attentions) + else: + check_attentions_validity(outputs.attentions) + + def test_head_pruning(self): + if not self.test_pruning: + self.skipTest(reason="Pruning is not activated") + + for model_class in self.all_model_classes: + ( + config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + model = model_class(config=config) + model.to(torch_device) + model.eval() + model.set_attn_implementation("eager") + heads_to_prune = { + 0: list(range(1, self.model_tester.num_attention_heads)), + -1: [0], + } + model.prune_heads(heads_to_prune) + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], 1) + # TODO: To have this check, we will need at least 3 layers. Do we really need it? + # self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads) + self.assertEqual(attentions[-1].shape[-3], self.model_tester.num_attention_heads - 1) + + def test_head_pruning_save_load_from_pretrained(self): + if not self.test_pruning: + self.skipTest(reason="Pruning is not activated") + + for model_class in self.all_model_classes: + ( + config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + model = model_class(config=config) + model.to(torch_device) + model.eval() + model.set_attn_implementation("eager") + heads_to_prune = { + 0: list(range(1, self.model_tester.num_attention_heads)), + -1: [0], + } + model.prune_heads(heads_to_prune) + + with tempfile.TemporaryDirectory() as temp_dir_name: + model.save_pretrained(temp_dir_name) + model = model_class.from_pretrained(temp_dir_name, attn_implementation="eager") + model.to(torch_device) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + self.assertEqual(attentions[0].shape[-3], 1) + # TODO: To have this check, we will need at least 3 layers. Do we really need it? + # self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads) + self.assertEqual(attentions[-1].shape[-3], self.model_tester.num_attention_heads - 1) + + def test_head_pruning_save_load_from_config_init(self): + if not self.test_pruning: + self.skipTest(reason="Pruning is not activated") + + for model_class in self.all_model_classes: + ( + config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + + heads_to_prune = { + 0: list(range(1, self.model_tester.num_attention_heads)), + -1: [0], + } + config.pruned_heads = heads_to_prune + + model = model_class(config=config) + model.to(torch_device) + model.eval() + model.set_attn_implementation("eager") + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], 1) + # TODO: To have this check, we will need at least 3 layers. Do we really need it? + # self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads) + self.assertEqual(attentions[-1].shape[-3], self.model_tester.num_attention_heads - 1) + + def test_head_pruning_integration(self): + if not self.test_pruning: + self.skipTest(reason="Pruning is not activated") + + for model_class in self.all_model_classes: + ( + config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + if "head_mask" in inputs_dict: + del inputs_dict["head_mask"] + + inputs_dict["output_attentions"] = True + config.output_hidden_states = False + + heads_to_prune = {1: [1, 2]} + config.pruned_heads = heads_to_prune + + model = model_class(config=config) + model.to(torch_device) + model.eval() + model.set_attn_implementation("eager") + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], self.model_tester.num_attention_heads - 0) + self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads - 2) + + with tempfile.TemporaryDirectory() as temp_dir_name: + model.save_pretrained(temp_dir_name) + model = model_class.from_pretrained(temp_dir_name, attn_implementation="eager") + model.to(torch_device) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], self.model_tester.num_attention_heads - 0) + self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads - 2) + + heads_to_prune = {0: [0], 1: [1, 2]} + model.prune_heads(heads_to_prune) + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + attentions = outputs[-1] + + self.assertEqual(attentions[0].shape[-3], self.model_tester.num_attention_heads - 1) + self.assertEqual(attentions[1].shape[-3], self.model_tester.num_attention_heads - 2) + + self.assertDictEqual(model.config.pruned_heads, {0: [0], 1: [1, 2]}) + + def test_hidden_states_output(self): + def check_hidden_states_output(inputs_dict, config, model_class): + model = model_class(copy.deepcopy(config)) + model.to(torch_device) + model.eval() + + with torch.no_grad(): + outputs = model(**self._prepare_for_class(inputs_dict, model_class)) + + hidden_states = outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states + + expected_num_layers = getattr( + self.model_tester, "expected_num_hidden_layers", self.model_tester.num_hidden_layers + 1 + ) + self.assertEqual(len(hidden_states), expected_num_layers) + + if hasattr(self.model_tester, "encoder_seq_length"): + seq_length = self.model_tester.encoder_seq_length + if hasattr(self.model_tester, "chunk_length") and self.model_tester.chunk_length > 1: + seq_length = seq_length * self.model_tester.chunk_length + else: + seq_length = self.model_tester.seq_length + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [seq_length, self.model_tester.hidden_size], + ) + + if config.is_encoder_decoder: + hidden_states = outputs.decoder_hidden_states + + self.assertIsInstance(hidden_states, (list, tuple)) + self.assertEqual(len(hidden_states), expected_num_layers) + seq_len = getattr(self.model_tester, "seq_length", None) + decoder_seq_length = getattr(self.model_tester, "decoder_seq_length", seq_len) + + self.assertListEqual( + list(hidden_states[0].shape[-2:]), + [decoder_seq_length, self.model_tester.hidden_size], + ) + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + inputs_dict["output_hidden_states"] = True + check_hidden_states_output(inputs_dict, config, model_class) + + # check that output_hidden_states also work using config + del inputs_dict["output_hidden_states"] + config.output_hidden_states = True + for k in config.sub_configs: + getattr(config, k).output_hidden_states = True + + check_hidden_states_output(inputs_dict, config, model_class) + + def test_retain_grad_hidden_states_attentions(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + for k in config.sub_configs: + getattr(config, k).output_hidden_states = True + + config.output_hidden_states = True + config.output_attentions = self.has_attentions + + for k in config.sub_configs: + getattr(config, k).output_attentions = self.has_attentions + + # force eager attention to support output attentions + if self.has_attentions: + config._attn_implementation = "eager" + + # no need to test all models as different heads yield the same functionality + model_class = self.all_model_classes[0] + model = model_class._from_config(config, attn_implementation="eager") + model.to(torch_device) + + inputs = self._prepare_for_class(inputs_dict, model_class) + + outputs = model(**inputs) + + output = outputs[0] + + if config.is_encoder_decoder: + # Seq2Seq models + encoder_hidden_states = outputs.encoder_hidden_states[0] + encoder_hidden_states.retain_grad() + + decoder_hidden_states = outputs.decoder_hidden_states[0] + decoder_hidden_states.retain_grad() + + if self.has_attentions: + encoder_attentions = outputs.encoder_attentions[0] + encoder_attentions.retain_grad() + + decoder_attentions = outputs.decoder_attentions[0] + decoder_attentions.retain_grad() + + cross_attentions = outputs.cross_attentions[0] + cross_attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(encoder_hidden_states.grad) + self.assertIsNotNone(decoder_hidden_states.grad) + + if self.has_attentions: + self.assertIsNotNone(encoder_attentions.grad) + self.assertIsNotNone(decoder_attentions.grad) + self.assertIsNotNone(cross_attentions.grad) + else: + # Encoder-/Decoder-only models + hidden_states = outputs.hidden_states[0] + hidden_states.retain_grad() + + if self.has_attentions: + attentions = outputs.attentions[0] + attentions.retain_grad() + + output.flatten()[0].backward(retain_graph=True) + + self.assertIsNotNone(hidden_states.grad) + + if self.has_attentions: + self.assertIsNotNone(attentions.grad) + + def test_feed_forward_chunking(self): + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + torch.manual_seed(0) + model = model_class(copy.deepcopy(original_config)) + model.to(torch_device) + model.eval() + + hidden_states_no_chunk = model(**self._prepare_for_class(inputs_dict, model_class))[0] + + torch.manual_seed(0) + original_config.chunk_size_feed_forward = 1 + model = model_class(copy.deepcopy(original_config)) + model.to(torch_device) + model.eval() + + hidden_states_with_chunk = model(**self._prepare_for_class(inputs_dict, model_class))[0] + torch.testing.assert_close(hidden_states_no_chunk, hidden_states_with_chunk, rtol=1e-3, atol=1e-3) + + def test_resize_position_vector_embeddings(self): + if not self.test_resize_position_embeddings: + self.skipTest(reason="Model does not have position embeddings") + + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + model = model_class(config) + model.to(torch_device) + + if self.model_tester.is_training is False: + model.eval() + + max_position_embeddings = config.max_position_embeddings + + # Retrieve the embeddings and clone theme + if model.config.is_encoder_decoder: + encoder_model_embed, decoder_model_embed = model.get_position_embeddings() + encoder_cloned_embeddings = encoder_model_embed.weight.clone() + decoder_cloned_embeddings = decoder_model_embed.weight.clone() + else: + model_embed = model.get_position_embeddings() + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the position embeddings with a larger max_position_embeddings increases + # the model's position embeddings size + model.resize_position_embeddings(max_position_embeddings + 10) + self.assertEqual(model.config.max_position_embeddings, max_position_embeddings + 10) + + # Check that it actually resizes the embeddings matrix + if model.config.is_encoder_decoder: + encoder_model_embed, decoder_model_embed = model.get_position_embeddings() + self.assertEqual(encoder_model_embed.weight.shape[0], encoder_cloned_embeddings.shape[0] + 10) + self.assertEqual(decoder_model_embed.weight.shape[0], decoder_cloned_embeddings.shape[0] + 10) + else: + model_embed = model.get_position_embeddings() + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that resizing the position embeddings with a smaller max_position_embeddings decreases + # the model's max_position_embeddings + model.resize_position_embeddings(max_position_embeddings - 5) + self.assertEqual(model.config.max_position_embeddings, max_position_embeddings - 5) + + # Check that it actually resizes the embeddings matrix + if model.config.is_encoder_decoder: + encoder_model_embed, decoder_model_embed = model.get_position_embeddings() + self.assertEqual(encoder_model_embed.weight.shape[0], encoder_cloned_embeddings.shape[0] - 5) + self.assertEqual(decoder_model_embed.weight.shape[0], decoder_cloned_embeddings.shape[0] - 5) + else: + model_embed = model.get_position_embeddings() + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 5) + + # Check that the model can still do a forward pass successfully (every parameter should be resized) + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Check that adding and removing tokens has not modified the first part of the embedding matrix. + models_equal = True + + if model.config.is_encoder_decoder: + for p1, p2 in zip(encoder_cloned_embeddings, encoder_model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + for p1, p2 in zip(decoder_cloned_embeddings, decoder_model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + else: + for p1, p2 in zip(cloned_embeddings, model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + def test_resize_tokens_embeddings(self): + if not self.test_resize_embeddings: + self.skipTest(reason="test_resize_embeddings is set to `False`") + ( + original_config, + inputs_dict, + ) = self.model_tester.prepare_config_and_inputs_for_common() + inputs_dict.pop("labels", None) + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + if is_deepspeed_zero3_enabled(): + with deepspeed.zero.Init(): + model = model_class(config) + else: + model = model_class(config) + model.to(torch_device) + + model_embed_pre_resize = model.get_input_embeddings() + type_model_embed_pre_resize = type(model_embed_pre_resize) + + if self.model_tester.is_training is False: + model.eval() + + model_vocab_size = config.get_text_config().vocab_size + # Retrieve the embeddings and clone theme + model_embed = model.resize_token_embeddings(model_vocab_size) + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size + 10) + new_model_vocab_size = model.config.get_text_config().vocab_size + self.assertEqual(new_model_vocab_size, model_vocab_size + 10) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + # Check to make sure the type of embeddings returned post resizing is same as type of input + type_model_embed_post_resize = type(model_embed) + self.assertEqual(type_model_embed_pre_resize, type_model_embed_post_resize) + # Check that added embeddings mean is close to the old embeddings mean + if is_deepspeed_zero3_enabled(): + with deepspeed.zero.GatheredParameters(model_embed.weight, modifier_rank=None): + old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0) + new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0) + else: + old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0) + new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0) + torch.testing.assert_close(old_embeddings_mean, new_embeddings_mean, rtol=1e-3, atol=1e-3) + + # Check that the model can still do a forward pass successfully (every parameter should be resized) + if not is_deepspeed_zero3_enabled(): + # A distriputed launcher is needed for the forward pass when deepspeed is enabled + model_inputs = self._prepare_for_class(inputs_dict, model_class) + model(**model_inputs) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size - 15) + new_model_vocab_size = model.config.get_text_config().vocab_size + self.assertEqual(new_model_vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] - 15) + + # Check that the model can still do a forward pass successfully (every parameter should be resized) + # Input ids should be clamped to the maximum size of the vocabulary + inputs_dict["input_ids"].clamp_(max=model_vocab_size - 15 - 1) + + # make sure that decoder_input_ids are resized as well + if not is_deepspeed_zero3_enabled(): + # A distriputed launcher is needed for the forward pass when deepspeed is enabled + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + model_inputs = self._prepare_for_class(inputs_dict, model_class) + model(**model_inputs) + + # Check that adding and removing tokens has not modified the first part of the embedding matrix. + models_equal = True + for p1, p2 in zip(cloned_embeddings, model_embed.weight): + if p1.data.ne(p2.data).sum() > 0: + models_equal = False + + self.assertTrue(models_equal) + + del model + del config + # Copy again. config changed with embedding resizing (`vocab_size` changed) + config = copy.deepcopy(original_config) + if is_deepspeed_zero3_enabled(): + with deepspeed.zero.Init(): + model = model_class(config) + else: + model = model_class(config) + model.to(torch_device) + + model_vocab_size = config.get_text_config().vocab_size + model.resize_token_embeddings(model_vocab_size + 10, pad_to_multiple_of=1) + new_model_vocab_size = model.config.get_text_config().vocab_size + self.assertTrue(new_model_vocab_size + 10, model_vocab_size) + + model_embed = model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=64) + new_model_vocab_size = model.config.get_text_config().vocab_size + self.assertTrue(model_embed.weight.shape[0] // 64, 0) + + self.assertTrue(model_embed.weight.shape[0], new_model_vocab_size) + self.assertTrue(new_model_vocab_size, model.vocab_size) + + model_embed = model.resize_token_embeddings(model_vocab_size + 13, pad_to_multiple_of=64) + self.assertTrue(model_embed.weight.shape[0] // 64, 0) + + # Check that resizing a model to a multiple of pad_to_multiple leads to a model of exactly that size + target_dimension = 128 + model_embed = model.resize_token_embeddings(target_dimension, pad_to_multiple_of=64) + self.assertTrue(model_embed.weight.shape[0], target_dimension) + + with self.assertRaisesRegex( + ValueError, + "Asking to pad the embedding matrix to a multiple of `1.3`, which is not and integer. Please make sure to pass an integer", + ): + model.resize_token_embeddings(model_vocab_size, pad_to_multiple_of=1.3) + + # Test when `vocab_size` is smaller than `hidden_size`. + del model + del config + # Copy again. config changed with embedding resizing (`vocab_size` changed) + config = copy.deepcopy(original_config) + config.vocab_size = 4 + config.pad_token_id = 3 + if is_deepspeed_zero3_enabled(): + with deepspeed.zero.Init(): + model = model_class(config) + else: + model = model_class(config) + model.to(torch_device) + + model_vocab_size = config.get_text_config().vocab_size + # Retrieve the embeddings and clone theme + model_embed = model.resize_token_embeddings(model_vocab_size) + cloned_embeddings = model_embed.weight.clone() + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_embed = model.resize_token_embeddings(model_vocab_size + 10) + new_model_vocab_size = model.config.get_text_config().vocab_size + self.assertEqual(new_model_vocab_size, model_vocab_size + 10) + # Check that it actually resizes the embeddings matrix + self.assertEqual(model_embed.weight.shape[0], cloned_embeddings.shape[0] + 10) + # Check to make sure the type of embeddings returned post resizing is same as type of input + type_model_embed_post_resize = type(model_embed) + self.assertEqual(type_model_embed_pre_resize, type_model_embed_post_resize) + # Check that added embeddings mean is close to the old embeddings mean + if is_deepspeed_zero3_enabled(): + with deepspeed.zero.GatheredParameters(model_embed.weight, modifier_rank=None): + old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0) + new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0) + else: + old_embeddings_mean = torch.mean(model_embed.weight.data[:-10, :], axis=0) + new_embeddings_mean = torch.mean(model_embed.weight.data[-10:, :], axis=0) + torch.testing.assert_close(old_embeddings_mean, new_embeddings_mean, rtol=1e-3, atol=1e-3) + + @require_deepspeed + @require_torch_accelerator + def test_resize_tokens_embeddings_with_deepspeed(self): + ds_config = { + "zero_optimization": { + "stage": 3, + "offload_param": {"device": "cpu", "pin_memory": True}, + }, + } + with _deepspeed_zero3(ds_config): + self.test_resize_tokens_embeddings() + + @require_deepspeed + @require_torch_multi_accelerator + def test_resize_tokens_embeddings_with_deepspeed_multi_gpu(self): + ds_config = { + "zero_optimization": { + "stage": 3, + }, + } + with _deepspeed_zero3(ds_config): + self.test_resize_tokens_embeddings() + + def test_resize_embeddings_untied(self): + if not self.test_resize_embeddings: + self.skipTest(reason="test_resize_embeddings is set to `False`") + + original_config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + original_config.tie_word_embeddings = False + inputs_dict.pop("labels", None) + + # if model cannot untied embeddings -> leave test + if original_config.tie_word_embeddings: + self.skipTest(reason="Model cannot untied embeddings") + + for model_class in self.all_model_classes: + config = copy.deepcopy(original_config) + if is_deepspeed_zero3_enabled(): + with deepspeed.zero.Init(): + model = model_class(config) + else: + model = model_class(config).to(torch_device) + + # if no output embeddings -> leave test + if model.get_output_embeddings() is None: + continue + + # Check that resizing the token embeddings with a larger vocab size increases the model's vocab size + model_vocab_size = config.get_text_config().vocab_size + model.resize_token_embeddings(model_vocab_size + 10) + new_model_vocab_size = model.config.get_text_config().vocab_size + self.assertEqual(new_model_vocab_size, model_vocab_size + 10) + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size + 10) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size + 10) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + if not is_deepspeed_zero3_enabled(): + # A distriputed launcher is needed for the forward pass when deepspeed is enabled + model(**self._prepare_for_class(inputs_dict, model_class)) + + # Test multivariate resizing. + model.resize_token_embeddings(model_vocab_size + 10) + output_embeds = model.get_output_embeddings() + # Check that added embeddings mean is close to the old embeddings mean + if is_deepspeed_zero3_enabled(): + with deepspeed.zero.GatheredParameters(output_embeds.weight, modifier_rank=None): + old_embeddings_mean = torch.mean(output_embeds.weight.data[:-10, :], axis=0) + new_embeddings_mean = torch.mean(output_embeds.weight.data[-10:, :], axis=0) + else: + old_embeddings_mean = torch.mean(output_embeds.weight.data[:-10, :], axis=0) + new_embeddings_mean = torch.mean(output_embeds.weight.data[-10:, :], axis=0) + torch.testing.assert_close(old_embeddings_mean, new_embeddings_mean, rtol=1e-3, atol=1e-3) + # check if the old bias mean close to added bias mean. + if output_embeds.bias is not None: + if is_deepspeed_zero3_enabled(): + with deepspeed.zero.GatheredParameters(output_embeds.bias, modifier_rank=None): + old_bias_mean = torch.mean(output_embeds.bias.data[:-10], axis=0) + new_bias_mean = torch.mean(output_embeds.bias.data[-10:], axis=0) + else: + old_bias_mean = torch.mean(output_embeds.bias.data[:-10], axis=0) + new_bias_mean = torch.mean(output_embeds.bias.data[-10:], axis=0) + + torch.testing.assert_close(old_bias_mean, new_bias_mean, rtol=1e-5, atol=1e-5) + + # Check that resizing the token embeddings with a smaller vocab size decreases the model's vocab size + model.resize_token_embeddings(model_vocab_size - 15) + new_model_vocab_size = model.config.get_text_config().vocab_size + self.assertEqual(new_model_vocab_size, model_vocab_size - 15) + # Check that it actually resizes the embeddings matrix + output_embeds = model.get_output_embeddings() + self.assertEqual(output_embeds.weight.shape[0], model_vocab_size - 15) + # Check bias if present + if output_embeds.bias is not None: + self.assertEqual(output_embeds.bias.shape[0], model_vocab_size - 15) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + # Input ids should be clamped to the maximum size of the vocabulary + inputs_dict["input_ids"].clamp_(max=model_vocab_size - 15 - 1) + if "decoder_input_ids" in inputs_dict: + inputs_dict["decoder_input_ids"].clamp_(max=model_vocab_size - 15 - 1) + # Check that the model can still do a forward pass successfully (every parameter should be resized) + if not is_deepspeed_zero3_enabled(): + # A distriputed launcher is needed for the forward pass when deepspeed is enabled + model(**self._prepare_for_class(inputs_dict, model_class)) + + @require_deepspeed + @require_torch_accelerator + def test_resize_embeddings_untied_with_deepspeed(self): + ds_config = { + "zero_optimization": { + "stage": 3, + "offload_param": {"device": "cpu", "pin_memory": True}, + }, + } + with _deepspeed_zero3(ds_config): + self.test_resize_embeddings_untied() + + @require_deepspeed + @require_torch_multi_accelerator + def test_resize_embeddings_untied_with_deepspeed_multi_gpu(self): + ds_config = { + "zero_optimization": { + "stage": 3, + }, + } + with _deepspeed_zero3(ds_config): + self.test_resize_embeddings_untied() + + def test_model_get_set_embeddings(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(copy.deepcopy(config)) + self.assertIsInstance(model.get_input_embeddings(), nn.Embedding) + + new_input_embedding_layer = nn.Embedding(10, 10) + model.set_input_embeddings(new_input_embedding_layer) + self.assertEqual(model.get_input_embeddings(), new_input_embedding_layer) + + x = model.get_output_embeddings() + self.assertTrue(x is None or isinstance(x, nn.Linear)) + + def test_model_main_input_name(self): + for model_class in self.all_model_classes: + model_signature = inspect.signature(getattr(model_class, "forward")) + # The main input is the name of the argument after `self` + observed_main_input_name = list(model_signature.parameters.keys())[1] + self.assertEqual(model_class.main_input_name, observed_main_input_name) + + def test_correct_missing_keys(self): + if not self.test_missing_keys: + self.skipTest(reason="test_missing_keys is set to `False`") + + for model_class in self.all_model_classes: + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + base_model_prefix = model.base_model_prefix + + if hasattr(model, base_model_prefix): + extra_params = {k: v for k, v in model.named_parameters() if not k.startswith(base_model_prefix)} + extra_params.update({k: v for k, v in model.named_buffers() if not k.startswith(base_model_prefix)}) + # Some models define this as None + if model._keys_to_ignore_on_load_missing: + for key in model._keys_to_ignore_on_load_missing: + extra_params.pop(key, None) + + if not extra_params: + # In that case, we *are* on a head model, but every single key is not actual parameters + continue + + with tempfile.TemporaryDirectory() as temp_dir_name: + model.base_model.save_pretrained(temp_dir_name) + model, loading_info = model_class.from_pretrained(temp_dir_name, output_loading_info=True) + self.assertGreater(len(loading_info["missing_keys"]), 0, model.__class__.__name__) + + def test_tie_model_weights(self): + if not self.test_torchscript: + self.skipTest(reason="test_torchscript is set to `False`") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def check_same_values(layer_1, layer_2): + equal = True + for p1, p2 in zip(layer_1.weight, layer_2.weight): + if p1.data.ne(p2.data).sum() > 0: + equal = False + return equal + + for model_class in self.all_model_classes: + config.torchscript = True + model_not_tied = model_class(copy.deepcopy(config)) + if model_not_tied.get_output_embeddings() is None: + continue + + config_tied = copy.deepcopy(config) + config_tied.torchscript = False + model_tied = model_class(config_tied) + params_tied = list(model_tied.parameters()) + # Check that the embedding layer and decoding layer are the same in size and in value + # self.assertTrue(check_same_values(embeddings, decoding)) + + # Check that after resize they remain tied. + vocab_size = config.get_text_config().vocab_size + model_tied.resize_token_embeddings(vocab_size + 10) + params_tied_2 = list(model_tied.parameters()) + self.assertEqual(len(params_tied_2), len(params_tied)) + + @require_safetensors + def test_can_use_safetensors(self): + for model_class in self.all_model_classes: + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + model_tied = model_class(config) + with tempfile.TemporaryDirectory() as d: + try: + model_tied.save_pretrained(d, safe_serialization=True) + except Exception as e: + raise Exception(f"Class {model_class.__name__} cannot be saved using safetensors: {e}") + + model_reloaded, infos = model_class.from_pretrained(d, output_loading_info=True) + # Checking the state dicts are correct + reloaded_state = model_reloaded.state_dict() + for k, v in model_tied.state_dict().items(): + self.assertIn(k, reloaded_state, f"Key {k} is missing from reloaded") + torch.testing.assert_close( + v, reloaded_state[k], msg=lambda x: f"{model_class.__name__}: Tensor {k}: {x}" + ) + # Checking there was no complain of missing weights + self.assertEqual(infos["missing_keys"], []) + + # Checking the tensor sharing are correct + ptrs = defaultdict(list) + for k, v in model_tied.state_dict().items(): + ptrs[v.data_ptr()].append(k) + + shared_ptrs = {k: v for k, v in ptrs.items() if len(v) > 1} + + for shared_names in shared_ptrs.values(): + reloaded_ptrs = {reloaded_state[k].data_ptr() for k in shared_names} + self.assertEqual( + len(reloaded_ptrs), + 1, + f"The shared pointers are incorrect, found different pointers for keys {shared_names}", + ) + + def test_load_save_without_tied_weights(self): + for model_class in self.all_model_classes: + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + config.tie_word_embeddings = False + model = model_class(config) + with tempfile.TemporaryDirectory() as d: + model.save_pretrained(d) + + model_reloaded, infos = model_class.from_pretrained(d, output_loading_info=True) + # Checking the state dicts are correct + reloaded_state = model_reloaded.state_dict() + for k, v in model.state_dict().items(): + self.assertIn(k, reloaded_state, f"Key {k} is missing from reloaded") + torch.testing.assert_close( + v, reloaded_state[k], msg=lambda x: f"{model_class.__name__}: Tensor {k}: {x}" + ) + # Checking there was no complain of missing weights + self.assertEqual(infos["missing_keys"], []) + + def test_tied_weights_keys(self): + original_config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + copied_config = copy.deepcopy(original_config) + copied_config.get_text_config().tie_word_embeddings = True + model_tied = model_class(copied_config) + + tied_weight_keys = _get_tied_weight_keys(model_tied) + # If we don't find any tied weights keys, and by default we don't tie the embeddings, it's because the model + # does not tie them + if len(tied_weight_keys) == 0 and not original_config.tie_word_embeddings: + continue + + ptrs = collections.defaultdict(list) + for name, tensor in model_tied.state_dict().items(): + ptrs[id_tensor_storage(tensor)].append(name) + + # These are all the pointers of shared tensors. + tied_params = [names for _, names in ptrs.items() if len(names) > 1] + + # Detect we get a hit for each key + for key in tied_weight_keys: + is_tied_key = any(re.search(key, p) for group in tied_params for p in group) + self.assertTrue(is_tied_key, f"{key} is not a tied weight key for {model_class}.") + + # Removed tied weights found from tied params -> there should only be one left after + for key in tied_weight_keys: + for i in range(len(tied_params)): + tied_params[i] = [p for p in tied_params[i] if re.search(key, p) is None] + + tied_params = [group for group in tied_params if len(group) > 1] + self.assertListEqual( + tied_params, + [], + f"Missing `_tied_weights_keys` for {model_class}: add all of {tied_params} except one.", + ) + + def test_model_weights_reload_no_missing_tied_weights(self): + for model_class in self.all_model_classes: + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + # We are nuking ALL weights on file, so every parameter should + # yell on load. We're going to detect if we yell too much, or too little. + placeholder_dict = {"tensor": torch.tensor([1, 2])} + safe_save_file(placeholder_dict, os.path.join(tmp_dir, "model.safetensors"), metadata={"format": "pt"}) + model_reloaded, infos = model_class.from_pretrained(tmp_dir, output_loading_info=True) + + params = dict(model_reloaded.named_parameters()) + params.update(dict(model_reloaded.named_buffers())) + param_names = set(params.keys()) + + missing_keys = set(infos["missing_keys"]) + + extra_missing = missing_keys - param_names + # Remove tied weights from extra missing: they are normally not warned as missing if their tied + # counterpart is present but here there are no weights at all so we do get the warning. + ptrs = collections.defaultdict(list) + for name, tensor in model_reloaded.state_dict().items(): + ptrs[id_tensor_storage(tensor)].append(name) + tied_params = [names for _, names in ptrs.items() if len(names) > 1] + for group in tied_params: + # We remove the group from extra_missing if not all weights from group are in it + if len(set(group) - extra_missing) > 0: + extra_missing = extra_missing - set(group) + + self.assertEqual( + extra_missing, + set(), + f"This model {model_class.__name__} might be missing some `keys_to_ignore`: {extra_missing}. " + f"For debugging, tied parameters are {tied_params}", + ) + + missed_missing = param_names - missing_keys + # Remove nonpersistent buffers from missed_missing + buffers = [n for n, _ in model_reloaded.named_buffers()] + nonpersistent_buffers = {n for n in buffers if n not in model_reloaded.state_dict()} + missed_missing = missed_missing - nonpersistent_buffers + + if model_reloaded._keys_to_ignore_on_load_missing is None: + expected_missing = set() + else: + expected_missing = set() + for pattern in model_reloaded._keys_to_ignore_on_load_missing: + expected_missing.update({k for k in param_names if re.search(pattern, k) is not None}) + self.assertEqual( + missed_missing, + expected_missing, + f"This model {model_class.__name__} ignores keys {missed_missing} but they look like real" + " parameters. If they are non persistent buffers make sure to instantiate them with" + " `persistent=False`", + ) + + def test_model_outputs_equivalence(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + def set_nan_tensor_to_zero(t): + t[t != t] = 0 + return t + + def check_equivalence(model, tuple_inputs, dict_inputs, additional_kwargs={}): + with torch.no_grad(): + tuple_output = model(**tuple_inputs, return_dict=False, **additional_kwargs) + dict_output = model(**dict_inputs, return_dict=True, **additional_kwargs).to_tuple() + + def recursive_check(tuple_object, dict_object): + if isinstance(tuple_object, (list, tuple)): + for tuple_iterable_value, dict_iterable_value in zip(tuple_object, dict_object): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif isinstance(tuple_object, dict): + for tuple_iterable_value, dict_iterable_value in zip( + tuple_object.values(), dict_object.values() + ): + recursive_check(tuple_iterable_value, dict_iterable_value) + elif tuple_object is None: + return + # model might return non-tensors objects (e.g. Cache class) + elif isinstance(tuple_object, torch.Tensor): + self.assertTrue( + torch.allclose( + set_nan_tensor_to_zero(tuple_object), set_nan_tensor_to_zero(dict_object), atol=1e-5 + ), + msg=( + "Tuple and dict output are not equal. Difference:" + f" {torch.max(torch.abs(tuple_object - dict_object))}. Tuple has `nan`:" + f" {torch.isnan(tuple_object).any()} and `inf`: {torch.isinf(tuple_object)}. Dict has" + f" `nan`: {torch.isnan(dict_object).any()} and `inf`: {torch.isinf(dict_object)}." + ), + ) + + recursive_check(tuple_output, dict_output) + + for model_class in self.all_model_classes: + model = model_class(copy.deepcopy(config)) + model.to(torch_device) + model.eval() + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_hidden_states": True}) + + if self.has_attentions: + tuple_inputs = self._prepare_for_class(inputs_dict, model_class) + dict_inputs = self._prepare_for_class(inputs_dict, model_class) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence(model, tuple_inputs, dict_inputs, {"output_attentions": True}) + + tuple_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + dict_inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + check_equivalence( + model, tuple_inputs, dict_inputs, {"output_hidden_states": True, "output_attentions": True} + ) + + # Don't copy this method to model specific test file! + # TODO: remove this method once the issues are all fixed! + def _make_attention_mask_non_null(self, inputs_dict): + """Make sure no sequence has all zeros as attention mask""" + + for k in ["attention_mask", "encoder_attention_mask", "decoder_attention_mask"]: + if k in inputs_dict: + attention_mask = inputs_dict[k] + + # Make sure no all 0s attention masks - to avoid failure at this moment. + # Put `1` at the beginning of sequences to make it still work when combining causal attention masks. + # TODO: remove this line once a fix regarding large negative values for attention mask is done. + attention_mask = torch.cat( + [torch.ones_like(attention_mask[:, :1], dtype=attention_mask.dtype), attention_mask[:, 1:]], dim=-1 + ) + + # Here we make the first sequence with all 0s as attention mask. + # Currently, this will fail for `TFWav2Vec2Model`. This is caused by the different large negative + # values, like `1e-4`, `1e-9`, `1e-30` and `-inf` for attention mask across models/frameworks. + # TODO: enable this block once the large negative values thing is cleaned up. + # (see https://github.com/huggingface/transformers/issues/14859) + # attention_mask = torch.cat( + # [torch.zeros_like(attention_mask[:1], dtype=attention_mask.dtype), attention_mask[1:]], + # dim=0 + # ) + + inputs_dict[k] = attention_mask + + # Don't copy this method to model specific test file! + # TODO: remove this method once the issues are all fixed! + def _postprocessing_to_ignore_test_cases(self, tf_outputs, pt_outputs, model_class): + """For temporarily ignoring some failed test cases (issues to be fixed)""" + + tf_keys = {k for k, v in tf_outputs.items() if v is not None} + pt_keys = {k for k, v in pt_outputs.items() if v is not None} + + key_differences = tf_keys.symmetric_difference(pt_keys) + + if model_class.__name__ in [ + "FlaubertWithLMHeadModel", + "FunnelForPreTraining", + "ElectraForPreTraining", + "XLMWithLMHeadModel", + ]: + for k in key_differences: + if k in ["loss", "losses"]: + tf_keys.discard(k) + pt_keys.discard(k) + elif model_class.__name__.startswith("GPT2"): + # `TFGPT2` has `past_key_values` as a tensor while `GPT2` has it as a tuple. + tf_keys.discard("past_key_values") + pt_keys.discard("past_key_values") + + # create new outputs from the remaining fields + new_tf_outputs = type(tf_outputs)(**{k: tf_outputs[k] for k in tf_keys}) + new_pt_outputs = type(pt_outputs)(**{k: pt_outputs[k] for k in pt_keys}) + + return new_tf_outputs, new_pt_outputs + + def test_inputs_embeds(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(config) + model.to(torch_device) + model.eval() + + model_forward_args = inspect.signature(model.forward).parameters + if "inputs_embeds" not in model_forward_args: + self.skipTest(reason="This model doesn't use `inputs_embeds`") + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + del inputs["input_ids"] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + + wte = model.get_input_embeddings() + if not self.is_encoder_decoder: + inputs["inputs_embeds"] = wte(input_ids) + else: + inputs["inputs_embeds"] = wte(encoder_input_ids) + inputs["decoder_inputs_embeds"] = wte(decoder_input_ids) + + with torch.no_grad(): + model(**inputs)[0] + + def test_inputs_embeds_matches_input_ids(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class.__name__ not in get_values(MODEL_MAPPING_NAMES): + continue + model = model_class(config) + model.to(torch_device) + model.eval() + + model_forward_args = inspect.signature(model.forward).parameters + if "inputs_embeds" not in model_forward_args: + self.skipTest(reason="This model doesn't use `inputs_embeds`") + + inputs = copy.deepcopy(self._prepare_for_class(inputs_dict, model_class)) + pad_token_id = ( + config.get_text_config().pad_token_id if config.get_text_config().pad_token_id is not None else 1 + ) + + wte = model.get_input_embeddings() + if not self.is_encoder_decoder: + input_ids = inputs["input_ids"] + # some models infer position ids/attn mask differently when input ids + # by check if pad_token let's make sure no padding is in input ids + not_pad_token_id = pad_token_id + 1 if max(0, pad_token_id - 1) == 0 else pad_token_id - 1 + input_ids[input_ids == pad_token_id] = not_pad_token_id + del inputs["input_ids"] + inputs_embeds = wte(input_ids) + with torch.no_grad(): + out_ids = model(input_ids=input_ids, **inputs)[0] + out_embeds = model(inputs_embeds=inputs_embeds, **inputs)[0] + else: + encoder_input_ids = inputs["input_ids"] + decoder_input_ids = inputs.get("decoder_input_ids", encoder_input_ids) + encoder_input_ids[encoder_input_ids == pad_token_id] = max(0, pad_token_id + 1) + decoder_input_ids[decoder_input_ids == pad_token_id] = max(0, pad_token_id + 1) + del inputs["input_ids"] + inputs.pop("decoder_input_ids", None) + inputs_embeds = wte(encoder_input_ids) + decoder_inputs_embeds = wte(decoder_input_ids) + with torch.no_grad(): + out_ids = model(input_ids=encoder_input_ids, decoder_input_ids=decoder_input_ids, **inputs)[0] + out_embeds = model( + inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, **inputs + )[0] + torch.testing.assert_close(out_embeds, out_ids) + + @require_torch_gpu + @require_torch_multi_gpu + def test_multi_gpu_data_parallel_forward(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # some params shouldn't be scattered by nn.DataParallel + # so just remove them if they are present. + blacklist_non_batched_params = ["head_mask", "decoder_head_mask", "cross_attn_head_mask"] + for k in blacklist_non_batched_params: + inputs_dict.pop(k, None) + + # move input tensors to accelerator O + for k, v in inputs_dict.items(): + if torch.is_tensor(v): + inputs_dict[k] = v.to(0) + + for model_class in self.all_model_classes: + model = model_class(config=config) + model.to(0) + model.eval() + + # Wrap model in nn.DataParallel + model = nn.DataParallel(model) + with torch.no_grad(): + _ = model(**self._prepare_for_class(inputs_dict, model_class)) + + @require_torch_gpu + @require_torch_multi_gpu + def test_model_parallelization(self): + if not self.test_model_parallel: + self.skipTest(reason="test_model_parallel is set to False") + + # a candidate for testing_utils + def get_current_gpu_memory_use(): + """returns a list of VRAM allocations per GPU in MBs""" + + per_device_memory = [] + for id in range(backend_device_count(torch_device)): + with backend_torch_accelerator_module(torch_device).device(id): + per_device_memory.append(backend_memory_allocated(torch_device) >> 20) + + return per_device_memory + + # Needs a large model to see the difference. + config = self.model_tester.get_large_model_config() + + for model_class in self.all_parallelizable_model_classes: + backend_empty_cache(torch_device) + + # 1. single gpu memory load + unload + memory measurements + # Retrieve initial memory usage (can easily be ~0.6-1.5GB if cuda-kernels have been preloaded by previous tests) + memory_at_start = get_current_gpu_memory_use() + + # Put model on device 0 and take a memory snapshot + model = model_class(config) + model.to(f"{torch_device}:0") + memory_after_model_load = get_current_gpu_memory_use() + + # The memory use on device 0 should be higher than it was initially. + self.assertGreater(memory_after_model_load[0], memory_at_start[0]) + + del model + gc.collect() + backend_empty_cache(torch_device) + + # 2. MP test + # it's essential to re-calibrate the usage before the next stage + memory_at_start = get_current_gpu_memory_use() + + # Spread model layers over multiple devices + model = model_class(config) + model.parallelize() + memory_after_parallelization = get_current_gpu_memory_use() + + # Assert that the memory use on all devices is higher than it was when loaded only on CPU + for n in range(len(model.device_map.keys())): + self.assertGreater(memory_after_parallelization[n], memory_at_start[n]) + + # Assert that the memory use of device 0 is lower than it was when the entire model was loaded on it + self.assertLess(memory_after_parallelization[0], memory_after_model_load[0]) + + # Assert that the memory use of device 1 is higher than it was when the entire model was loaded + # on device 0 and device 1 wasn't used at all + self.assertGreater(memory_after_parallelization[1], memory_after_model_load[1]) + + del model + gc.collect() + backend_empty_cache(torch_device) + + @require_torch_gpu + @require_torch_multi_gpu + def test_model_parallel_equal_results(self): + if not self.test_model_parallel: + self.skipTest(reason="test_model_parallel is set to False") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_parallelizable_model_classes: + inputs_dict = self._prepare_for_class(inputs_dict, model_class) + + def cast_to_device(dictionary, device): + output = {} + for k, v in dictionary.items(): + if isinstance(v, torch.Tensor): + output[k] = v.to(device) + else: + output[k] = v + + return output + + model = model_class(config) + output = model(**cast_to_device(inputs_dict, "cpu")) + + model.parallelize() + + parallel_output = model(**cast_to_device(inputs_dict, f"{torch_device}:0")) + + for value, parallel_value in zip(output, parallel_output): + if isinstance(value, torch.Tensor): + torch.testing.assert_close(value, parallel_value.to("cpu"), rtol=1e-7, atol=1e-7) + elif isinstance(value, (tuple, list)): + for value_, parallel_value_ in zip(value, parallel_value): + torch.testing.assert_close(value_, parallel_value_.to("cpu"), rtol=1e-7, atol=1e-7) + + def check_device_map_is_respected(self, model, device_map): + for param_name, param in model.named_parameters(): + # Find device in device_map + while len(param_name) > 0 and param_name not in device_map: + param_name = ".".join(param_name.split(".")[:-1]) + if param_name not in device_map: + raise ValueError("device map is incomplete, it does not contain any device for `param_name`.") + + param_device = device_map[param_name] + if param_device in ["cpu", "disk"]: + self.assertEqual(param.device, torch.device("meta")) + elif param_device in ["mps"]: + self.assertEqual(param.device, torch.device("mps")) + else: + # when loaded with device_map, `param_device` are integer values for cuda/xpu/hpu/npu/mlu + self.assertEqual(param.device, torch.device(f"{torch_device}:{param_device}")) + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_disk_offload_bin(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class._no_split_modules is None: + continue + + inputs_dict_class = self._prepare_for_class(inputs_dict, model_class) + model = model_class(copy.deepcopy(config)).eval() + model = model.to(torch_device) + torch.manual_seed(0) + base_output = model(**inputs_dict_class) + + model_size = compute_module_sizes(model)[""] + with tempfile.TemporaryDirectory() as tmp_dir: + model.cpu().save_pretrained(tmp_dir, safe_serialization=False) + + with self.assertRaises(ValueError): + max_size = int(self.model_split_percents[0] * model_size) + max_memory = {0: max_size, "cpu": max_size} + # This errors out cause it's missing an offload folder + new_model = model_class.from_pretrained(tmp_dir, device_map="auto", max_memory=max_memory) + + max_size = int(self.model_split_percents[1] * model_size) + max_memory = {0: max_size, "cpu": max_size} + new_model = model_class.from_pretrained( + tmp_dir, device_map="auto", max_memory=max_memory, offload_folder=tmp_dir + ) + + self.check_device_map_is_respected(new_model, new_model.hf_device_map) + torch.manual_seed(0) + new_output = new_model(**inputs_dict_class) + + if isinstance(base_output[0], tuple) and isinstance(new_output[0], tuple): + [ + torch.testing.assert_close(a, b, rtol=1e-5, atol=1e-5) + for a, b in zip(base_output[0], new_output[0]) + ] + else: + torch.testing.assert_close(base_output[0], new_output[0], rtol=1e-5, atol=1e-5) + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_disk_offload_safetensors(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class._no_split_modules is None: + continue + + inputs_dict_class = self._prepare_for_class(inputs_dict, model_class) + model = model_class(copy.deepcopy(config)).eval() + model = model.to(torch_device) + torch.manual_seed(0) + base_output = model(**inputs_dict_class) + + model_size = compute_module_sizes(model)[""] + with tempfile.TemporaryDirectory() as tmp_dir: + model.cpu().save_pretrained(tmp_dir) + + max_size = int(self.model_split_percents[1] * model_size) + max_memory = {0: max_size, "cpu": max_size} + + # This doesn't error out as it's in safetensors and doesn't need an offload folder + new_model = model_class.from_pretrained(tmp_dir, device_map="auto", max_memory=max_memory) + + self.check_device_map_is_respected(new_model, new_model.hf_device_map) + torch.manual_seed(0) + new_output = new_model(**inputs_dict_class) + + if isinstance(base_output[0], tuple) and isinstance(new_output[0], tuple): + [ + torch.testing.assert_close(a, b, rtol=1e-5, atol=1e-5) + for a, b in zip(base_output[0], new_output[0]) + ] + else: + torch.testing.assert_close(base_output[0], new_output[0], rtol=1e-5, atol=1e-5) + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_cpu_offload(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class._no_split_modules is None: + continue + + inputs_dict_class = self._prepare_for_class(inputs_dict, model_class) + model = model_class(copy.deepcopy(config)).eval() + model = model.to(torch_device) + + torch.manual_seed(0) + base_output = model(**inputs_dict_class) + + model_size = compute_module_sizes(model)[""] + # We test several splits of sizes to make sure it works. + max_gpu_sizes = [int(p * model_size) for p in self.model_split_percents[1:]] + with tempfile.TemporaryDirectory() as tmp_dir: + model.cpu().save_pretrained(tmp_dir) + + for max_size in max_gpu_sizes: + max_memory = {0: max_size, "cpu": model_size * 2} + new_model = model_class.from_pretrained(tmp_dir, device_map="auto", max_memory=max_memory) + # Making sure part of the model will actually end up offloaded + self.assertSetEqual(set(new_model.hf_device_map.values()), {0, "cpu"}) + + self.check_device_map_is_respected(new_model, new_model.hf_device_map) + + torch.manual_seed(0) + new_output = new_model(**inputs_dict_class) + + if isinstance(base_output[0], tuple) and isinstance(new_output[0], tuple): + [ + torch.testing.assert_close(a, b, rtol=1e-5, atol=1e-5) + for a, b in zip(base_output[0], new_output[0]) + ] + else: + torch.testing.assert_close(base_output[0], new_output[0], rtol=1e-5, atol=1e-5) + + @require_non_hpu + @require_accelerate + @mark.accelerate_tests + @require_torch_multi_accelerator + def test_model_parallelism(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class._no_split_modules is None: + continue + + inputs_dict_class = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config).eval() + model = model.to(torch_device) + + torch.manual_seed(0) + base_output = model(**inputs_dict_class) + + model_size = compute_module_sizes(model)[""] + # We test several splits of sizes to make sure it works. + max_gpu_sizes = [int(p * model_size) for p in self.model_split_percents[1:]] + with tempfile.TemporaryDirectory() as tmp_dir: + model.cpu().save_pretrained(tmp_dir) + + for max_size in max_gpu_sizes: + max_memory = {0: max_size, 1: model_size * 2, "cpu": model_size * 2} + new_model = model_class.from_pretrained(tmp_dir, device_map="auto", max_memory=max_memory) + # Making sure part of the model will actually end up offloaded + self.assertSetEqual(set(new_model.hf_device_map.values()), {0, 1}) + self.check_device_map_is_respected(new_model, new_model.hf_device_map) + + torch.manual_seed(0) + new_output = new_model(**inputs_dict_class) + + if isinstance(base_output[0], tuple) and isinstance(new_output[0], tuple): + [ + torch.testing.assert_close(a, b, rtol=1e-5, atol=1e-5) + for a, b in zip(base_output[0], new_output[0]) + ] + else: + torch.testing.assert_close(base_output[0], new_output[0], rtol=1e-5, atol=1e-5) + + def test_problem_types(self): + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + problem_types = [ + {"title": "multi_label_classification", "num_labels": 2, "dtype": torch.float}, + {"title": "single_label_classification", "num_labels": 1, "dtype": torch.long}, + {"title": "regression", "num_labels": 1, "dtype": torch.float}, + ] + + for model_class in self.all_model_classes: + if model_class.__name__ not in [ + *get_values(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES), + *get_values(MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES), + ]: + continue + + for problem_type in problem_types: + with self.subTest(msg=f"Testing {model_class} with {problem_type['title']}"): + config.problem_type = problem_type["title"] + config.num_labels = problem_type["num_labels"] + + model = model_class(config) + model.to(torch_device) + model.train() + + inputs = self._prepare_for_class(inputs_dict, model_class, return_labels=True) + + if problem_type["num_labels"] > 1: + inputs["labels"] = inputs["labels"].unsqueeze(1).repeat(1, problem_type["num_labels"]) + + inputs["labels"] = inputs["labels"].to(problem_type["dtype"]) + + # This tests that we do not trigger the warning form PyTorch "Using a target size that is different + # to the input size. This will likely lead to incorrect results due to broadcasting. Please ensure + # they have the same size." which is a symptom something in wrong for the regression problem. + # See https://github.com/huggingface/transformers/issues/11780 + with warnings.catch_warnings(record=True) as warning_list: + loss = model(**inputs).loss + for w in warning_list: + if "Using a target size that is different to the input size" in str(w.message): + raise ValueError( + f"Something is going wrong in the regression problem: intercepted {w.message}" + ) + + loss.backward() + + def test_load_with_mismatched_shapes(self): + if not self.test_mismatched_shapes: + self.skipTest(reason="test_missmatched_shapes is set to False") + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + if model_class.__name__ not in get_values(MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES): + continue + + with self.subTest(msg=f"Testing {model_class}"): + with tempfile.TemporaryDirectory() as tmp_dir: + model = model_class(config) + model.save_pretrained(tmp_dir) + + # Fails when we don't set ignore_mismatched_sizes=True + with self.assertRaises(RuntimeError): + new_model = AutoModelForSequenceClassification.from_pretrained(tmp_dir, num_labels=42) + with self.assertRaises(RuntimeError): + new_model_without_prefix = AutoModel.from_pretrained(tmp_dir, vocab_size=10) + + logger = logging.get_logger("transformers.modeling_utils") + + with CaptureLogger(logger) as cl: + new_model = AutoModelForSequenceClassification.from_pretrained( + tmp_dir, num_labels=42, ignore_mismatched_sizes=True + ) + self.assertIn("the shapes did not match", cl.out) + new_model.to(torch_device) + inputs = self._prepare_for_class(inputs_dict, model_class) + logits = new_model(**inputs).logits + self.assertEqual(logits.shape[1], 42) + + with CaptureLogger(logger) as cl: + new_model_without_prefix = AutoModel.from_pretrained( + tmp_dir, vocab_size=10, ignore_mismatched_sizes=True + ) + self.assertIn("the shapes did not match", cl.out) + input_ids = ids_tensor((2, 8), 10) + new_model_without_prefix.to(torch_device) + if self.is_encoder_decoder: + new_model_without_prefix(input_ids, decoder_input_ids=input_ids) + else: + new_model_without_prefix(input_ids) + + def test_mismatched_shapes_have_properly_initialized_weights(self): + if not self.test_mismatched_shapes: + self.skipTest(reason="test_missmatched_shapes is set to False") + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + configs_no_init = _config_zero_init(config) + + for model_class in self.all_model_classes: + mappings = [ + MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES, + MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES, + ] + is_classication_model = any(model_class.__name__ in get_values(mapping) for mapping in mappings) + + if not is_classication_model: + continue + + # TODO: ydshieh + is_special_classes = model_class.__name__ in [ + "wav2vec2.masked_spec_embed", + "Wav2Vec2ForSequenceClassification", + "CLIPForImageClassification", + "MetaClip2ForImageClassification", + "Siglip2ForImageClassification", + "RegNetForImageClassification", + "ResNetForImageClassification", + "UniSpeechSatForSequenceClassification", + "Wav2Vec2BertForSequenceClassification", + "PvtV2ForImageClassification", + "Wav2Vec2ConformerForSequenceClassification", + "WavLMForSequenceClassification", + "SwiftFormerForImageClassification", + "SEWForSequenceClassification", + "BitForImageClassification", + "SEWDForSequenceClassification", + "SiglipForImageClassification", + "HubertForSequenceClassification", + "Swinv2ForImageClassification", + "Data2VecAudioForSequenceClassification", + "UniSpeechForSequenceClassification", + "PvtForImageClassification", + "ModernBertForSequenceClassification", + "ModernBertForTokenClassification", + "TimmWrapperForImageClassification", + "ModernBertForQuestionAnswering", + "ModernBertDecoderForSequenceClassification", + "ModernBertDecoderForCausalLM", + ] + special_param_names = [ + r"^bit\.", + r"^classifier\.weight", + r"^classifier\.bias", + r"^classifier\..+\.weight", + r"^classifier\..+\.bias", + r"^data2vec_audio\.", + r"^dist_head\.", + r"^head\.", + r"^hubert\.", + r"^pvt\.", + r"^pvt_v2\.", + r"^regnet\.", + r"^resnet\.", + r"^sew\.", + r"^sew_d\.", + r"^swiftformer\.", + r"^swinv2\.", + r"^transformers\.models\.swiftformer\.", + r"^timm_model\.", + r"^unispeech\.", + r"^unispeech_sat\.", + r"^vision_model\.", + r"^wav2vec2\.", + r"^wav2vec2_bert\.", + r"^wav2vec2_conformer\.", + r"^wavlm\.", + ] + + with self.subTest(msg=f"Testing {model_class}"): + with tempfile.TemporaryDirectory() as tmp_dir: + model = model_class(configs_no_init) + model.save_pretrained(tmp_dir) + + # Fails when we don't set ignore_mismatched_sizes=True + with self.assertRaises(RuntimeError): + new_model = model_class.from_pretrained(tmp_dir, num_labels=42) + + logger = logging.get_logger("transformers.modeling_utils") + + with CaptureLogger(logger) as cl: + new_model = model_class.from_pretrained(tmp_dir, num_labels=42, ignore_mismatched_sizes=True) + self.assertIn("the shapes did not match", cl.out) + + for name, param in new_model.named_parameters(): + if param.requires_grad: + param_mean = ((param.data.mean() * 1e9).round() / 1e9).item() + if not ( + is_special_classes + and any(len(re.findall(target, name)) > 0 for target in special_param_names) + ): + self.assertIn( + param_mean, + [0.0, 1.0], + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + else: + # Here we allow the parameters' mean to be in the range [-5.0, 5.0] instead of being + # either `0.0` or `1.0`, because their initializations are not using + # `config.initializer_factor` (or something similar). The purpose of this test is simply + # to make sure they are properly initialized (to avoid very large value or even `nan`). + self.assertGreaterEqual( + param_mean, + -5.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + self.assertLessEqual( + param_mean, + 5.0, + msg=f"Parameter {name} of model {model_class} seems not properly initialized", + ) + + def test_matched_shapes_have_loaded_weights_when_some_mismatched_shapes_exist(self): + # 1. Create a dummy class. Should have buffers as well? To make sure we test __init__ + class MyClass(PreTrainedModel): + config_class = PretrainedConfig + + def __init__(self, config=None): + super().__init__(config if config is not None else PretrainedConfig()) + self.linear = nn.Linear(10, config.num_labels, bias=True) + self.embedding = nn.Embedding(10, 10) + self.std = 1 + + def _init_weights(self, module): + if isinstance(module, nn.Linear): + module.weight.data = nn.init.kaiming_uniform_(module.weight.data, np.sqrt(5)) + if module.bias is not None: + module.bias.data = module.bias.data.normal_(mean=0.0, std=self.std) + + # Used to make sure the weights with matched shape are loaded correctly + config = PretrainedConfig() + config.num_labels = 3 + model = MyClass(config=config) + + # Used to make sure the weights with mismatched shape are properly initialized + set_seed(0) + config = PretrainedConfig() + config.num_labels = 4 + # not to init. the weights during the creation: to match the logic in `from_pretrained`, so we can keep the + # same sequence of random ops in the execution path to allow us to compare `target_model` and `new_model` below + # for `linear` part. + with ContextManagers([no_init_weights()]): + target_model = MyClass(config=config) + target_model.apply(target_model._initialize_weights) + + with tempfile.TemporaryDirectory() as tmpdirname: + state_dict = model.state_dict() + del state_dict["linear.weight"] + + model.config.save_pretrained(tmpdirname) + torch.save(state_dict, os.path.join(tmpdirname, "pytorch_model.bin")) + + set_seed(0) + new_model = MyClass.from_pretrained(tmpdirname, num_labels=4, ignore_mismatched_sizes=True) + + for key in new_model.state_dict(): + # check weight values for weights with matched shapes are identical + # (i.e. correctly loaded from the checkpoint) + if key not in ["linear.weight", "linear.bias"]: + max_diff = torch.max(torch.abs(model.state_dict()[key] - new_model.state_dict()[key])) + self.assertLessEqual( + max_diff.item(), + 1e-6, + msg=f"the weight values for `{key}` in `new_model` and `model` are not identical", + ) + else: + # check we have some mismatched shapes + self.assertNotEqual( + model.state_dict()[key].shape, + new_model.state_dict()[key].shape, + msg=f"the weight shapes for {key} in `model` and `new_model` should differ", + ) + # check the weights with mismatched shape are properly initialized + max_diff = torch.max(torch.abs(new_model.state_dict()[key] - target_model.state_dict()[key])) + self.assertLessEqual( + max_diff.item(), + 1e-6, + msg=f"the weight values for `{key}` in `new_model` and `target_model` are not identical", + ) + + def test_model_is_small(self): + # Just a consistency check to make sure we are not running tests on 80M parameter models. + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + for model_class in self.all_model_classes: + model = model_class(copy.deepcopy(config)) + num_params = model.num_parameters() + assert num_params < 1000000, ( + f"{model_class} is too big for the common tests ({num_params})! It should have 1M max." + ) + + def flash_attn_inference_equivalence(self, attn_implementation: str, padding_side: str): + r""" + Tests the equivalence between the eager and flash attention implementations. + This test is only for inference and runs with `torch_dtype=torch.bfloat16`. + """ + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + for model_class in self.all_model_classes: + if not model_class._supports_flash_attn: + self.skipTest(f"{model_class.__name__} does not support {attn_implementation}") + # Custom kernel which needs the mask interface to be properly usable on these models + if not model_class._supports_attention_backend and not attn_implementation.startswith("flash_attention"): + self.skipTest(f"{model_class.__name__} does not support {attn_implementation}") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # flash attention variants does not always support arbitrary headim + config = self._prepare_config_headdim(config, 16) + + # TODO it is unclear why saving and reloading with dtype works while + # casting with `.to(dtype=..., device=...)` does not. + # Discovered on tests with `Bart` models. + model = model_class(config) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.bfloat16) + model.to(torch_device) + + dummy_input = inputs_dict[model.main_input_name][:1] + if dummy_input.dtype in [torch.float32, torch.float16]: + dummy_input = dummy_input.to(torch.bfloat16) + + dummy_attention_mask = inputs_dict.get("attention_mask", None) + + if dummy_attention_mask is not None: + dummy_attention_mask = dummy_attention_mask[:1] + if padding_side == "left": + dummy_attention_mask[:, 1:] = 1 + dummy_attention_mask[:, :1] = 0 + else: + dummy_attention_mask[:, :-1] = 1 + dummy_attention_mask[:, -1:] = 0 + if model.config.is_encoder_decoder: + decoder_input_ids = inputs_dict.get("decoder_input_ids", dummy_input)[:1] + + outputs = model(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + model.set_attn_implementation(attn_implementation) + outputs_fa = model(dummy_input, decoder_input_ids=decoder_input_ids, output_hidden_states=True) + else: + outputs = model(dummy_input, output_hidden_states=True) + model.set_attn_implementation(attn_implementation) + outputs_fa = model(dummy_input, output_hidden_states=True) + + model.set_attn_implementation("sdpa") + logits = ( + outputs.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs.decoder_hidden_states[-1] + ) + logits_fa = ( + outputs_fa.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs_fa.decoder_hidden_states[-1] + ) + + assert torch.allclose(logits_fa, logits, atol=4e-2, rtol=4e-2) + + if model.config.is_encoder_decoder: + other_inputs = { + "decoder_input_ids": decoder_input_ids, + "decoder_attention_mask": dummy_attention_mask, + "output_hidden_states": True, + } + if dummy_attention_mask is not None: + other_inputs["attention_mask"] = dummy_attention_mask + + outputs = model(dummy_input, **other_inputs) + model.set_attn_implementation(attn_implementation) + outputs_fa = model(dummy_input, **other_inputs) + else: + other_inputs = { + "output_hidden_states": True, + } + if dummy_attention_mask is not None: + other_inputs["attention_mask"] = dummy_attention_mask + + outputs = model(dummy_input, **other_inputs) + model.set_attn_implementation(attn_implementation) + outputs_fa = model(dummy_input, **other_inputs) + + model.set_attn_implementation("sdpa") + logits = ( + outputs.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs.decoder_hidden_states[-1] + ) + logits_fa = ( + outputs_fa.hidden_states[-1] + if not model.config.is_encoder_decoder + else outputs_fa.decoder_hidden_states[-1] + ) + + if padding_side == "left": + assert torch.allclose(logits_fa[1:], logits[1:], atol=4e-2, rtol=4e-2) + + # check with inference + dropout + model.train() + model.set_attn_implementation(attn_implementation) + _ = model(dummy_input, **other_inputs) + else: + assert torch.allclose(logits_fa[:-1], logits[:-1], atol=4e-2, rtol=4e-2) + + @require_kernels + @require_torch_gpu + @mark.flash_attn_test + @slow + @is_flaky() + def test_flash_attn_kernels_inference_equivalence(self): + self.flash_attn_inference_equivalence(attn_implementation="kernels-community/flash-attn3", padding_side="left") + + @require_torch_mps + @require_kernels + @mark.flash_attn_test + @slow + @is_flaky() + def test_flash_attn_kernels_mps_inference_equivalence(self): + self.flash_attn_inference_equivalence( + attn_implementation="kernels-community/metal-flash-sdpa", padding_side="left" + ) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + @is_flaky() + def test_flash_attn_2_inference_equivalence(self): + self.flash_attn_inference_equivalence(attn_implementation="flash_attention_2", padding_side="left") + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + @is_flaky() + def test_flash_attn_2_inference_equivalence_right_padding(self): + self.flash_attn_inference_equivalence(attn_implementation="flash_attention_2", padding_side="right") + + @require_flash_attn_3 + @require_torch_gpu + @mark.flash_attn_3_test + @slow + @is_flaky() + def test_flash_attn_3_inference_equivalence(self): + self.flash_attn_inference_equivalence(attn_implementation="flash_attention_3", padding_side="left") + + @require_flash_attn_3 + @require_torch_gpu + @mark.flash_attn_3_test + @slow + @is_flaky() + def test_flash_attn_3_inference_equivalence_right_padding(self): + self.flash_attn_inference_equivalence(attn_implementation="flash_attention_3", padding_side="right") + + def test_attn_implementation_composite_models(self): + """ + Tests if composite models can receive a dict object as attn_implementation, where each key should be + one of the sub-configs from the model's config. + """ + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + for model_class in self.all_model_classes: + if not self._is_composite: + self.skipTest("Model is not a composite model.") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + # set eager as it will be the one supported in all models + # we just need to test if passing 'attn_implementation' as a dict fails or not + attn_implementation_per_subconfig = {"": "eager"} + for key in config.sub_configs: + attn_implementation_per_subconfig[key] = "eager" + + config._attn_implementation = attn_implementation_per_subconfig + model = model_class(config) + for key in config.sub_configs: + sub_config = getattr(model.config, key) + self.assertTrue(sub_config._attn_implementation == "eager") + + for name, submodule in model.named_modules(): + class_name = submodule.__class__.__name__ + if ( + class_name.endswith("Attention") + and getattr(submodule, "config", None) + and submodule.config._attn_implementation != "eager" + ): + raise ValueError( + f"The eager model should not have SDPA/FA2 attention layers but got `{class_name}.config._attn_implementation={submodule.config._attn_implementation}`" + ) + + # Set the attention to default `None` but the text config to `eager` + # The model should load encoders in SDPA but not the text attention + config._attn_implementation = None + config.get_text_config(decoder=True)._attn_implementation = "eager" + model = model_class(config) + self.assertTrue(model.config.get_text_config(decoder=True)._attn_implementation == "eager") + + # Test that using `dict` atttention implementation works with `from_pretrained` + # Set all backbones to "eager" because "eager" attention is always available + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + new_model = model.from_pretrained(tmpdirname, attn_implementation=attn_implementation_per_subconfig) + self.assertTrue(new_model.config._attn_implementation == "eager") + for submodule in new_model.modules(): + if ( + submodule is not new_model + and isinstance(submodule, PreTrainedModel) + and submodule.config.__class__ != new_model.config.__class__ + ): + self.assertTrue(submodule.config._attn_implementation == "eager") + + @require_torch_sdpa + def test_sdpa_can_dispatch_non_composite_models(self): + """ + Tests if non-composite models dispatch correctly on SDPA/eager when requested so when loading the model. + This tests only by looking at layer names, as usually SDPA layers are called "SDPAAttention". + """ + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + if not self.all_model_classes[0]._supports_sdpa or self._is_composite: + self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA") + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_sdpa = model_class.from_pretrained(tmpdirname) + model_sdpa = model_sdpa.eval().to(torch_device) + + self.assertTrue(model_sdpa.config._attn_implementation == "sdpa") + + model_eager = model_class.from_pretrained(tmpdirname, attn_implementation="eager") + model_eager = model_eager.eval().to(torch_device) + self.assertTrue(model_eager.config._attn_implementation == "eager") + + for name, submodule in model_eager.named_modules(): + class_name = submodule.__class__.__name__ + if ( + class_name.endswith("Attention") + and getattr(submodule, "config", None) + and submodule.config._attn_implementation == "sdpa" + ): + raise ValueError( + f"The eager model should not have SDPA attention layers but got `{class_name}.config._attn_implementation={submodule.config._attn_implementation}`" + ) + + @require_torch_sdpa + def test_sdpa_can_dispatch_composite_models(self): + """ + Tests if composite models dispatch correctly on SDPA/eager when requested so when loading the model. + This tests only by looking at layer names, as usually SDPA layers are called "SDPAAttention". + In contrast to the above test, this one checks if the "config._attn_implamentation" is a dict after the model + is loaded, because we manually replicate requested attn implementation on each sub-config when loading. + See https://github.com/huggingface/transformers/pull/32238 for more info + + The test tries to cover most general cases of composite models, VLMs with vision and text configs. Any model + that has a different set of sub-configs has to overwrite this test. + """ + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + if not self._is_composite: + self.skipTest(f"{self.all_model_classes[0].__name__} does not support SDPA") + + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model_sdpa = model_class.from_pretrained(tmpdirname) + model_sdpa = model_sdpa.eval().to(torch_device) + + vision_model_names = {"visual", "image_tower", "vision_tower", "vision_model"} + language_model_names = {"language_model", "model", "text_model"} + vision_model_name = [name for name in vision_model_names if hasattr(model_sdpa, name)][0] + language_model_name = [name for name in language_model_names if hasattr(model_sdpa, name)][0] + + vision_model_sdpa = getattr(model_sdpa, vision_model_name) + language_model_sdpa = getattr(model_sdpa, language_model_name) + text_attn = "sdpa" if language_model_sdpa._supports_sdpa else "eager" + vision_attn = "sdpa" if vision_model_sdpa._supports_sdpa else "eager" + + # `None` as it is the requested one which will be assigned to each sub-config + # Sub-model will dispatch to SDPA if it can (checked below that `SDPA` layers are present) + self.assertTrue(language_model_sdpa.config._attn_implementation == text_attn) + self.assertTrue(vision_model_sdpa.config._attn_implementation == vision_attn) + + model_eager = model_class.from_pretrained(tmpdirname, attn_implementation="eager") + model_eager = model_eager.eval().to(torch_device) + self.assertTrue(getattr(model_eager, language_model_name).config._attn_implementation == "eager") + self.assertTrue(getattr(model_eager, vision_model_name).config._attn_implementation == "eager") + + for name, submodule in model_eager.named_modules(): + class_name = submodule.__class__.__name__ + if ( + class_name.endswith("Attention") + and getattr(submodule, "config", None) + and submodule.config._attn_implementation == "sdpa" + ): + raise ValueError("The eager model should not have SDPA attention layers") + + @parameterized.expand(TEST_EAGER_MATCHES_SDPA_INFERENCE_PARAMETERIZATION) + @require_torch_sdpa + def test_eager_matches_sdpa_inference( + self, name, torch_dtype, padding_side, use_attention_mask, output_attentions, enable_kernels + ): + _test_eager_matches_sdpa_inference( + self, name, torch_dtype, padding_side, use_attention_mask, output_attentions, enable_kernels + ) + + @require_torch_sdpa + @require_torch_accelerator + @slow + def test_sdpa_can_dispatch_on_flash(self): + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + device_type, major, minor = get_device_properties() + if device_type == "cuda" and major < 8: + self.skipTest(reason="This test requires an NVIDIA GPU with compute capability >= 8.0") + elif device_type == "rocm" and major < 9: + self.skipTest(reason="This test requires an AMD GPU with compute capability >= 9.0") + elif device_type not in ["cuda", "rocm", "xpu"]: + self.skipTest(reason="This test requires a Nvidia or AMD GPU, or an Intel XPU") + + torch.compiler.reset() + + for model_class in self.all_model_classes: + if not model_class._supports_sdpa: + self.skipTest(f"{model_class.__name__} does not support SDPA") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + inputs_dict = self._prepare_for_class(inputs_dict, model_class) + if config.model_type in ["paligemma"]: + self.skipTest( + "PaliGemma-like models currently (transformers==4.41.0) requires an attention_mask input" + ) + if config.model_type in [ + "modernbert", + "gemma3", + "t5gemma", + "diffllama", + "dpr", + "eomt", + "gpt_bigcode", + "jamba", + "kosmos-2", + "mllama", + "pixtral", + "sam", + "sam_hq", + "zamba2", + "sam_vision_model", + "sam2_vision_model", + "sam_hq_vision_model", + ]: + self.skipTest( + reason=f"{config.model_type} currently (transformers==4.52.0) automatically adds an attention_mask input" + ) + if config.model_type in ["idefics", "idefics2", "idefics3"]: + self.skipTest(reason="Idefics currently (transformers==4.39.1) requires an image_attention_mask input") + if config.model_type in ["sam"]: + self.skipTest(reason="SAM requires an attention_mask input for relative positional embeddings") + + model = model_class(config) + + sub_models_supporting_sdpa = [ + module._supports_sdpa + for name, module in model.named_modules() + if isinstance(module, PreTrainedModel) and name != "" + ] + supports_sdpa_all_modules = ( + all(sub_models_supporting_sdpa) if len(sub_models_supporting_sdpa) > 0 else model._supports_sdpa + ) + if not supports_sdpa_all_modules: + self.skipTest(reason="This models' submodels does not support sdpa") + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16, attn_implementation="sdpa") + model.to(torch_device) + + inputs_dict.pop("attention_mask", None) + inputs_dict.pop("decoder_attention_mask", None) + + for name, inp in inputs_dict.items(): + if isinstance(inp, torch.Tensor) and inp.dtype in [torch.float32, torch.float16]: + inputs_dict[name] = inp.to(torch.float16) + + with sdpa_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False): + _ = model(**inputs_dict) + + @require_torch_sdpa + @require_torch_accelerator + @pytest.mark.torch_compile_test + @slow + def test_sdpa_can_compile_dynamic(self): + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + device_type, major, minor = get_device_properties() + if device_type == "cuda" and major < 8: + self.skipTest(reason="This test requires an NVIDIA GPU with compute capability >= 8.0") + elif device_type == "rocm" and major < 9: + self.skipTest(reason="This test requires an AMD GPU with compute capability >= 9.0") + elif device_type not in ["cuda", "rocm", "xpu"]: + self.skipTest(reason="This test requires a Nvidia or AMD GPU, or an Intel XPU") + + torch.compiler.reset() + + for model_class in self.all_model_classes: + if not model_class._supports_sdpa: + self.skipTest(f"{model_class.__name__} does not support SDPA") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + inputs_dict = self._prepare_for_class(inputs_dict, model_class) + if config.model_type in ["dbrx"]: + self.skipTest( + "DBRX (transformers==4.40) requires a modification to support dynamic shapes with compile." + ) + if getattr(config, "cache_implementation", None) == "hybrid": + self.skipTest( + "Cannot compile forward without an existing cache with Hybrid, as `torch._dynamo.mark_static_address` " + "is a forbidden call." + ) + + model = model_class(config) + + sub_models_supporting_sdpa = [ + module._supports_sdpa + for name, module in model.named_modules() + if isinstance(module, PreTrainedModel) and name != "" + ] + supports_sdpa_all_modules = ( + all(sub_models_supporting_sdpa) if len(sub_models_supporting_sdpa) > 0 else model._supports_sdpa + ) + if not supports_sdpa_all_modules: + self.skipTest(reason="This models' submodels does not support sdpa") + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch.float16, attn_implementation="sdpa") + model.to(torch_device) + + # For PyTorch 2.1 - 2.3.0 set `dynamic=True`. In the future setting `dynamic=None` and using `torch._dynamo.mark_dynamic()` + # on input tensors will be required. `mark_dynamic` currently raises inconsistent shape errors. + model = torch.compile(model, dynamic=True) + + inputs_dict.pop("attention_mask", None) + inputs_dict.pop("decoder_attention_mask", None) + for name, inp in inputs_dict.items(): + if isinstance(inp, torch.Tensor) and inp.dtype in [torch.float32, torch.float16]: + inputs_dict[name] = inp.to(torch.float16) + + # use no_grad to save some memory + with torch.no_grad(): + _ = model(**inputs_dict) + + @require_torch_sdpa + def test_sdpa_matches_eager_sliding_window(self): + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + WINDOW_ATTENTION_MODELS = ["mistral", "mixtral", "minimax", "qwen2", "qwen_moe", "starcoder2"] + + if len(self.all_generative_model_classes) == 0: + self.skipTest(f"No generative model classes for {self.__class__.__name__}") + + for model_class in self.all_generative_model_classes: + if model_class._supports_sdpa: + self.skipTest(reason="Model architecture does not support attentions") + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + + if config.model_type not in WINDOW_ATTENTION_MODELS: + self.skipTest(f"{config.model_type} does not use window attention") + + config.sliding_window = 2 + + dummy_input = inputs_dict[model_class.main_input_name] + attention_mask = inputs_dict["attention_mask"] + + self.assertTrue(dummy_input.ndim == 2) + self.assertTrue(dummy_input.shape[1] > 6) + + with tempfile.TemporaryDirectory() as tmpdir: + with torch.device(torch_device): + model_eager = AutoModelForCausalLM.from_config( + config, attn_implementation="eager", torch_dtype=torch.float32 + ) + + model_eager.save_pretrained(tmpdir) + + with torch.device(torch_device): + model_sdpa = AutoModelForCausalLM.from_pretrained( + tmpdir, attn_implementation="sdpa", torch_dtype=torch.float32 + ) + + model_eager = model_eager.eval() + model_sdpa = model_sdpa.eval() + + with torch.no_grad(): + with sdpa_kernel(enable_flash=False, enable_math=True, enable_mem_efficient=False): + res_eager = model_eager(**inputs_dict, return_dict=False)[0] + res_sdpa = model_sdpa(**inputs_dict, return_dict=False)[0] + + # Only non-padding tokens are expected to match. + self.assertTrue( + torch.allclose(res_eager[attention_mask == 1], res_sdpa[attention_mask == 1], rtol=1e-4, atol=1e-4) + ) + + def flash_attn_can_dispatch_composite_models(self, attn_implementation: str): + """ + Tests if composite models can dispatch on flash attention if the sub-models support it. + The tests is needed as we handle differently composite models and we cannot check them + with above tests. If any of the sub-models does not support flash attention, we'll raise an error when dispatching + that particular sub-model. Otherwise we dispatch safely in all sub-models, where "sub-models" are specific + backbone models (LM/vision/audio/etc) + """ + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + if not is_torch_bf16_available_on_device(torch_device): + self.skipTest(f"bfloat16 not supported on {torch_device} (on the specific device currently used)") + + torch_dtype = torch.bfloat16 + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + if not self._is_composite: + self.skipTest("This model is not a composite model!") + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = model_class.from_pretrained(tmpdirname, torch_dtype=torch_dtype) + + sub_models_supporting_fa = [ + module._supports_flash_attn + for name, module in model.named_modules() + if isinstance(module, PreTrainedModel) and name != "" + ] + supports_fa_all_modules = ( + all(sub_models_supporting_fa) if len(sub_models_supporting_fa) > 0 else model._supports_flash_attn + ) + if not supports_fa_all_modules: + with self.assertRaises(ValueError): + model_fa = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch_dtype, + attn_implementation=attn_implementation, + ) + else: + model_fa = model_class.from_pretrained( + tmpdirname, torch_dtype=torch_dtype, attn_implementation=attn_implementation + ) + for key in model_fa.config: + if isinstance(getattr(model_fa.config, key), PretrainedConfig): + sub_config = getattr(model_fa.config, key) + self.assertTrue(sub_config._attn_implementation == attn_implementation) + + has_fa = False + for name, submodule in model_fa.named_modules(): + class_name = submodule.__class__.__name__ + if ( + "Attention" in class_name + and getattr(submodule, "config", None) + and submodule.config._attn_implementation == attn_implementation + ): + has_fa = True + break + if not has_fa: + raise ValueError(f"The {attn_implementation} model should have {attn_implementation} layers") + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + def test_flash_attn_2_can_dispatch_composite_models(self): + self.flash_attn_can_dispatch_composite_models(attn_implementation="flash_attention_2") + + @require_flash_attn_3 + @require_torch_gpu + @mark.flash_attn_3_test + def test_flash_attn_3_can_dispatch_composite_models(self): + self.flash_attn_can_dispatch_composite_models(attn_implementation="flash_attention_3") + + @require_flash_attn + @require_torch_gpu + @require_bitsandbytes + @mark.flash_attn_test + @slow + def test_flash_attn_2_fp32_ln(self): + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + for model_class in self.all_generative_model_classes: + if not model_class._supports_flash_attn: + self.skipTest(f"{model_class.__name__} does not support Flash Attention 2") + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + model = model_class(config) + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + dummy_input = inputs_dict[model.main_input_name] + dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input)) + batch_size = dummy_attention_mask.shape[0] + + is_padding_right = dummy_attention_mask[:, -1].sum().item() != batch_size + + # To avoid errors with padding_side=="right" + if is_padding_right: + dummy_attention_mask = torch.ones_like(dummy_input) + + model = model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.float16, + attn_implementation="flash_attention_2", + load_in_4bit=True, + ) + + for _, param in model.named_parameters(): + # upcast only layer norms + if (param.dtype == torch.float16) or (param.dtype == torch.bfloat16): + param.data = param.data.to(torch.float32) + + if model.config.is_encoder_decoder: + dummy_decoder_input_ids = inputs_dict["decoder_input_ids"] + dummy_decoder_attention_mask = inputs_dict["decoder_attention_mask"] + + _ = model(dummy_input, decoder_input_ids=dummy_decoder_input_ids) + # with attention mask + _ = model( + dummy_input, + attention_mask=dummy_attention_mask, + decoder_input_ids=dummy_decoder_input_ids, + decoder_attention_mask=dummy_decoder_attention_mask, + ) + else: + _ = model(dummy_input) + # with attention mask + _ = model(dummy_input, attention_mask=dummy_attention_mask) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @pytest.mark.torch_compile_test + @slow + def test_flash_attn_2_can_compile_with_attention_mask_None_without_graph_break(self): + if version.parse(torch.__version__) < version.parse("2.3"): + self.skipTest(reason="This test requires torch >= 2.3 to run.") + + if not hasattr(self, "_torch_compile_train_cls"): + self.skipTest(f"{self.__class__.__name__} doesn't have the attribute `_torch_compile_train_cls`.") + + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + if not is_torch_fp16_available_on_device(torch_device): + self.skipTest(f"float16 not supported on {torch_device} (on the specific device currently used)") + + torch.compiler.reset() + torch_dtype = torch.float16 + + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + cls = self._torch_compile_train_cls # e.g. LlamaFroCausalLM + model = cls._from_config(config, attn_implementation="flash_attention_2").to( + device=torch_device, dtype=torch_dtype + ) + + inputs = { + "input_ids": torch.randint(low=1, high=model.config.vocab_size, size=(2, 10), device=torch_device), + "labels": torch.randint(low=1, high=model.config.vocab_size, size=(2, 10), device=torch_device), + } + + model = torch.compile(model, fullgraph=True) + # forward compilation + set_seed(42) + loss = model(**inputs).loss + # backward compilation + loss.backward() + + assert not loss.isnan().any() + + def attention_mask_padding_matches_padding_free_with_position_ids( + self, attn_implementation: str, fa_kwargs: bool = False + ): + """ + Tests that the given attention implementation can work with packed sequences and infers the mask + from position ids. This test requires the model to use new attention mask API which handles packing. + """ + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + max_new_tokens = 30 + support_flag = { + "sdpa": "_supports_sdpa", + "flash_attention_2": "_supports_flash_attn", + "flash_attention_3": "_supports_flash_attn", + } + + for model_class in self.all_generative_model_classes: + if attn_implementation != "eager" and not getattr(model_class, support_flag[attn_implementation]): + self.skipTest(f"{model_class.__name__} does not support {attn_implementation}") + + # can't infer if new attn mask API is supported by assume that only model with attention backend support it + if not model_class._supports_attention_backend: + self.skipTest(f"{model_class.__name__} does not support new attention mask API") + + if model_class._is_stateful: # non-transformer models most probably have no packing support + self.skipTest(f"{model_class.__name__} doesn't support packing!") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if config.is_encoder_decoder: + self.skipTest("Model is an encoder-decoder") + + if 0 not in inputs_dict.get("attention_mask", []) or "attention_mask" not in inputs_dict: + self.skipTest("Model dummy inputs should contain padding in their attention mask") + + if "input_ids" not in inputs_dict or inputs_dict["input_ids"].ndim != 2: + self.skipTest("Model dummy inputs should contain text input ids") + + # make sure that all models have enough positions for generation + dummy_input_ids = inputs_dict["input_ids"] + if hasattr(config, "max_position_embeddings"): + config.max_position_embeddings = max_new_tokens + dummy_input_ids.shape[1] + 1 + + model = model_class(config) + if "position_ids" not in inspect.signature(model.forward).parameters: + self.skipTest("Model does not support position_ids") + + if (not fa_kwargs) and "position_ids" not in inspect.signature(model.forward).parameters: + continue # this model doesn't accept position ids as input + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + # Drop all keys except for the minimal set. Hard to manipulate with multimodals/head_mask/etc + inputs_dict = {k: v for k, v in inputs_dict.items() if k in ["input_ids", "attention_mask"]} + + # Ensure left padding, to adapt for some models + if 0 in inputs_dict["attention_mask"][:, -1]: + inputs_dict["attention_mask"] = inputs_dict["attention_mask"].flip(1) + dummy_attention_mask = inputs_dict["attention_mask"] + dummy_input_ids[~dummy_attention_mask.bool()] = config.get_text_config().pad_token_id + + model = ( + model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.bfloat16, + attn_implementation=attn_implementation, + ) + .to(torch_device) + .eval() + ) + + if fa_kwargs: + # flatten + features = [ + {"input_ids": i[a.bool()].tolist()} for i, a in zip(dummy_input_ids, dummy_attention_mask) + ] + + # add position_ids + fa_kwargs + data_collator = DataCollatorWithFlattening(return_tensors="pt", return_flash_attn_kwargs=True) + batch = data_collator(features) + padfree_inputs_dict = { + k: t.to(torch_device) if torch.is_tensor(t) else t for k, t in batch.items() + } + else: + # create packed position_ids + position_ids = ( + torch.cat([torch.arange(length) for length in dummy_attention_mask.sum(1).tolist()]) + .long() + .unsqueeze(0) + .to(torch_device) + ) + padfree_inputs_dict = { + "input_ids": dummy_input_ids[dummy_attention_mask.bool()].unsqueeze(0), + "position_ids": position_ids, + } + + # We need to do simple forward without cache in order to trigger packed SDPA/flex/eager attention path + res_padded = model(**inputs_dict, use_cache=False) + res_padfree = model(**padfree_inputs_dict, use_cache=False) + + logits_padded = res_padded.logits[dummy_attention_mask.bool()] + logits_padfree = res_padfree.logits[0] + + # acceptable numerical instability + tol = torch.finfo(torch.bfloat16).eps + torch.testing.assert_close(logits_padded, logits_padfree, rtol=tol, atol=tol) + + def test_eager_padding_matches_padding_free_with_position_ids(self): + self.attention_mask_padding_matches_padding_free_with_position_ids(attn_implementation="eager") + + def test_sdpa_padding_matches_padding_free_with_position_ids(self): + self.attention_mask_padding_matches_padding_free_with_position_ids(attn_implementation="sdpa") + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attention_2_padding_matches_padding_free_with_position_ids(self): + self.attention_mask_padding_matches_padding_free_with_position_ids(attn_implementation="flash_attention_2") + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attention_2_padding_matches_padding_free_with_position_ids_and_fa_kwargs(self): + self.attention_mask_padding_matches_padding_free_with_position_ids( + attn_implementation="flash_attention_2", fa_kwargs=True + ) + + @require_flash_attn_3 + @require_torch_gpu + @mark.flash_attn_3_test + @slow + def test_flash_attention_3_padding_matches_padding_free_with_position_ids(self): + self.attention_mask_padding_matches_padding_free_with_position_ids(attn_implementation="flash_attention_3") + + @require_flash_attn_3 + @require_torch_gpu + @mark.flash_attn_3_test + @slow + def test_flash_attention_3_padding_matches_padding_free_with_position_ids_and_fa_kwargs(self): + self.attention_mask_padding_matches_padding_free_with_position_ids( + attn_implementation="flash_attention_3", fa_kwargs=True + ) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + def test_flash_attention_2_continue_generate_with_position_ids(self): + """ + Tests that the given attention implementation can work with packed sequences and infers the mask + from position ids. This test requires the model to use new attention mask API which handles packing. + """ + + max_new_tokens = 2 + for model_class in self.all_generative_model_classes: + if not model_class._supports_flash_attn: + self.skipTest(f"{model_class.__name__} does not support Flash Attention.") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + if config.is_encoder_decoder: + self.skipTest("Model is an encoder-decoder") + + if not hasattr(config.get_text_config(), "use_cache"): + self.skipTest(f"{model_class.__name__} doesn't support caching") + + if "input_ids" not in inputs_dict or inputs_dict["input_ids"].ndim != 2: + self.skipTest("Model dummy inputs should contain text input ids") + + # make sure that all models have enough positions for generation + dummy_input_ids = inputs_dict["input_ids"] + if hasattr(config, "max_position_embeddings"): + config.max_position_embeddings = max_new_tokens + dummy_input_ids.shape[1] + 1 + + model = model_class(config) + if "position_ids" not in inspect.signature(model.forward).parameters: + self.skipTest("Model does not support position_ids") + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = ( + model_class.from_pretrained( + tmpdirname, + torch_dtype=torch.bfloat16, + attn_implementation="flash_attention_2", + ) + .to(torch_device) + .eval() + ) + + # Drop all keys except for `input_ids`. Hard to manipulate with multimodals/head_mask/etc + dummy_input_ids = inputs_dict["input_ids"] + dummy_position_ids = torch.arange(dummy_input_ids.shape[1], device=torch_device) + dummy_position_ids = dummy_position_ids.unsqueeze(0).repeat(dummy_input_ids.shape[0], 1) + + # Store cache for the input prompt + output = model(dummy_input_ids, position_ids=dummy_position_ids, use_cache=True) + if "past_key_values" not in output: + self.skipTest("This model doesn't return `past_key_values`") + + # create new input_ids and position_ids to continue generation re-using the cache + new_input_ids = output.logits[:, -1, :].float().argmax(-1)[:, None] + past_length = dummy_input_ids.shape[1] + position_ids = torch.arange(past_length, past_length + new_input_ids.shape[1], device=torch_device) + position_ids = position_ids.unsqueeze(0).repeat(new_input_ids.shape[0], 1) + + output = model( + input_ids=new_input_ids, + past_key_values=output.past_key_values, + position_ids=position_ids, + use_cache=True, + ) + next_token_logits = output.logits[:, -1, :].float() + + generate_kwargs = { + "pad_token_id": -1, + "eos_token_id": -1, + "forced_eos_token_id": None, + "use_cache": True, + "do_sample": False, + "return_dict_in_generate": True, + "output_logits": True, + "max_new_tokens": max_new_tokens, + } + generation_out = model.generate(dummy_input_ids, **generate_kwargs) + next_token_logits_from_generate = generation_out.logits[-1] + + # acceptable numerical instability + # print(next_token_logits_from_generate, next_token_logits) + tol = torch.finfo(torch.bfloat16).eps + torch.testing.assert_close(next_token_logits_from_generate, next_token_logits, rtol=tol, atol=tol) + + def flash_attn_from_config(self, attn_implementation: str): + r""" + Tests if the model can be loaded with `attn_implementation` from the config and if the + weights are not randomly initialized. + """ + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + for model_class in self.all_generative_model_classes: + if not model_class._supports_flash_attn: + self.skipTest(f"{model_class.__name__} does not support {attn_implementation}") + + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + # TODO: to change it in the future with other relevant auto classes + fa_model = model_class._from_config( + config, attn_implementation=attn_implementation, torch_dtype=torch.bfloat16 + ).to(torch_device) + + dummy_input = inputs_dict[fa_model.main_input_name] + if dummy_input.dtype in [torch.float32, torch.float16]: + dummy_input = dummy_input.to(torch.bfloat16) + dummy_attention_mask = inputs_dict.get("attention_mask", torch.ones_like(dummy_input)) + + if fa_model.config.is_encoder_decoder: + dummy_decoder_input_ids = inputs_dict["decoder_input_ids"] + dummy_decoder_attention_mask = inputs_dict["decoder_attention_mask"] + _ = fa_model( + dummy_input, + attention_mask=dummy_attention_mask, + decoder_input_ids=dummy_decoder_input_ids, + decoder_attention_mask=dummy_decoder_attention_mask, + ) + else: + _ = fa_model(dummy_input, attention_mask=dummy_attention_mask) + + with tempfile.TemporaryDirectory() as tmpdirname: + fa_model.save_pretrained(tmpdirname) + model_from_pretrained = model_class.from_pretrained(tmpdirname) + self.assertTrue(model_from_pretrained.config._attn_implementation != attn_implementation) + + @require_flash_attn + @require_torch_gpu + @mark.flash_attn_test + @slow + def test_flash_attn_2_from_config(self): + self.flash_attn_from_config(attn_implementation="flash_attention_2") + + @require_flash_attn_3 + @require_torch_gpu + @mark.flash_attn_3_test + @slow + def test_flash_attn_3_from_config(self): + self.flash_attn_from_config(attn_implementation="flash_attention_3") + + def _get_custom_4d_mask_test_data(self): + # Sequence in which all but the last token is the same + input_ids = torch.tensor( + [[10, 11, 12, 13], [10, 11, 12, 14], [10, 11, 12, 15]], device=torch_device, dtype=torch.int64 + ) + position_ids = torch.tensor([[0, 1, 2, 3]] * 3, device=torch_device, dtype=torch.int64) + + # Combining common prefix with the unique ending tokens: + input_ids_shared_prefix = torch.cat([input_ids[0][:-1], input_ids[:, -1]]).unsqueeze(0) + + # Creating a 4D mask where each of the last 3 tokens do not attend to each other. + mask_shared_prefix = torch.tensor( + [ + [ + [ + [1, 0, 0, 0, 0, 0], + [1, 1, 0, 0, 0, 0], + [1, 1, 1, 0, 0, 0], + [1, 1, 1, 1, 0, 0], + [1, 1, 1, 0, 1, 0], + [1, 1, 1, 0, 0, 1], + ] + ] + ], + ) + # inverting the attention mask + mask_dtype = torch.float32 + min_dtype = torch.finfo(mask_dtype).min + mask_shared_prefix = (mask_shared_prefix.eq(0.0)).to(dtype=mask_dtype, device=torch_device) * min_dtype + + # Creating a position_ids tensor. note the repeating figures in the end. + position_ids_shared_prefix = torch.tensor([[0, 1, 2, 3, 3, 3]], device=torch_device, dtype=torch.int64) + + return input_ids, position_ids, input_ids_shared_prefix, mask_shared_prefix, position_ids_shared_prefix + + def test_sliding_window_mask(self): + """Tests that we can control the sliding window attention behavior of a model.""" + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + + if not self.has_attentions: + self.skipTest(reason="Model does not support output_attentions") + + if not (hasattr(config, "sliding_window") and hasattr(config, "use_sliding_window")): + self.skipTest(reason="Model does not support sliding window mask") + + seq_len = self.model_tester.seq_length + batch_size = self.model_tester.batch_size + sliding_window = 3 # set to arbitrary small number + + sliding_mask = torch.zeros((seq_len, seq_len), dtype=torch.bool) + for i in range(seq_len): + start = max(0, i - sliding_window + 1) + sliding_mask[i, start : i + 1] = True + sliding_mask = sliding_mask.to(torch_device) + + config.sliding_window = sliding_window + inputs["attention_mask"] = torch.ones(batch_size, seq_len).to(torch.int64).to(torch_device) + for model_class in self.all_model_classes: + # Set sliding window to `True` and check that all tokens beyond window size are masked + config.use_sliding_window = True + config_dict = config.to_diff_dict() + if hasattr(config, "layer_types"): + del config_dict["layer_types"] + new_config = config.__class__(**config_dict) + # We need to set eager as otherwise `output_attentions` is not supported + model = model_class._from_config(new_config, attn_implementation="eager").to(torch_device) + model.eval() + layer_types = getattr(model.config, "layer_types", ["sliding_attention"] * config.num_hidden_layers) + attentions = model(**inputs, output_attentions=True).attentions + for layer_attention, layer_type in zip(attentions, layer_types): + if layer_type == "sliding_attention": + self.assertTrue((layer_attention[:, :, ~sliding_mask] == 0).all().item()) + else: + self.assertFalse((layer_attention[:, :, ~sliding_mask] == 0).all().item()) + + # Set sliding window to `False` while keeping `sliding_window=3` + # Check that all tokens beyond window size are not masked + config.use_sliding_window = False + config_dict = config.to_diff_dict() + if hasattr(config, "layer_types"): + del config_dict["layer_types"] + new_config = config.__class__(**config_dict) + # We need to set eager as otherwise `output_attentions` is not supported + model = model_class._from_config(new_config, attn_implementation="eager").to(torch_device) + model.eval() + attentions_not_sliding = model(**inputs, output_attentions=True).attentions + for layer_attention in attentions_not_sliding: + self.assertFalse((layer_attention[:, :, ~sliding_mask] == 0).all().item()) + + def test_custom_4d_attention_mask(self): + if not self.has_attentions: + self.skipTest(reason="Model architecture does not support attentions") + + if len(self.all_generative_model_classes) == 0: + self.skipTest( + reason="Model architecture has no generative classes, and thus not necessarily supporting 4D masks" + ) + + set_model_tester_for_less_flaky_test(self) + + for model_class in self.all_generative_model_classes: + if not model_class._can_compile_fullgraph: + self.skipTest(f"{model_class.__name__} is not guaranteed to work with custom 4D attention masks") + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + set_config_for_less_flaky_test(config) + if getattr(config, "sliding_window", 0) is not None and getattr(config, "sliding_window", 0) > 0: + self.skipTest(f"{model_class.__name__} with sliding window attention is not supported by this test") + model = model_class(config).to(device=torch_device, dtype=torch.float32).eval() + set_model_for_less_flaky_test(model) + if "position_ids" not in inspect.signature(model.forward).parameters: + continue # model doesn't accept position ids and probably has special way to model positions + + if "position_ids" not in inspect.signature(model.forward).parameters: + continue # this model doesn't accept position ids as input + + ( + input_ids, + position_ids, + input_ids_shared_prefix, + mask_shared_prefix, + position_ids_shared_prefix, + ) = self._get_custom_4d_mask_test_data() + + logits = model.forward(input_ids, position_ids=position_ids).logits + # logits.shape == torch.Size([3, 4, ...]) + + logits_shared_prefix = model( + input_ids_shared_prefix, + attention_mask=mask_shared_prefix, + position_ids=position_ids_shared_prefix, + )[0] + # logits_shared_prefix.shape == torch.Size([1, 6, ...]) + + out_last_tokens = logits[:, -1, :] # last tokens in each batch line + out_shared_prefix_last_tokens = logits_shared_prefix[0, -3:, :] # last three tokens + + # comparing softmax-normalized logits: + normalized_0 = F.softmax(out_last_tokens, dim=-1) + normalized_1 = F.softmax(out_shared_prefix_last_tokens, dim=-1) + torch.testing.assert_close(normalized_0, normalized_1, rtol=1e-3, atol=1e-3) + + @slow + @require_torch_accelerator + @pytest.mark.torch_compile_test + def test_torch_compile_for_training(self): + if version.parse(torch.__version__) < version.parse("2.3"): + self.skipTest(reason="This test requires torch >= 2.3 to run.") + + if getattr(self, "_torch_compile_train_cls", None) is None: + self.skipTest(f"{self.__class__.__name__} doesn't have the attribute `_torch_compile_train_cls`.") + + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + cls = self._torch_compile_train_cls + attn_implementation = getattr(self, "_torch_compile_train_attn_implementation", None) + if attn_implementation is not None: + config._attn_implementation = attn_implementation + + model = cls(config).to(torch_device) + + inputs = { + "input_ids": torch.randint(low=1, high=model.config.vocab_size, size=(2, 10), device=torch_device), + "attention_mask": torch.tensor( + [[1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], + dtype=torch.int64, + device=torch_device, + ), + "position_ids": torch.arange(0, 10, device=torch_device).unsqueeze(0), + "labels": torch.randint(low=1, high=model.config.vocab_size, size=(2, 10), device=torch_device), + "use_cache": False, + } + + # eager backward + set_seed(42) + loss = model(**inputs).loss + loss.backward() + + params = {name: param.grad.detach().to(device="cpu", copy=True) for name, param in model.named_parameters()} + model.zero_grad() + del loss + + model = torch.compile(model, fullgraph=True, mode="reduce-overhead") + + # forward compilation + set_seed(42) + loss = model(**inputs).loss + # backward compilation + loss.backward() + # check grad matches + for name, param in model._orig_mod.named_parameters(): + torch.testing.assert_close(param.grad.detach().cpu(), params[name], rtol=1e-4, atol=1e-4) + + def test_forward_with_logits_to_keep(self): + for model_class in self.all_generative_model_classes: + if "logits_to_keep" not in set(inspect.signature(model_class.forward).parameters.keys()): + self.skipTest(reason="This model does not support `logits_to_keep` argument.") + + config, inputs = self.model_tester.prepare_config_and_inputs_for_common() + batch_size, sequence_length = inputs["input_ids"].shape[:2] + vocab_size = config.get_text_config().vocab_size + model = model_class(config).to(device=torch_device).eval() + # some models have labels but `logits_to_keep` should not be used in train mode + _ = inputs.pop("labels", None) + + # logits_to_keep=0 is a special case meaning "keep all logits" + all_logits = model(**inputs, logits_to_keep=0).logits + last_token_logits = model(**inputs, logits_to_keep=1).logits + + # Assert all shapes are correct + self.assertEqual(tuple(all_logits.shape), (batch_size, sequence_length, vocab_size)) + self.assertEqual(tuple(last_token_logits.shape), (batch_size, 1, vocab_size)) + + # Assert the last tokens are actually the same (except for the natural fluctuation due to order of FP ops) + torch.testing.assert_close(all_logits[:, -1:, :], last_token_logits, rtol=1e-5, atol=1e-5) + + @slow + @require_torch_greater_or_equal("2.5") + @pytest.mark.torch_export_test + def test_torch_export(self, config=None, inputs_dict=None, tolerance=1e-4): + """ + Test if model can be exported with torch.export.export() + + Args: + config (PretrainedConfig): + Config to use for the model, if None, use default config from model_tester + inputs_dict (dict): + Inputs to use for the model, if None, use default inputs from model_tester + tolerance (float): + `atol` for torch.allclose(), defined in signature for test overriding + """ + if not self.test_torch_exportable: + self.skipTest(reason="test_torch_exportable=False for this model.") + + def recursively_check(eager_outputs, exported_outputs): + is_tested = False + if isinstance(eager_outputs, torch.Tensor): + torch.testing.assert_close(eager_outputs, exported_outputs, atol=tolerance, rtol=tolerance) + return True + elif isinstance(eager_outputs, (tuple, list)): + for eager_output, exported_output in zip(eager_outputs, exported_outputs): + is_tested = is_tested or recursively_check(eager_output, exported_output) + return is_tested + elif isinstance(eager_outputs, dict): + for key in eager_outputs: + is_tested = is_tested or recursively_check(eager_outputs[key], exported_outputs[key]) + return is_tested + return is_tested + + default_config, default_inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + config = config or default_config + inputs_dict = inputs_dict or default_inputs_dict + + for model_class in self.all_model_classes: + if model_class.__name__.endswith("ForPreTraining"): + continue + + with self.subTest(model_class.__name__): + model = model_class(config).eval().to(torch_device) + + # Export model + exported_model = torch.export.export( + model, args=(), kwargs=inputs_dict, strict=getattr(self, "test_torch_exportable_strictly", True) + ) + + # Run exported model and eager model + with torch.no_grad(): + # set seed in case anything is not deterministic in model (e.g. vit_mae noise) + torch.manual_seed(1234) + eager_outputs = model(**inputs_dict) + torch.manual_seed(1234) + exported_outputs = exported_model.module().forward(**inputs_dict) + + # Check if outputs are close: + # is_tested is a boolean flag indicating if we compare any outputs, + # e.g. there might be a situation when outputs are empty list, then is_tested will be False. + # In case of outputs are different the error will be raised in `recursively_check` function. + is_tested = recursively_check(eager_outputs, exported_outputs) + self.assertTrue(is_tested, msg=f"No outputs were compared for {model_class.__name__}") + + @staticmethod + def _prepare_config_headdim(config, requested_dim): + """ + This method allows to update the head dim for all model types including + composite models and models that do not support head dim by themselves. + + Why? A lot of kernels including flex attention rely on triton for compilation. + However, triton cannot handle hidden dimensions of less than 16 for example. + (There are many more examples especially now that the `kernels` library is + supported) + """ + + def update_config_headdim(config, requested_dim): + # Flex Attention cannot use dropout + if hasattr(config, "attention_dropout"): + config.attention_dropout = 0 + if hasattr(config, "attention_probs_dropout_prob"): + config.attention_probs_dropout_prob = 0 + + # Update the head dim and try to update hidden size as well if present in config + # NOTE: some models may have none if the values in sub-config, thus we check for `Noneness` + head_dim = None + if hasattr(config, "head_dim") and config.head_dim is not None: + head_dim = config.head_dim + config.head_dim = max(requested_dim, config.head_dim) + + cross_head_dim = None + if hasattr(config, "cross_head_dim") and config.cross_head_dim is not None: + cross_head_dim = config.cross_head_dim + config.cross_head_dim = max(requested_dim, config.cross_head_dim) + + if ( + getattr(config, "hidden_size", None) is not None + and getattr(config, "num_attention_heads", None) is not None + ): + head_dim = head_dim if head_dim is not None else config.hidden_size // config.num_attention_heads + config.hidden_size *= max(requested_dim // head_dim, 1) + + if ( + getattr(config, "decoder_hidden_size", None) is not None + and getattr(config, "decoder_num_attention_heads", None) is not None + ): + decoder_head_dim = config.decoder_hidden_size // config.decoder_num_attention_heads + config.decoder_hidden_size *= max(requested_dim // decoder_head_dim, 1) + + if ( + getattr(config, "cross_hidden_size", None) is not None + and getattr(config, "cross_num_attention_heads", None) is not None + ): + cross_head_dim = ( + cross_head_dim + if cross_head_dim is not None + else config.cross_hidden_size // config.cross_num_attention_heads + ) + config.cross_hidden_size *= max(requested_dim // cross_head_dim, 1) + + # Update config values + update_config_headdim(config, requested_dim) + for key in config.sub_configs: + sub_config = getattr(config, key) + update_config_headdim(sub_config, requested_dim) + + return config + + @require_torch_gpu + def test_flex_attention_with_grads(self): + for model_class in self.all_model_classes: + config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() + inputs_dict = self._prepare_for_class(inputs_dict, model_class) + model = model_class(config).to(device=torch_device) + + # If not all sub-models support flex, skip the test + if not all( + submodel._supports_flex_attn for submodel in model.modules() if isinstance(submodel, PreTrainedModel) + ): + self.skipTest(reason="At least some parts of this model do not support flex attention") + + # Set default attention to flex and update config values + config = self._prepare_config_headdim(config, 16) # specific to triton + + if model_class._can_set_attn_implementation(): + model = model_class(config).to(device=torch_device) + model.set_attn_implementation("flex_attention") + self.assertTrue(model.config._attn_implementation == "flex_attention") + else: + config._attn_implementation = "flex_attention" + model = model_class(config).to(device=torch_device) + + # Elaborate workaround for encoder-decoder models as some do not specify their main input + dummy_inputs = {model.main_input_name: inputs_dict[model.main_input_name].to(torch_device)} + for key in getattr(self, "additional_model_inputs", []): + # Some models don't have all `additional_model_inputs`, especially when we + # craft cases to test model in different settings + if key in inputs_dict: + dummy_inputs[key] = inputs_dict[key].to(torch_device) + + if config.get_text_config(decoder=True).is_encoder_decoder: + dummy_inputs["decoder_input_ids"] = inputs_dict["decoder_input_ids"].to(torch_device) + dummy_inputs["decoder_attention_mask"] = inputs_dict["decoder_attention_mask"].to(torch_device) + + # If this does not raise an error, the test passes (see https://github.com/huggingface/transformers/pull/35605) + _ = model(**dummy_inputs) + + def test_generation_tester_mixin_inheritance(self): + """ + Ensures that we have the generation tester mixin if the model can generate. The test will fail otherwise, + forcing the mixin to be added -- and ensuring proper test coverage + """ + if len(self.all_generative_model_classes) > 0: + self.assertTrue( + issubclass(self.__class__, GenerationTesterMixin), + msg=( + "This model can call `generate` from `GenerationMixin`, so one of two things must happen: 1) the " + "tester must inherit from `GenerationTesterMixin` to run `generate` tests, or 2) if the model " + "doesn't fully support the original `generate` or has a custom `generate` with partial feature " + "support, the tester must overwrite `all_generative_model_classes` to skip the failing classes " + "(make sure to comment why). If `all_generative_model_classes` is overwritten as `()`, then we " + "need to remove the `GenerationTesterMixin` inheritance -- no `generate` tests are being run." + ), + ) + else: + self.assertFalse( + issubclass(self.__class__, GenerationTesterMixin), + msg=( + "This model can't call `generate`, so its tester can't inherit `GenerationTesterMixin`. (If you " + "think the model should be able to `generate`, the model may be missing the `GenerationMixin` " + "inheritance)" + ), + ) + + def test_can_be_initialized_on_meta(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + # If it does not raise here, the test passes + with torch.device("meta"): + _ = model_class(copy.deepcopy(config)) + + @require_torch_accelerator + def test_can_load_with_device_context_manager(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + # Need to specify index 0 here, as `torch_device` is simply the str of the type, e.g. "cuda" + device = torch.device(torch_device, index=0) + for model_class in self.all_model_classes: + # Need to deepcopy here as it is modified in-place in save_pretrained (it sets sdpa for default attn, which + # is not supported for e.g. dpt_hybrid) + model = model_class(copy.deepcopy(config)) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + with device: + new_model = model_class.from_pretrained(tmpdirname) + unique_devices = {param.device for param in new_model.parameters()} | { + buffer.device for buffer in new_model.buffers() + } + + self.assertEqual( + unique_devices, {device}, f"All parameters should be on {device}, but found {unique_devices}." + ) + + # Here we need to run with a subprocess as otherwise setting back the default device to the default value ("cpu") + # may bring unwanted consequences on other tests. See PR #37553 + @run_first + @run_test_using_subprocess + @require_torch_accelerator + def test_can_load_with_global_device_set(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + # Need to specify index 0 here, as `torch_device` is simply the str of the type, e.g. "cuda" + device = torch.device(torch_device, index=0) + default_device = torch.get_default_device() + for model_class in self.all_model_classes: + # Need to deepcopy here as it is modified in-place in save_pretrained (it sets sdpa for default attn, which + # is not supported for e.g. dpt_hybrid) + model = model_class(copy.deepcopy(config)) + + # set a global gpu device + torch.set_default_device(device) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + new_model = model_class.from_pretrained(tmpdirname) + unique_devices = {param.device for param in new_model.parameters()} | { + buffer.device for buffer in new_model.buffers() + } + + # set back the correct device + torch.set_default_device(default_device) + + self.assertEqual( + unique_devices, {device}, f"All parameters should be on {device}, but found {unique_devices}." + ) + + def test_can_load_with_meta_device_context_manager(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + # Need to deepcopy here as it is modified in-place in save_pretrained (it sets sdpa for default attn, which + # is not supported for e.g. dpt_hybrid) + model = model_class(copy.deepcopy(config)) + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + with torch.device("meta"): + new_model = model_class.from_pretrained(tmpdirname) + unique_devices = {param.device for param in new_model.parameters()} | { + buffer.device for buffer in new_model.buffers() + } + + self.assertEqual( + unique_devices, + {torch.device("meta")}, + f"All parameters should be on meta device, but found {unique_devices}.", + ) + + def test_config_attn_implementation_setter(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + + def check_attn_implementation_setter(config: PretrainedConfig, attn_implementation: str): + if not config._attn_implementation == attn_implementation: + raise ValueError( + f"Unexpected attn_implementation for config {config.__class__.__name__}: " + f"{config._attn_implementation} != {attn_implementation}" + ) + for attribute_value in config.__dict__.values(): + if isinstance(attribute_value, PretrainedConfig): + check_attn_implementation_setter(attribute_value, attn_implementation) + + config._attn_implementation = "eager" + check_attn_implementation_setter(config, "eager") + + config._attn_implementation = "sdpa" + check_attn_implementation_setter(config, "sdpa") + + def test_internal_model_config_and_subconfig_are_same(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + subconfig_keys = list(config.sub_configs.keys()) + for model_class in self.all_model_classes: + if len(config.sub_configs) == 0: + self.skipTest(reason="No subconfigs so the test does not make sense") + # Need to deepcopy here to avoid changing the _attn_implementation in-place + model = model_class(copy.deepcopy(config)) + + for submodule in model.modules(): + # This is a submodel + if isinstance(submodule, PreTrainedModel) and submodule.config.__class__ != model.config.__class__: + subconfig_from_model_internal = submodule.config + matching_sub_configs = [] + for subconfig_key in subconfig_keys: + # Get the subconfig from the model config + subconfig_from_model_config = getattr(model.config, subconfig_key) + if subconfig_from_model_config.__class__ == subconfig_from_model_internal.__class__: + # Since some composite models have different submodels parameterized by 2 of the same config + # class instances, we need to check against a list of matching classes, and check that at least + # 1 is the exact object (instead of checking immediately for similar object) + matching_sub_configs.append(subconfig_from_model_config) + + # Both should be exactly the same object, that is when instantiating the submodel when should + # absolutely not copy the subconfig + if len(matching_sub_configs) > 0: + self.assertTrue( + any( + subconfig_from_model_config is subconfig_from_model_internal + for subconfig_from_model_config in matching_sub_configs + ) + ) + + def test_can_set_attention_dynamically(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + if not model_class._can_set_attn_implementation(): + self.skipTest(reason="This model does not support setting its attention dynamically") + + # Need to deepcopy here to avoid changing the _attn_implementation in-place + model_config = copy.deepcopy(config) + # Set eager everywhere (it sets it recursively on subconfigs) + model_config._attn_implementation = "eager" + model = model_class(model_config) + + # sanity check to make sure everything is correctly eager + self.assertTrue(model.config._attn_implementation == "eager") + for subconfig_key in model.config.sub_configs: + self.assertTrue(getattr(model.config, subconfig_key)._attn_implementation == "eager") + + if not all( + submodule._can_set_attn_implementation() + for submodule in model.modules() + if isinstance(submodule, PreTrainedModel) + ): + self.skipTest(reason="Parts of this model cannot set attention dynamically") + # Some old models technically should support switching, but don't have the flags active... + if not all( + submodule._supports_sdpa for submodule in model.modules() if isinstance(submodule, PreTrainedModel) + ): + self.skipTest(reason="Parts of this model don't support sdpa") + + # Now, set it to sdpa + model.set_attn_implementation("sdpa") + + # Check everything was correctly changed + self.assertTrue(model.config._attn_implementation == "sdpa") + for subconfig_key in model.config.sub_configs: + self.assertTrue(getattr(model.config, subconfig_key)._attn_implementation == "sdpa") + + # Check we cannot set it to random values, and it raises an error + with self.assertRaisesRegex(ValueError, 'Specified `attn_implementation="foo"` is not supported'): + model.set_attn_implementation("foo") + + # Should still be sdpa everywhere + self.assertTrue(model.config._attn_implementation == "sdpa") + for subconfig_key in model.config.sub_configs: + self.assertTrue(getattr(model.config, subconfig_key)._attn_implementation == "sdpa") + + def test_can_set_attention_dynamically_composite_model(self): + config, _ = self.model_tester.prepare_config_and_inputs_for_common() + for model_class in self.all_model_classes: + if not model_class._can_set_attn_implementation(): + self.skipTest(reason="This model does not support setting its attention dynamically") + if not self._is_composite: + self.skipTest(reason="This model is not composite") + + # Need to deepcopy here to avoid changing the _attn_implementation in-place + model_config = copy.deepcopy(config) + # Set eager everywhere (it sets it recursively on subconfigs) + model_config._attn_implementation = "eager" + model = model_class(model_config) + + # sanity check to make sure everything is correctly eager + self.assertTrue(model.config._attn_implementation == "eager") + for subconfig_key in model.config.sub_configs: + self.assertTrue(getattr(model.config, subconfig_key)._attn_implementation == "eager") + + if not all( + submodule._can_set_attn_implementation() + for submodule in model.modules() + if isinstance(submodule, PreTrainedModel) + ): + self.skipTest(reason="Parts of this model cannot set attention dynamically") + + # Now, set only top-most to sdpa (should support it if it supports the dynamic switch) + model.set_attn_implementation({"": "sdpa"}) + + # Check only top-most was correctly changed + self.assertTrue(model.config._attn_implementation == "sdpa") + for subconfig_key in model.config.sub_configs: + self.assertTrue(getattr(model.config, subconfig_key)._attn_implementation == "eager") + + +global_rng = random.Random() + + +def ids_tensor(shape, vocab_size, rng=None, name=None): + # Creates a random int32 tensor of the shape within the vocab size + if rng is None: + rng = global_rng + + total_dims = 1 + for dim in shape: + total_dims *= dim + + values = [] + for _ in range(total_dims): + values.append(rng.randint(0, vocab_size - 1)) + + return torch.tensor(data=values, dtype=torch.long, device=torch_device).view(shape).contiguous() + + +def random_attention_mask(shape, rng=None, name=None): + attn_mask = ids_tensor(shape, vocab_size=2, rng=None, name=None) + # make sure that at least one token is attended to for each batch + # we choose the 1st token so this property of `at least one being non-zero` still holds after applying causal mask + attn_mask[:, 0] = 1 + return attn_mask + + +def floats_tensor(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + total_dims = 1 + for dim in shape: + total_dims *= dim + + values = [] + for _ in range(total_dims): + values.append(rng.random() * scale) + + return torch.tensor(data=values, dtype=torch.float, device=torch_device).view(shape).contiguous() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_pipeline_mixin.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_pipeline_mixin.py new file mode 100644 index 0000000000000000000000000000000000000000..2cad0b90527e212b17f78c6c02ee406e1f83f3de --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_pipeline_mixin.py @@ -0,0 +1,976 @@ +# Copyright 2023 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. + +import copy +import inspect +import json +import os +import random +import re +import unittest +from dataclasses import fields, is_dataclass +from pathlib import Path +from textwrap import dedent +from typing import get_args + +from huggingface_hub import ( + AudioClassificationInput, + AutomaticSpeechRecognitionInput, + DepthEstimationInput, + ImageClassificationInput, + ImageSegmentationInput, + ImageToTextInput, + ObjectDetectionInput, + QuestionAnsweringInput, + VideoClassificationInput, + ZeroShotImageClassificationInput, +) + +from transformers.models.auto.processing_auto import PROCESSOR_MAPPING_NAMES +from transformers.pipelines import ( + AudioClassificationPipeline, + AutomaticSpeechRecognitionPipeline, + DepthEstimationPipeline, + ImageClassificationPipeline, + ImageSegmentationPipeline, + ImageToTextPipeline, + ObjectDetectionPipeline, + QuestionAnsweringPipeline, + VideoClassificationPipeline, + ZeroShotImageClassificationPipeline, +) +from transformers.testing_utils import ( + is_pipeline_test, + require_av, + require_pytesseract, + require_timm, + require_torch, + require_torch_or_tf, + require_vision, +) +from transformers.utils import direct_transformers_import, logging + +from .pipelines.test_pipelines_audio_classification import AudioClassificationPipelineTests +from .pipelines.test_pipelines_automatic_speech_recognition import AutomaticSpeechRecognitionPipelineTests +from .pipelines.test_pipelines_depth_estimation import DepthEstimationPipelineTests +from .pipelines.test_pipelines_document_question_answering import DocumentQuestionAnsweringPipelineTests +from .pipelines.test_pipelines_feature_extraction import FeatureExtractionPipelineTests +from .pipelines.test_pipelines_fill_mask import FillMaskPipelineTests +from .pipelines.test_pipelines_image_classification import ImageClassificationPipelineTests +from .pipelines.test_pipelines_image_feature_extraction import ImageFeatureExtractionPipelineTests +from .pipelines.test_pipelines_image_segmentation import ImageSegmentationPipelineTests +from .pipelines.test_pipelines_image_text_to_text import ImageTextToTextPipelineTests +from .pipelines.test_pipelines_image_to_image import ImageToImagePipelineTests +from .pipelines.test_pipelines_image_to_text import ImageToTextPipelineTests +from .pipelines.test_pipelines_mask_generation import MaskGenerationPipelineTests +from .pipelines.test_pipelines_object_detection import ObjectDetectionPipelineTests +from .pipelines.test_pipelines_question_answering import QAPipelineTests +from .pipelines.test_pipelines_summarization import SummarizationPipelineTests +from .pipelines.test_pipelines_table_question_answering import TQAPipelineTests +from .pipelines.test_pipelines_text2text_generation import Text2TextGenerationPipelineTests +from .pipelines.test_pipelines_text_classification import TextClassificationPipelineTests +from .pipelines.test_pipelines_text_generation import TextGenerationPipelineTests +from .pipelines.test_pipelines_text_to_audio import TextToAudioPipelineTests +from .pipelines.test_pipelines_token_classification import TokenClassificationPipelineTests +from .pipelines.test_pipelines_translation import TranslationPipelineTests +from .pipelines.test_pipelines_video_classification import VideoClassificationPipelineTests +from .pipelines.test_pipelines_visual_question_answering import VisualQuestionAnsweringPipelineTests +from .pipelines.test_pipelines_zero_shot import ZeroShotClassificationPipelineTests +from .pipelines.test_pipelines_zero_shot_audio_classification import ZeroShotAudioClassificationPipelineTests +from .pipelines.test_pipelines_zero_shot_image_classification import ZeroShotImageClassificationPipelineTests +from .pipelines.test_pipelines_zero_shot_object_detection import ZeroShotObjectDetectionPipelineTests + + +pipeline_test_mapping = { + "audio-classification": {"test": AudioClassificationPipelineTests}, + "automatic-speech-recognition": {"test": AutomaticSpeechRecognitionPipelineTests}, + "depth-estimation": {"test": DepthEstimationPipelineTests}, + "document-question-answering": {"test": DocumentQuestionAnsweringPipelineTests}, + "feature-extraction": {"test": FeatureExtractionPipelineTests}, + "fill-mask": {"test": FillMaskPipelineTests}, + "image-classification": {"test": ImageClassificationPipelineTests}, + "image-feature-extraction": {"test": ImageFeatureExtractionPipelineTests}, + "image-segmentation": {"test": ImageSegmentationPipelineTests}, + "image-text-to-text": {"test": ImageTextToTextPipelineTests}, + "image-to-image": {"test": ImageToImagePipelineTests}, + "image-to-text": {"test": ImageToTextPipelineTests}, + "mask-generation": {"test": MaskGenerationPipelineTests}, + "object-detection": {"test": ObjectDetectionPipelineTests}, + "question-answering": {"test": QAPipelineTests}, + "summarization": {"test": SummarizationPipelineTests}, + "table-question-answering": {"test": TQAPipelineTests}, + "text2text-generation": {"test": Text2TextGenerationPipelineTests}, + "text-classification": {"test": TextClassificationPipelineTests}, + "text-generation": {"test": TextGenerationPipelineTests}, + "text-to-audio": {"test": TextToAudioPipelineTests}, + "token-classification": {"test": TokenClassificationPipelineTests}, + "translation": {"test": TranslationPipelineTests}, + "video-classification": {"test": VideoClassificationPipelineTests}, + "visual-question-answering": {"test": VisualQuestionAnsweringPipelineTests}, + "zero-shot": {"test": ZeroShotClassificationPipelineTests}, + "zero-shot-audio-classification": {"test": ZeroShotAudioClassificationPipelineTests}, + "zero-shot-image-classification": {"test": ZeroShotImageClassificationPipelineTests}, + "zero-shot-object-detection": {"test": ZeroShotObjectDetectionPipelineTests}, +} + +task_to_pipeline_and_spec_mapping = { + # Adding a task to this list will cause its pipeline input signature to be checked against the corresponding + # task spec in the HF Hub + "audio-classification": (AudioClassificationPipeline, AudioClassificationInput), + "automatic-speech-recognition": (AutomaticSpeechRecognitionPipeline, AutomaticSpeechRecognitionInput), + "depth-estimation": (DepthEstimationPipeline, DepthEstimationInput), + "image-classification": (ImageClassificationPipeline, ImageClassificationInput), + "image-segmentation": (ImageSegmentationPipeline, ImageSegmentationInput), + "image-to-text": (ImageToTextPipeline, ImageToTextInput), + "object-detection": (ObjectDetectionPipeline, ObjectDetectionInput), + "question-answering": (QuestionAnsweringPipeline, QuestionAnsweringInput), + "video-classification": (VideoClassificationPipeline, VideoClassificationInput), + "zero-shot-image-classification": (ZeroShotImageClassificationPipeline, ZeroShotImageClassificationInput), +} + +for task_info in pipeline_test_mapping.values(): + test = task_info["test"] + task_info["mapping"] = { + "pt": getattr(test, "model_mapping", None), + "tf": getattr(test, "tf_model_mapping", None), + } + + +# The default value `hf-internal-testing` is for running the pipeline testing against the tiny models on the Hub. +# For debugging purpose, we can specify a local path which is the `output_path` argument of a previous run of +# `utils/create_dummy_models.py`. +TRANSFORMERS_TINY_MODEL_PATH = os.environ.get("TRANSFORMERS_TINY_MODEL_PATH", "hf-internal-testing") +if TRANSFORMERS_TINY_MODEL_PATH == "hf-internal-testing": + TINY_MODEL_SUMMARY_FILE_PATH = os.path.join(Path(__file__).parent.parent, "tests/utils/tiny_model_summary.json") +else: + TINY_MODEL_SUMMARY_FILE_PATH = os.path.join(TRANSFORMERS_TINY_MODEL_PATH, "reports", "tiny_model_summary.json") +with open(TINY_MODEL_SUMMARY_FILE_PATH) as fp: + tiny_model_summary = json.load(fp) + + +PATH_TO_TRANSFORMERS = os.path.join(Path(__file__).parent.parent, "src/transformers") + + +# Dynamically import the Transformers module to grab the attribute classes of the processor form their names. +transformers_module = direct_transformers_import(PATH_TO_TRANSFORMERS) + +logger = logging.get_logger(__name__) + + +class PipelineTesterMixin: + model_tester = None + pipeline_model_mapping = None + supported_frameworks = ["pt", "tf"] + + def run_task_tests(self, task, torch_dtype="float32"): + """Run pipeline tests for a specific `task` + + Args: + task (`str`): + A task name. This should be a key in the mapping `pipeline_test_mapping`. + torch_dtype (`str`, `optional`, defaults to `'float32'`): + The torch dtype to use for the model. Can be used for FP16/other precision inference. + """ + if task not in self.pipeline_model_mapping: + self.skipTest( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')}_{torch_dtype} is skipped: `{task}` is not in " + f"`self.pipeline_model_mapping` for `{self.__class__.__name__}`." + ) + + model_architectures = self.pipeline_model_mapping[task] + if not isinstance(model_architectures, tuple): + model_architectures = (model_architectures,) + + # We are going to run tests for multiple model architectures, some of them might be skipped + # with this flag we are control if at least one model were tested or all were skipped + at_least_one_model_is_tested = False + + for model_architecture in model_architectures: + model_arch_name = model_architecture.__name__ + model_type = model_architecture.config_class.model_type + + # Get the canonical name + for _prefix in ["Flax", "TF"]: + if model_arch_name.startswith(_prefix): + model_arch_name = model_arch_name[len(_prefix) :] + break + + if model_arch_name not in tiny_model_summary: + continue + + tokenizer_names = tiny_model_summary[model_arch_name]["tokenizer_classes"] + + # Sort image processors and feature extractors from tiny-models json file + image_processor_names = [] + feature_extractor_names = [] + + processor_classes = tiny_model_summary[model_arch_name]["processor_classes"] + for cls_name in processor_classes: + if "ImageProcessor" in cls_name: + image_processor_names.append(cls_name) + elif "FeatureExtractor" in cls_name: + feature_extractor_names.append(cls_name) + + # Processor classes are not in tiny models JSON file, so extract them from the mapping + # processors are mapped to instance, e.g. "XxxProcessor" + processor_names = PROCESSOR_MAPPING_NAMES.get(model_type, None) + if not isinstance(processor_names, (list, tuple)): + processor_names = [processor_names] + + commit = None + if model_arch_name in tiny_model_summary and "sha" in tiny_model_summary[model_arch_name]: + commit = tiny_model_summary[model_arch_name]["sha"] + + repo_name = f"tiny-random-{model_arch_name}" + if TRANSFORMERS_TINY_MODEL_PATH != "hf-internal-testing": + repo_name = model_arch_name + + self.run_model_pipeline_tests( + task, + repo_name, + model_architecture, + tokenizer_names=tokenizer_names, + image_processor_names=image_processor_names, + feature_extractor_names=feature_extractor_names, + processor_names=processor_names, + commit=commit, + torch_dtype=torch_dtype, + ) + at_least_one_model_is_tested = True + + if task in task_to_pipeline_and_spec_mapping: + pipeline, hub_spec = task_to_pipeline_and_spec_mapping[task] + compare_pipeline_args_to_hub_spec(pipeline, hub_spec) + + if not at_least_one_model_is_tested: + self.skipTest( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')}_{torch_dtype} is skipped: Could not find any " + f"model architecture in the tiny models JSON file for `{task}`." + ) + + def run_model_pipeline_tests( + self, + task, + repo_name, + model_architecture, + tokenizer_names, + image_processor_names, + feature_extractor_names, + processor_names, + commit, + torch_dtype="float32", + ): + """Run pipeline tests for a specific `task` with the give model class and tokenizer/processor class names + + Args: + task (`str`): + A task name. This should be a key in the mapping `pipeline_test_mapping`. + repo_name (`str`): + A model repository id on the Hub. + model_architecture (`type`): + A subclass of `PretrainedModel` or `PretrainedModel`. + tokenizer_names (`list[str]`): + A list of names of a subclasses of `PreTrainedTokenizerFast` or `PreTrainedTokenizer`. + image_processor_names (`list[str]`): + A list of names of subclasses of `BaseImageProcessor`. + feature_extractor_names (`list[str]`): + A list of names of subclasses of `FeatureExtractionMixin`. + processor_names (`list[str]`): + A list of names of subclasses of `ProcessorMixin`. + commit (`str`): + The commit hash of the model repository on the Hub. + torch_dtype (`str`, `optional`, defaults to `'float32'`): + The torch dtype to use for the model. Can be used for FP16/other precision inference. + """ + # Get an instance of the corresponding class `XXXPipelineTests` in order to use `get_test_pipeline` and + # `run_pipeline_test`. + pipeline_test_class_name = pipeline_test_mapping[task]["test"].__name__ + + # If no image processor or feature extractor is found, we still need to test the pipeline with None + # otherwise for any empty list we might skip all the tests + tokenizer_names = tokenizer_names or [None] + image_processor_names = image_processor_names or [None] + feature_extractor_names = feature_extractor_names or [None] + processor_names = processor_names or [None] + + test_cases = [ + { + "tokenizer_name": tokenizer_name, + "image_processor_name": image_processor_name, + "feature_extractor_name": feature_extractor_name, + "processor_name": processor_name, + } + for tokenizer_name in tokenizer_names + for image_processor_name in image_processor_names + for feature_extractor_name in feature_extractor_names + for processor_name in processor_names + ] + + for test_case in test_cases: + tokenizer_name = test_case["tokenizer_name"] + image_processor_name = test_case["image_processor_name"] + feature_extractor_name = test_case["feature_extractor_name"] + processor_name = test_case["processor_name"] + + do_skip_test_case = self.is_pipeline_test_to_skip( + pipeline_test_class_name, + model_architecture.config_class, + model_architecture, + tokenizer_name, + image_processor_name, + feature_extractor_name, + processor_name, + ) + + if do_skip_test_case: + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')}_{torch_dtype} is skipped: test is " + f"currently known to fail for: model `{model_architecture.__name__}` | tokenizer " + f"`{tokenizer_name}` | image processor `{image_processor_name}` | feature extractor {feature_extractor_name}." + ) + continue + + self.run_pipeline_test( + task, + repo_name, + model_architecture, + tokenizer_name=tokenizer_name, + image_processor_name=image_processor_name, + feature_extractor_name=feature_extractor_name, + processor_name=processor_name, + commit=commit, + torch_dtype=torch_dtype, + ) + + def run_pipeline_test( + self, + task, + repo_name, + model_architecture, + tokenizer_name, + image_processor_name, + feature_extractor_name, + processor_name, + commit, + torch_dtype="float32", + ): + """Run pipeline tests for a specific `task` with the give model class and tokenizer/processor class name + + The model will be loaded from a model repository on the Hub. + + Args: + task (`str`): + A task name. This should be a key in the mapping `pipeline_test_mapping`. + repo_name (`str`): + A model repository id on the Hub. + model_architecture (`type`): + A subclass of `PretrainedModel` or `PretrainedModel`. + tokenizer_name (`str`): + The name of a subclass of `PreTrainedTokenizerFast` or `PreTrainedTokenizer`. + image_processor_name (`str`): + The name of a subclass of `BaseImageProcessor`. + feature_extractor_name (`str`): + The name of a subclass of `FeatureExtractionMixin`. + processor_name (`str`): + The name of a subclass of `ProcessorMixin`. + commit (`str`): + The commit hash of the model repository on the Hub. + torch_dtype (`str`, `optional`, defaults to `'float32'`): + The torch dtype to use for the model. Can be used for FP16/other precision inference. + """ + repo_id = f"{TRANSFORMERS_TINY_MODEL_PATH}/{repo_name}" + model_type = model_architecture.config_class.model_type + + if TRANSFORMERS_TINY_MODEL_PATH != "hf-internal-testing": + repo_id = os.path.join(TRANSFORMERS_TINY_MODEL_PATH, model_type, repo_name) + + # -------------------- Load model -------------------- + + # TODO: We should check if a model file is on the Hub repo. instead. + try: + model = model_architecture.from_pretrained(repo_id, revision=commit) + except Exception: + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')}_{torch_dtype} is skipped: Could not find or load " + f"the model from `{repo_id}` with `{model_architecture}`." + ) + self.skipTest(f"Could not find or load the model from {repo_id} with {model_architecture}.") + + # -------------------- Load tokenizer -------------------- + + tokenizer = None + if tokenizer_name is not None: + tokenizer_class = getattr(transformers_module, tokenizer_name) + tokenizer = tokenizer_class.from_pretrained(repo_id, revision=commit) + + # -------------------- Load processors -------------------- + + processors = {} + for key, name in zip( + ["image_processor", "feature_extractor", "processor"], + [image_processor_name, feature_extractor_name, processor_name], + ): + if name is not None: + try: + # Can fail if some extra dependencies are not installed + processor_class = getattr(transformers_module, name) + processor = processor_class.from_pretrained(repo_id, revision=commit) + processors[key] = processor + except Exception: + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')}_{torch_dtype} is skipped: " + f"Could not load the {key} from `{repo_id}` with `{name}`." + ) + self.skipTest(f"Could not load the {key} from {repo_id} with {name}.") + + # --------------------------------------------------------- + + # TODO: Maybe not upload such problematic tiny models to Hub. + if tokenizer is None and "image_processor" not in processors and "feature_extractor" not in processors: + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')}_{torch_dtype} is skipped: Could not find or load " + f"any tokenizer / image processor / feature extractor from `{repo_id}`." + ) + self.skipTest(f"Could not find or load any tokenizer / processor from {repo_id}.") + + pipeline_test_class_name = pipeline_test_mapping[task]["test"].__name__ + if self.is_pipeline_test_to_skip_more(pipeline_test_class_name, model.config, model, tokenizer, **processors): + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')}_{torch_dtype} is skipped: test is " + f"currently known to fail for: model `{model_architecture.__name__}` | tokenizer " + f"`{tokenizer_name}` | image processor `{image_processor_name}` | feature extractor `{feature_extractor_name}`." + ) + self.skipTest( + f"Test is known to fail for: model `{model_architecture.__name__}` | tokenizer `{tokenizer_name}` " + f"| image processor `{image_processor_name}` | feature extractor `{feature_extractor_name}`." + ) + + # validate + validate_test_components(model, tokenizer) + + if hasattr(model, "eval"): + model = model.eval() + + # Get an instance of the corresponding class `XXXPipelineTests` in order to use `get_test_pipeline` and + # `run_pipeline_test`. + task_test = pipeline_test_mapping[task]["test"]() + + pipeline, examples = task_test.get_test_pipeline(model, tokenizer, **processors, torch_dtype=torch_dtype) + if pipeline is None: + # The test can disable itself, but it should be very marginal + # Concerns: Wav2Vec2ForCTC without tokenizer test (FastTokenizer don't exist) + logger.warning( + f"{self.__class__.__name__}::test_pipeline_{task.replace('-', '_')}_{torch_dtype} is skipped: Could not get the " + "pipeline for testing." + ) + self.skipTest(reason="Could not get the pipeline for testing.") + + task_test.run_pipeline_test(pipeline, examples) + + def run_batch_test(pipeline, examples): + # Need to copy because `Conversation` are stateful + if pipeline.tokenizer is not None and pipeline.tokenizer.pad_token_id is None: + return # No batching for this and it's OK + + # 10 examples with batch size 4 means there needs to be a unfinished batch + # which is important for the unbatcher + def data(n): + for _ in range(n): + # Need to copy because Conversation object is mutated + yield copy.deepcopy(random.choice(examples)) + + out = [] + for item in pipeline(data(10), batch_size=4): + out.append(item) + self.assertEqual(len(out), 10) + + run_batch_test(pipeline, examples) + + @is_pipeline_test + def test_pipeline_audio_classification(self): + self.run_task_tests(task="audio-classification") + + @is_pipeline_test + @require_torch + def test_pipeline_audio_classification_fp16(self): + self.run_task_tests(task="audio-classification", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_automatic_speech_recognition(self): + self.run_task_tests(task="automatic-speech-recognition") + + @is_pipeline_test + @require_torch + def test_pipeline_automatic_speech_recognition_fp16(self): + self.run_task_tests(task="automatic-speech-recognition", torch_dtype="float16") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_depth_estimation(self): + self.run_task_tests(task="depth-estimation") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_depth_estimation_fp16(self): + self.run_task_tests(task="depth-estimation", torch_dtype="float16") + + @is_pipeline_test + @require_pytesseract + @require_torch + @require_vision + def test_pipeline_document_question_answering(self): + self.run_task_tests(task="document-question-answering") + + @is_pipeline_test + @require_pytesseract + @require_torch + @require_vision + def test_pipeline_document_question_answering_fp16(self): + self.run_task_tests(task="document-question-answering", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_feature_extraction(self): + self.run_task_tests(task="feature-extraction") + + @is_pipeline_test + @require_torch + def test_pipeline_feature_extraction_fp16(self): + self.run_task_tests(task="feature-extraction", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_fill_mask(self): + self.run_task_tests(task="fill-mask") + + @is_pipeline_test + @require_torch + def test_pipeline_fill_mask_fp16(self): + self.run_task_tests(task="fill-mask", torch_dtype="float16") + + @is_pipeline_test + @require_torch_or_tf + @require_vision + def test_pipeline_image_classification(self): + self.run_task_tests(task="image-classification") + + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_image_classification_fp16(self): + self.run_task_tests(task="image-classification", torch_dtype="float16") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_image_segmentation(self): + self.run_task_tests(task="image-segmentation") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_image_segmentation_fp16(self): + self.run_task_tests(task="image-segmentation", torch_dtype="float16") + + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_image_text_to_text(self): + self.run_task_tests(task="image-text-to-text") + + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_image_text_to_text_fp16(self): + self.run_task_tests(task="image-text-to-text", torch_dtype="float16") + + @is_pipeline_test + @require_vision + def test_pipeline_image_to_text(self): + self.run_task_tests(task="image-to-text") + + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_image_to_text_fp16(self): + self.run_task_tests(task="image-to-text", torch_dtype="float16") + + @is_pipeline_test + @require_timm + @require_vision + @require_torch + def test_pipeline_image_feature_extraction(self): + self.run_task_tests(task="image-feature-extraction") + + @is_pipeline_test + @require_timm + @require_vision + @require_torch + def test_pipeline_image_feature_extraction_fp16(self): + self.run_task_tests(task="image-feature-extraction", torch_dtype="float16") + + @unittest.skip(reason="`run_pipeline_test` is currently not implemented.") + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_mask_generation(self): + self.run_task_tests(task="mask-generation") + + @unittest.skip(reason="`run_pipeline_test` is currently not implemented.") + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_mask_generation_fp16(self): + self.run_task_tests(task="mask-generation", torch_dtype="float16") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_object_detection(self): + self.run_task_tests(task="object-detection") + + @is_pipeline_test + @require_vision + @require_timm + @require_torch + def test_pipeline_object_detection_fp16(self): + self.run_task_tests(task="object-detection", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_question_answering(self): + self.run_task_tests(task="question-answering") + + @is_pipeline_test + @require_torch + def test_pipeline_question_answering_fp16(self): + self.run_task_tests(task="question-answering", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_summarization(self): + self.run_task_tests(task="summarization") + + @is_pipeline_test + @require_torch + def test_pipeline_summarization_fp16(self): + self.run_task_tests(task="summarization", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_table_question_answering(self): + self.run_task_tests(task="table-question-answering") + + @is_pipeline_test + @require_torch + def test_pipeline_table_question_answering_fp16(self): + self.run_task_tests(task="table-question-answering", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_text2text_generation(self): + self.run_task_tests(task="text2text-generation") + + @is_pipeline_test + @require_torch + def test_pipeline_text2text_generation_fp16(self): + self.run_task_tests(task="text2text-generation", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_text_classification(self): + self.run_task_tests(task="text-classification") + + @is_pipeline_test + @require_torch + def test_pipeline_text_classification_fp16(self): + self.run_task_tests(task="text-classification", torch_dtype="float16") + + @is_pipeline_test + @require_torch_or_tf + def test_pipeline_text_generation(self): + self.run_task_tests(task="text-generation") + + @is_pipeline_test + @require_torch + def test_pipeline_text_generation_fp16(self): + self.run_task_tests(task="text-generation", torch_dtype="float16") + + @is_pipeline_test + @require_torch + def test_pipeline_text_to_audio(self): + self.run_task_tests(task="text-to-audio") + + @is_pipeline_test + @require_torch + def test_pipeline_text_to_audio_fp16(self): + self.run_task_tests(task="text-to-audio", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_token_classification(self): + self.run_task_tests(task="token-classification") + + @is_pipeline_test + @require_torch + def test_pipeline_token_classification_fp16(self): + self.run_task_tests(task="token-classification", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_translation(self): + self.run_task_tests(task="translation") + + @is_pipeline_test + @require_torch + def test_pipeline_translation_fp16(self): + self.run_task_tests(task="translation", torch_dtype="float16") + + @is_pipeline_test + @require_torch_or_tf + @require_vision + @require_av + def test_pipeline_video_classification(self): + self.run_task_tests(task="video-classification") + + @is_pipeline_test + @require_vision + @require_torch + @require_av + def test_pipeline_video_classification_fp16(self): + self.run_task_tests(task="video-classification", torch_dtype="float16") + + @is_pipeline_test + @require_torch + @require_vision + def test_pipeline_visual_question_answering(self): + self.run_task_tests(task="visual-question-answering") + + @is_pipeline_test + @require_torch + @require_vision + def test_pipeline_visual_question_answering_fp16(self): + self.run_task_tests(task="visual-question-answering", torch_dtype="float16") + + @is_pipeline_test + def test_pipeline_zero_shot(self): + self.run_task_tests(task="zero-shot") + + @is_pipeline_test + @require_torch + def test_pipeline_zero_shot_fp16(self): + self.run_task_tests(task="zero-shot", torch_dtype="float16") + + @is_pipeline_test + @require_torch + def test_pipeline_zero_shot_audio_classification(self): + self.run_task_tests(task="zero-shot-audio-classification") + + @is_pipeline_test + @require_torch + def test_pipeline_zero_shot_audio_classification_fp16(self): + self.run_task_tests(task="zero-shot-audio-classification", torch_dtype="float16") + + @is_pipeline_test + @require_vision + def test_pipeline_zero_shot_image_classification(self): + self.run_task_tests(task="zero-shot-image-classification") + + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_zero_shot_image_classification_fp16(self): + self.run_task_tests(task="zero-shot-image-classification", torch_dtype="float16") + + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_zero_shot_object_detection(self): + self.run_task_tests(task="zero-shot-object-detection") + + @is_pipeline_test + @require_vision + @require_torch + def test_pipeline_zero_shot_object_detection_fp16(self): + self.run_task_tests(task="zero-shot-object-detection", torch_dtype="float16") + + # This contains the test cases to be skipped without model architecture being involved. + def is_pipeline_test_to_skip( + self, + pipeline_test_case_name, + config_class, + model_architecture, + tokenizer_name, + image_processor_name, + feature_extractor_name, + processor_name, + ): + """Skip some tests based on the classes or their names without the instantiated objects. + + This is to avoid calling `from_pretrained` (so reducing the runtime) if we already know the tests will fail. + """ + # No fix is required for this case. + if ( + pipeline_test_case_name == "DocumentQuestionAnsweringPipelineTests" + and tokenizer_name is not None + and not tokenizer_name.endswith("Fast") + ): + # `DocumentQuestionAnsweringPipelineTests` requires a fast tokenizer. + return True + + return False + + def is_pipeline_test_to_skip_more( + self, + pipeline_test_case_name, + config, + model, + tokenizer, + image_processor=None, + feature_extractor=None, + processor=None, + ): # noqa + """Skip some more tests based on the information from the instantiated objects.""" + # No fix is required for this case. + if ( + pipeline_test_case_name == "QAPipelineTests" + and tokenizer is not None + and getattr(tokenizer, "pad_token", None) is None + and not tokenizer.__class__.__name__.endswith("Fast") + ): + # `QAPipelineTests` doesn't work with a slow tokenizer that has no pad token. + return True + + return False + + +def validate_test_components(model, tokenizer): + # TODO: Move this to tiny model creation script + # head-specific (within a model type) necessary changes to the config + # 1. for `BlenderbotForCausalLM` + if model.__class__.__name__ == "BlenderbotForCausalLM": + model.config.encoder_no_repeat_ngram_size = 0 + + # TODO: Change the tiny model creation script: don't create models with problematic tokenizers + # Avoid `IndexError` in embedding layers + CONFIG_WITHOUT_VOCAB_SIZE = ["CanineConfig"] + if tokenizer is not None: + # Removing `decoder=True` in `get_text_config` can lead to conflicting values e.g. in MusicGen + config_vocab_size = getattr(model.config.get_text_config(decoder=True), "vocab_size", None) + # For CLIP-like models + if config_vocab_size is None: + if hasattr(model.config, "text_encoder"): + config_vocab_size = getattr(model.config.text_config, "vocab_size", None) + if config_vocab_size is None and model.config.__class__.__name__ not in CONFIG_WITHOUT_VOCAB_SIZE: + raise ValueError( + "Could not determine `vocab_size` from model configuration while `tokenizer` is not `None`." + ) + + +def get_arg_names_from_hub_spec(hub_spec, first_level=True): + # This util is used in pipeline tests, to verify that a pipeline's documented arguments + # match the Hub specification for that task + arg_names = [] + for field in fields(hub_spec): + # Recurse into nested fields, but max one level + if is_dataclass(field.type): + arg_names.extend([field.name for field in fields(field.type)]) + continue + # Next, catch nested fields that are part of a Union[], which is usually caused by Optional[] + for param_type in get_args(field.type): + if is_dataclass(param_type): + # Again, recurse into nested fields, but max one level + arg_names.extend([field.name for field in fields(param_type)]) + break + else: + # Finally, this line triggers if it's not a nested field + arg_names.append(field.name) + return arg_names + + +def parse_args_from_docstring_by_indentation(docstring): + # This util is used in pipeline tests, to extract the argument names from a google-format docstring + # to compare them against the Hub specification for that task. It uses indentation levels as a primary + # source of truth, so these have to be correct! + docstring = dedent(docstring) + lines_by_indent = [ + (len(line) - len(line.lstrip()), line.strip()) for line in docstring.split("\n") if line.strip() + ] + args_lineno = None + args_indent = None + args_end = None + for lineno, (indent, line) in enumerate(lines_by_indent): + if line == "Args:": + args_lineno = lineno + args_indent = indent + continue + elif args_lineno is not None and indent == args_indent: + args_end = lineno + break + if args_lineno is None: + raise ValueError("No args block to parse!") + elif args_end is None: + args_block = lines_by_indent[args_lineno + 1 :] + else: + args_block = lines_by_indent[args_lineno + 1 : args_end] + outer_indent_level = min(line[0] for line in args_block) + outer_lines = [line for line in args_block if line[0] == outer_indent_level] + arg_names = [re.match(r"(\w+)\W", line[1]).group(1) for line in outer_lines] + return arg_names + + +def compare_pipeline_args_to_hub_spec(pipeline_class, hub_spec): + """ + Compares the docstring of a pipeline class to the fields of the matching Hub input signature class to ensure that + they match. This guarantees that Transformers pipelines can be used in inference without needing to manually + refactor or rename inputs. + """ + ALLOWED_TRANSFORMERS_ONLY_ARGS = ["timeout"] + + docstring = inspect.getdoc(pipeline_class.__call__).strip() + docstring_args = set(parse_args_from_docstring_by_indentation(docstring)) + hub_args = set(get_arg_names_from_hub_spec(hub_spec)) + + # Special casing: We allow the name of this arg to differ + hub_generate_args = [ + hub_arg for hub_arg in hub_args if hub_arg.startswith("generate") or hub_arg.startswith("generation") + ] + docstring_generate_args = [ + docstring_arg + for docstring_arg in docstring_args + if docstring_arg.startswith("generate") or docstring_arg.startswith("generation") + ] + if ( + len(hub_generate_args) == 1 + and len(docstring_generate_args) == 1 + and hub_generate_args != docstring_generate_args + ): + hub_args.remove(hub_generate_args[0]) + docstring_args.remove(docstring_generate_args[0]) + + # Special casing 2: We permit some transformers-only arguments that don't affect pipeline output + for arg in ALLOWED_TRANSFORMERS_ONLY_ARGS: + if arg in docstring_args and arg not in hub_args: + docstring_args.remove(arg) + + if hub_args != docstring_args: + error = [f"{pipeline_class.__name__} differs from JS spec {hub_spec.__name__}"] + matching_args = hub_args & docstring_args + huggingface_hub_only = hub_args - docstring_args + transformers_only = docstring_args - hub_args + if matching_args: + error.append(f"Matching args: {matching_args}") + if huggingface_hub_only: + error.append(f"Huggingface Hub only: {huggingface_hub_only}") + if transformers_only: + error.append(f"Transformers only: {transformers_only}") + raise ValueError("\n".join(error)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_processing_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_processing_common.py new file mode 100644 index 0000000000000000000000000000000000000000..f757a6199908c1d83732bec08fe4f7d5a0d3203b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_processing_common.py @@ -0,0 +1,1250 @@ +# Copyright 2024 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. + + +import inspect +import json +import random +import tempfile +from pathlib import Path +from typing import Optional + +import numpy as np +from huggingface_hub import hf_hub_download +from parameterized import parameterized + +from transformers.models.auto.processing_auto import processor_class_from_name +from transformers.processing_utils import Unpack +from transformers.testing_utils import ( + check_json_file_has_correct_format, + require_av, + require_librosa, + require_torch, + require_vision, +) +from transformers.utils import is_av_available, is_torch_available, is_vision_available + + +global_rng = random.Random() + +if is_vision_available(): + from PIL import Image + +if is_torch_available(): + import torch + +MODALITY_INPUT_DATA = { + "images": [ + "http://images.cocodataset.org/val2017/000000039769.jpg", + "http://images.cocodataset.org/val2017/000000039769.jpg", + ], + "videos": [ + "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_10MB.mp4", + ["https://www.ilankelman.org/stopsigns/australia.jpg", "https://www.ilankelman.org/stopsigns/australia.jpg"], + ], + "audio": [ + "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/glass-breaking-151256.mp3", + "https://qianwen-res.oss-cn-beijing.aliyuncs.com/Qwen2-Audio/audio/f2641_0_throatclearing.wav", + ], +} + +if is_av_available(): + from transformers.video_utils import load_video + + # load a video file in memory for testing + video, _ = load_video("https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_10MB.mp4") + MODALITY_INPUT_DATA["videos"].append(video) + + +def prepare_image_inputs(): + """This function prepares a list of PIL images""" + image_inputs = [np.random.randint(255, size=(3, 30, 400), dtype=np.uint8)] + image_inputs = [Image.fromarray(np.moveaxis(x, 0, -1)) for x in image_inputs] + return image_inputs + + +# Copied from tests.models.whisper.test_feature_extraction_whisper.floats_list +def floats_list(shape, scale=1.0, rng=None, name=None): + """Creates a random float32 tensor""" + if rng is None: + rng = global_rng + + values = [] + for batch_idx in range(shape[0]): + values.append([]) + for _ in range(shape[1]): + values[-1].append(rng.random() * scale) + + return values + + +@require_torch +@require_vision +class ProcessorTesterMixin: + processor_class = None + text_input_name = "input_ids" + images_input_name = "pixel_values" + videos_input_name = "pixel_values_videos" + audio_input_name = "input_features" + + @staticmethod + def prepare_processor_dict(): + return {} + + def get_component(self, attribute, **kwargs): + assert attribute in self.processor_class.attributes + component_class_name = getattr(self.processor_class, f"{attribute}_class") + if isinstance(component_class_name, tuple): + if attribute == "image_processor": + # TODO: @yoni, change logic in v4.52 (when use_fast set to True by default) + component_class_name = component_class_name[0] + else: + component_class_name = component_class_name[-1] + + component_class = processor_class_from_name(component_class_name) + component = component_class.from_pretrained(self.tmpdirname, **kwargs) # noqa + if "tokenizer" in attribute and not component.pad_token: + component.pad_token = "[TEST_PAD]" + if component.pad_token_id is None: + component.pad_token_id = 0 + + return component + + def prepare_components(self): + components = {} + for attribute in self.processor_class.attributes: + component = self.get_component(attribute) + components[attribute] = component + + return components + + def get_processor(self): + components = self.prepare_components() + processor = self.processor_class(**components, **self.prepare_processor_dict()) + return processor + + def prepare_text_inputs(self, batch_size: Optional[int] = None, modality: Optional[str] = None): + if modality is not None: + special_token_to_add = getattr(self, f"{modality}_token", "") + else: + special_token_to_add = "" + + if batch_size is None: + return f"lower newer {special_token_to_add}" + + if batch_size < 1: + raise ValueError("batch_size must be greater than 0") + + if batch_size == 1: + return [f"lower newer {special_token_to_add}"] + return [f"lower newer {special_token_to_add}", f" {special_token_to_add} upper older longer string"] + [ + f"lower newer {special_token_to_add}" + ] * (batch_size - 2) + + @require_vision + def prepare_image_inputs(self, batch_size: Optional[int] = None): + """This function prepares a list of PIL images for testing""" + if batch_size is None: + return prepare_image_inputs()[0] + if batch_size < 1: + raise ValueError("batch_size must be greater than 0") + return prepare_image_inputs() * batch_size + + @require_vision + def prepare_video_inputs(self, batch_size: Optional[int] = None): + """This function prepares a list of numpy videos.""" + video_input = [np.random.randint(255, size=(3, 30, 400), dtype=np.uint8)] * 8 + if batch_size is None: + return video_input + return [video_input] * batch_size + + def test_processor_to_json_string(self): + processor = self.get_processor() + obj = json.loads(processor.to_json_string()) + for key, value in self.prepare_processor_dict().items(): + # Chat template is saved as a separate file + if key not in "chat_template": + # json converts dict keys to str, but some processors force convert back to int when init + if ( + isinstance(obj[key], dict) + and isinstance(list(obj[key].keys())[0], str) + and isinstance(list(value.keys())[0], int) + ): + obj[key] = {int(k): v for k, v in obj[key].items()} + self.assertEqual(obj[key], value) + self.assertEqual(getattr(processor, key, None), value) + + def test_processor_from_and_save_pretrained(self): + processor_first = self.get_processor() + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_files = processor_first.save_pretrained(tmpdirname) + if len(saved_files) > 0: + check_json_file_has_correct_format(saved_files[0]) + processor_second = self.processor_class.from_pretrained(tmpdirname) + + self.assertEqual(processor_second.to_dict(), processor_first.to_dict()) + + for attribute in processor_first.attributes: + attribute_first = getattr(processor_first, attribute) + attribute_second = getattr(processor_second, attribute) + + # tokenizer repr contains model-path from where we loaded + if "tokenizer" not in attribute: + self.assertEqual(repr(attribute_first), repr(attribute_second)) + + # These kwargs-related tests ensure that processors are correctly instantiated. + # they need to be applied only if an image_processor exists. + + def skip_processor_without_typed_kwargs(self, processor): + # TODO this signature check is to test only uniformized processors. + # Once all are updated, remove it. + is_kwargs_typed_dict = False + call_signature = inspect.signature(processor.__call__) + for param in call_signature.parameters.values(): + if param.kind == param.VAR_KEYWORD and param.annotation != param.empty: + is_kwargs_typed_dict = ( + hasattr(param.annotation, "__origin__") and param.annotation.__origin__ == Unpack + ) + if not is_kwargs_typed_dict: + self.skipTest(f"{self.processor_class} doesn't have typed kwargs.") + + def test_tokenizer_defaults_preserved_by_kwargs(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + input_str = self.prepare_text_inputs(modality="image") + image_input = self.prepare_image_inputs() + inputs = processor(text=input_str, images=image_input, return_tensors="pt") + self.assertEqual(inputs[self.text_input_name].shape[-1], 117) + + def test_image_processor_defaults_preserved_by_image_kwargs(self): + """ + We use do_rescale=True, rescale_factor=-1 to ensure that image_processor kwargs are preserved in the processor. + We then check that the mean of the pixel_values is less than or equal to 0 after processing. + Since the original pixel_values are in [0, 255], this is a good indicator that the rescale_factor is indeed applied. + """ + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_components["image_processor"] = self.get_component( + "image_processor", do_rescale=True, rescale_factor=-1 + ) + processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="image") + image_input = self.prepare_image_inputs() + + inputs = processor(text=input_str, images=image_input, return_tensors="pt") + self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) + + def test_kwargs_overrides_default_tokenizer_kwargs(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_components["tokenizer"] = self.get_component("tokenizer", padding="longest") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + input_str = self.prepare_text_inputs(modality="image") + image_input = self.prepare_image_inputs() + inputs = processor( + text=input_str, images=image_input, return_tensors="pt", max_length=112, padding="max_length" + ) + self.assertEqual(inputs[self.text_input_name].shape[-1], 112) + + def test_kwargs_overrides_default_image_processor_kwargs(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_components["image_processor"] = self.get_component( + "image_processor", do_rescale=True, rescale_factor=1 + ) + processor_components["tokenizer"] = self.get_component("tokenizer", max_length=117, padding="max_length") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="image") + image_input = self.prepare_image_inputs() + + inputs = processor(text=input_str, images=image_input, do_rescale=True, rescale_factor=-1, return_tensors="pt") + self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) + + def test_unstructured_kwargs(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="image") + image_input = self.prepare_image_inputs() + inputs = processor( + text=input_str, + images=image_input, + return_tensors="pt", + do_rescale=True, + rescale_factor=-1, + padding="max_length", + max_length=76, + ) + + self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) + self.assertEqual(inputs[self.text_input_name].shape[-1], 76) + + def test_unstructured_kwargs_batched(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(batch_size=2, modality="image") + image_input = self.prepare_image_inputs(batch_size=2) + inputs = processor( + text=input_str, + images=image_input, + return_tensors="pt", + do_rescale=True, + rescale_factor=-1, + padding="longest", + max_length=76, + ) + + self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) + self.assertTrue( + len(inputs[self.text_input_name][0]) == len(inputs[self.text_input_name][1]) + and len(inputs[self.text_input_name][1]) < 76 + ) + + def test_doubly_passed_kwargs(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = [self.prepare_text_inputs(modality="image")] + image_input = self.prepare_image_inputs() + with self.assertRaises(ValueError): + _ = processor( + text=input_str, + images=image_input, + images_kwargs={"do_rescale": True, "rescale_factor": -1}, + do_rescale=True, + return_tensors="pt", + ) + + def test_args_overlap_kwargs(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_first = self.get_processor() + image_processor = processor_first.image_processor + image_processor.is_override = True + + with tempfile.TemporaryDirectory() as tmpdirname: + processor_first.save_pretrained(tmpdirname) + processor_second = self.processor_class.from_pretrained(tmpdirname, image_processor=image_processor) + self.assertTrue(processor_second.image_processor.is_override) + + def test_structured_kwargs_nested(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="image") + image_input = self.prepare_image_inputs() + + # Define the kwargs for each modality + all_kwargs = { + "common_kwargs": {"return_tensors": "pt"}, + "images_kwargs": {"do_rescale": True, "rescale_factor": -1}, + "text_kwargs": {"padding": "max_length", "max_length": 76}, + } + + inputs = processor(text=input_str, images=image_input, **all_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) + self.assertEqual(inputs[self.text_input_name].shape[-1], 76) + + def test_structured_kwargs_nested_from_dict(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + input_str = self.prepare_text_inputs(modality="image") + image_input = self.prepare_image_inputs() + + # Define the kwargs for each modality + all_kwargs = { + "common_kwargs": {"return_tensors": "pt"}, + "images_kwargs": {"do_rescale": True, "rescale_factor": -1}, + "text_kwargs": {"padding": "max_length", "max_length": 76}, + } + + inputs = processor(text=input_str, images=image_input, **all_kwargs) + self.assertLessEqual(inputs[self.images_input_name][0][0].mean(), 0) + self.assertEqual(inputs[self.text_input_name].shape[-1], 76) + + # text + audio kwargs testing + @require_torch + def test_tokenizer_defaults_preserved_by_kwargs_audio(self): + if "feature_extractor" not in self.processor_class.attributes: + self.skipTest(f"feature_extractor attribute not present in {self.processor_class}") + + feature_extractor = self.get_component("feature_extractor") + tokenizer = self.get_component("tokenizer", max_length=300, padding="max_length") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(tokenizer=tokenizer, feature_extractor=feature_extractor, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(batch_size=3, modality="audio") + raw_speech = floats_list((3, 1000)) + raw_speech = [np.asarray(audio) for audio in raw_speech] + inputs = processor(text=input_str, audio=raw_speech, return_tensors="pt") + self.assertEqual(len(inputs[self.text_input_name][0]), 300) + + @require_torch + def test_kwargs_overrides_default_tokenizer_kwargs_audio(self): + if "feature_extractor" not in self.processor_class.attributes: + self.skipTest(f"feature_extractor attribute not present in {self.processor_class}") + + feature_extractor = self.get_component("feature_extractor") + tokenizer = self.get_component("tokenizer", max_length=117) + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(tokenizer=tokenizer, feature_extractor=feature_extractor, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(batch_size=3, modality="audio") + raw_speech = floats_list((3, 1000)) + raw_speech = [np.asarray(audio) for audio in raw_speech] + inputs = processor(text=input_str, audio=raw_speech, return_tensors="pt", max_length=300, padding="max_length") + + self.assertEqual(len(inputs[self.text_input_name][0]), 300) + + @require_torch + def test_unstructured_kwargs_audio(self): + if "feature_extractor" not in self.processor_class.attributes: + self.skipTest(f"feature_extractor attribute not present in {self.processor_class}") + + feature_extractor = self.get_component("feature_extractor") + tokenizer = self.get_component("tokenizer") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(tokenizer=tokenizer, feature_extractor=feature_extractor, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(batch_size=3, modality="audio") + raw_speech = floats_list((3, 1000)) + raw_speech = [np.asarray(audio) for audio in raw_speech] + inputs = processor(text=input_str, audio=raw_speech, return_tensors="pt", max_length=300, padding="max_length") + + self.assertEqual(len(inputs[self.text_input_name][0]), 300) + + @require_torch + def test_doubly_passed_kwargs_audio(self): + if "feature_extractor" not in self.processor_class.attributes: + self.skipTest(f"feature_extractor attribute not present in {self.processor_class}") + + feature_extractor = self.get_component("feature_extractor") + tokenizer = self.get_component("tokenizer") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(tokenizer=tokenizer, feature_extractor=feature_extractor, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(batch_size=3, modality="audio") + raw_speech = floats_list((3, 1000)) + raw_speech = [np.asarray(audio) for audio in raw_speech] + with self.assertRaises(ValueError): + _ = processor( + text=input_str, + audio=raw_speech, + text_kwargs={"padding": "max_length"}, + padding="max_length", + ) + + @require_torch + @require_vision + def test_structured_kwargs_audio_nested(self): + if "feature_extractor" not in self.processor_class.attributes: + self.skipTest(f"feature_extractor attribute not present in {self.processor_class}") + + feature_extractor = self.get_component("feature_extractor") + tokenizer = self.get_component("tokenizer", max_length=117) + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(tokenizer=tokenizer, feature_extractor=feature_extractor, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(batch_size=3, modality="audio") + raw_speech = floats_list((3, 1000)) + raw_speech = [np.asarray(audio) for audio in raw_speech] + + # Define the kwargs for each modality + all_kwargs = { + "common_kwargs": {"return_tensors": "pt"}, + "text_kwargs": {"padding": "max_length", "max_length": 76}, + "audio_kwargs": {"padding": "max_length", "max_length": 300}, + } + + inputs = processor(text=input_str, audio=raw_speech, **all_kwargs) + self.assertEqual(len(inputs[self.text_input_name][0]), 76) + + def test_tokenizer_defaults_preserved_by_kwargs_video(self): + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_components["tokenizer"] = self.get_component("tokenizer", max_length=167, padding="max_length") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + input_str = self.prepare_text_inputs(modality="video") + video_input = self.prepare_video_inputs() + inputs = processor(text=input_str, videos=video_input, do_sample_frames=False, return_tensors="pt") + self.assertEqual(inputs[self.text_input_name].shape[-1], 167) + + def test_video_processor_defaults_preserved_by_video_kwargs(self): + """ + We use do_rescale=True, rescale_factor=-1 to ensure that image_processor kwargs are preserved in the processor. + We then check that the mean of the pixel_values is less than or equal to 0 after processing. + Since the original pixel_values are in [0, 255], this is a good indicator that the rescale_factor is indeed applied. + """ + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_components["video_processor"] = self.get_component( + "video_processor", do_rescale=True, rescale_factor=-1 + ) + processor_components["tokenizer"] = self.get_component("tokenizer", max_length=167, padding="max_length") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="video") + video_input = self.prepare_video_inputs() + + inputs = processor(text=input_str, videos=video_input, do_sample_frames=False, return_tensors="pt") + self.assertLessEqual(inputs[self.videos_input_name][0].mean(), 0) + + def test_kwargs_overrides_default_tokenizer_kwargs_video(self): + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_components["tokenizer"] = self.get_component("tokenizer", padding="longest") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + input_str = self.prepare_text_inputs(modality="video") + video_input = self.prepare_video_inputs() + inputs = processor( + text=input_str, + videos=video_input, + do_sample_frames=False, + return_tensors="pt", + max_length=162, + padding="max_length", + ) + self.assertEqual(inputs[self.text_input_name].shape[-1], 162) + + def test_kwargs_overrides_default_video_processor_kwargs(self): + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_components["video_processor"] = self.get_component( + "video_processor", do_rescale=True, rescale_factor=1 + ) + processor_components["tokenizer"] = self.get_component("tokenizer", max_length=167, padding="max_length") + processor_kwargs = self.prepare_processor_dict() + + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="video") + video_input = self.prepare_video_inputs() + + inputs = processor( + text=input_str, + videos=video_input, + do_sample_frames=False, + do_rescale=True, + rescale_factor=-1, + return_tensors="pt", + ) + self.assertLessEqual(inputs[self.videos_input_name][0].mean(), 0) + + def test_unstructured_kwargs_video(self): + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="video") + video_input = self.prepare_video_inputs() + inputs = processor( + text=input_str, + videos=video_input, + do_sample_frames=False, + return_tensors="pt", + do_rescale=True, + rescale_factor=-1, + padding="max_length", + max_length=176, + ) + + self.assertLessEqual(inputs[self.videos_input_name][0].mean(), 0) + self.assertEqual(inputs[self.text_input_name].shape[-1], 176) + + def test_unstructured_kwargs_batched_video(self): + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(batch_size=2, modality="video") + video_input = self.prepare_video_inputs(batch_size=2) + inputs = processor( + text=input_str, + videos=video_input, + do_sample_frames=False, + return_tensors="pt", + do_rescale=True, + rescale_factor=-1, + padding="longest", + max_length=176, + ) + + self.assertLessEqual(inputs[self.videos_input_name][0].mean(), 0) + self.assertTrue( + len(inputs[self.text_input_name][0]) == len(inputs[self.text_input_name][1]) + and len(inputs[self.text_input_name][1]) < 176 + ) + + def test_doubly_passed_kwargs_video(self): + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = [self.prepare_text_inputs(modality="video")] + video_input = self.prepare_video_inputs() + with self.assertRaises(ValueError): + _ = processor( + text=input_str, + videos=video_input, + do_sample_frames=False, + videos_kwargs={"do_rescale": True, "rescale_factor": -1}, + do_rescale=True, + return_tensors="pt", + ) + + def test_structured_kwargs_nested_video(self): + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="video") + video_input = self.prepare_video_inputs() + + # Define the kwargs for each modality + all_kwargs = { + "common_kwargs": {"return_tensors": "pt"}, + "videos_kwargs": {"do_rescale": True, "rescale_factor": -1, "do_sample_frames": False}, + "text_kwargs": {"padding": "max_length", "max_length": 176}, + } + + inputs = processor(text=input_str, videos=video_input, **all_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + self.assertLessEqual(inputs[self.videos_input_name][0].mean(), 0) + self.assertEqual(inputs[self.text_input_name].shape[-1], 176) + + def test_structured_kwargs_nested_from_dict_video(self): + if "video_processor" not in self.processor_class.attributes: + self.skipTest(f"video_processor attribute not present in {self.processor_class}") + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + input_str = self.prepare_text_inputs(modality="video") + video_input = self.prepare_video_inputs() + + # Define the kwargs for each modality + all_kwargs = { + "common_kwargs": {"return_tensors": "pt"}, + "videos_kwargs": {"do_rescale": True, "rescale_factor": -1, "do_sample_frames": False}, + "text_kwargs": {"padding": "max_length", "max_length": 176}, + } + + inputs = processor(text=input_str, videos=video_input, **all_kwargs) + self.assertLessEqual(inputs[self.videos_input_name][0].mean(), 0) + self.assertEqual(inputs[self.text_input_name].shape[-1], 176) + + # TODO: the same test, but for audio + text processors that have strong overlap in kwargs + # TODO (molbap) use the same structure of attribute kwargs for other tests to avoid duplication + def test_overlapping_text_image_kwargs_handling(self): + if "image_processor" not in self.processor_class.attributes: + self.skipTest(f"image_processor attribute not present in {self.processor_class}") + + processor_components = self.prepare_components() + processor = self.processor_class(**processor_components) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(modality="image") + image_input = self.prepare_image_inputs() + + with self.assertRaises(ValueError): + _ = processor( + text=input_str, + images=image_input, + return_tensors="pt", + padding="max_length", + text_kwargs={"padding": "do_not_pad"}, + ) + + def test_overlapping_text_audio_kwargs_handling(self): + """ + Checks that `padding`, or any other overlap arg between audio extractor and tokenizer + is be passed to only text and ignored for audio for BC purposes + """ + if "feature_extractor" not in self.processor_class.attributes: + self.skipTest(f"feature_extractor attribute not present in {self.processor_class}") + + processor_components = self.prepare_components() + processor_kwargs = self.prepare_processor_dict() + processor = self.processor_class(**processor_components, **processor_kwargs) + self.skip_processor_without_typed_kwargs(processor) + + input_str = self.prepare_text_inputs(batch_size=3, modality="audio") + audio_lengths = [4000, 8000, 16000, 32000] + raw_speech = [np.asarray(audio)[:length] for audio, length in zip(floats_list((3, 32_000)), audio_lengths)] + + # padding = True should not raise an error and will if the audio processor popped its value to None + _ = processor(text=input_str, audio=raw_speech, padding=True, return_tensors="pt") + + def test_prepare_and_validate_optional_call_args(self): + processor = self.get_processor() + optional_call_args_name = getattr(processor, "optional_call_args", []) + num_optional_call_args = len(optional_call_args_name) + if num_optional_call_args == 0: + self.skipTest("No optional call args") + # test all optional call args are given + optional_call_args = processor.prepare_and_validate_optional_call_args( + *(f"optional_{i}" for i in range(num_optional_call_args)) + ) + self.assertEqual( + optional_call_args, {arg_name: f"optional_{i}" for i, arg_name in enumerate(optional_call_args_name)} + ) + # test only one optional call arg is given + optional_call_args = processor.prepare_and_validate_optional_call_args("optional_1") + self.assertEqual(optional_call_args, {optional_call_args_name[0]: "optional_1"}) + # test no optional call arg is given + optional_call_args = processor.prepare_and_validate_optional_call_args() + self.assertEqual(optional_call_args, {}) + # test too many optional call args are given + with self.assertRaises(ValueError): + processor.prepare_and_validate_optional_call_args( + *(f"optional_{i}" for i in range(num_optional_call_args + 1)) + ) + + def test_chat_template_save_loading(self): + processor = self.processor_class.from_pretrained(self.tmpdirname) + signature = inspect.signature(processor.__init__) + if "chat_template" not in {*signature.parameters.keys()}: + self.skipTest("Processor doesn't accept chat templates at input") + + existing_tokenizer_template = getattr(processor.tokenizer, "chat_template", None) + processor.chat_template = "test template" + with tempfile.TemporaryDirectory() as tmpdirname: + processor.save_pretrained(tmpdirname, save_jinja_files=False) + self.assertTrue(Path(tmpdirname, "chat_template.json").is_file()) + self.assertFalse(Path(tmpdirname, "chat_template.jinja").is_file()) + reloaded_processor = self.processor_class.from_pretrained(tmpdirname) + self.assertEqual(processor.chat_template, reloaded_processor.chat_template) + # When we don't use single-file chat template saving, processor and tokenizer chat templates + # should remain separate + self.assertEqual(getattr(reloaded_processor.tokenizer, "chat_template", None), existing_tokenizer_template) + + with tempfile.TemporaryDirectory() as tmpdirname: + processor.save_pretrained(tmpdirname) + self.assertTrue(Path(tmpdirname, "chat_template.jinja").is_file()) + self.assertFalse(Path(tmpdirname, "chat_template.json").is_file()) + self.assertFalse(Path(tmpdirname, "additional_chat_templates").is_dir()) + reloaded_processor = self.processor_class.from_pretrained(tmpdirname) + self.assertEqual(processor.chat_template, reloaded_processor.chat_template) + # When we save as single files, tokenizers and processors share a chat template, which means + # the reloaded tokenizer should get the chat template as well + self.assertEqual(reloaded_processor.chat_template, reloaded_processor.tokenizer.chat_template) + + with tempfile.TemporaryDirectory() as tmpdirname: + processor.chat_template = {"default": "a", "secondary": "b"} + processor.save_pretrained(tmpdirname) + self.assertTrue(Path(tmpdirname, "chat_template.jinja").is_file()) + self.assertFalse(Path(tmpdirname, "chat_template.json").is_file()) + self.assertTrue(Path(tmpdirname, "additional_chat_templates").is_dir()) + reloaded_processor = self.processor_class.from_pretrained(tmpdirname) + self.assertEqual(processor.chat_template, reloaded_processor.chat_template) + # When we save as single files, tokenizers and processors share a chat template, which means + # the reloaded tokenizer should get the chat template as well + self.assertEqual(reloaded_processor.chat_template, reloaded_processor.tokenizer.chat_template) + + with self.assertRaises(ValueError): + # Saving multiple templates in the legacy format is not permitted + with tempfile.TemporaryDirectory() as tmpdirname: + processor.chat_template = {"default": "a", "secondary": "b"} + processor.save_pretrained(tmpdirname, save_jinja_files=False) + + @require_torch + def _test_apply_chat_template( + self, + modality: str, + batch_size: int, + return_tensors: str, + input_name: str, + processor_name: str, + input_data: list[str], + ): + processor = self.get_processor() + if processor.chat_template is None: + self.skipTest("Processor has no chat template") + + if processor_name not in self.processor_class.attributes: + self.skipTest(f"{processor_name} attribute not present in {self.processor_class}") + + # some models have only Fast image processor + if getattr(processor, processor_name).__class__.__name__.endswith("Fast"): + return_tensors = "pt" + + batch_messages = [ + [ + { + "role": "user", + "content": [{"type": "text", "text": "Describe this."}], + }, + ] + ] * batch_size + + # Test that jinja can be applied + formatted_prompt = processor.apply_chat_template(batch_messages, add_generation_prompt=True, tokenize=False) + self.assertEqual(len(formatted_prompt), batch_size) + + # Test that tokenizing with template and directly with `self.tokenizer` gives same output + formatted_prompt_tokenized = processor.apply_chat_template( + batch_messages, add_generation_prompt=True, tokenize=True, return_tensors=return_tensors + ) + add_special_tokens = True + if processor.tokenizer.bos_token is not None and formatted_prompt[0].startswith(processor.tokenizer.bos_token): + add_special_tokens = False + tok_output = processor.tokenizer( + formatted_prompt, return_tensors=return_tensors, add_special_tokens=add_special_tokens + ) + expected_output = tok_output.input_ids + self.assertListEqual(expected_output.tolist(), formatted_prompt_tokenized.tolist()) + + # Test that kwargs passed to processor's `__call__` are actually used + tokenized_prompt_100 = processor.apply_chat_template( + batch_messages, + add_generation_prompt=True, + tokenize=True, + padding="max_length", + truncation=True, + return_tensors=return_tensors, + max_length=100, + ) + self.assertEqual(len(tokenized_prompt_100[0]), 100) + + # Test that `return_dict=True` returns text related inputs in the dict + out_dict_text = processor.apply_chat_template( + batch_messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors=return_tensors, + ) + self.assertTrue(all(key in out_dict_text for key in ["input_ids", "attention_mask"])) + self.assertEqual(len(out_dict_text["input_ids"]), batch_size) + self.assertEqual(len(out_dict_text["attention_mask"]), batch_size) + + # Test that with modality URLs and `return_dict=True`, we get modality inputs in the dict + for idx, url in enumerate(input_data[:batch_size]): + batch_messages[idx][0]["content"] = [batch_messages[idx][0]["content"][0], {"type": modality, "url": url}] + + out_dict = processor.apply_chat_template( + batch_messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors=return_tensors, + num_frames=2, # by default no more than 2 frames, otherwise too slow + ) + input_name = getattr(self, input_name) + self.assertTrue(input_name in out_dict) + self.assertEqual(len(out_dict["input_ids"]), batch_size) + self.assertEqual(len(out_dict["attention_mask"]), batch_size) + self.assertEqual(len(out_dict[input_name]), batch_size) + + return_tensor_to_type = {"pt": torch.Tensor, "np": np.ndarray, None: list} + for k in out_dict: + self.assertIsInstance(out_dict[k], return_tensor_to_type[return_tensors]) + + # Test continue from final message + assistant_message = { + "role": "assistant", + "content": [{"type": "text", "text": "It is the sound of"}], + } + for idx, url in enumerate(input_data[:batch_size]): + batch_messages[idx] = batch_messages[idx] + [assistant_message] + continue_prompt = processor.apply_chat_template(batch_messages, continue_final_message=True, tokenize=False) + for prompt in continue_prompt: + self.assertTrue(prompt.endswith("It is the sound of")) # no `eos` token at the end + + @require_librosa + @parameterized.expand([(1, "np"), (1, "pt"), (2, "np"), (2, "pt")]) + def test_apply_chat_template_audio(self, batch_size: int, return_tensors: str): + self._test_apply_chat_template( + "audio", batch_size, return_tensors, "audio_input_name", "feature_extracttor", MODALITY_INPUT_DATA["audio"] + ) + + @require_av + @parameterized.expand([(1, "pt"), (2, "pt"), (3, "pt")]) # video processor supports only torchvision + def test_apply_chat_template_video(self, batch_size: int, return_tensors: str): + self._test_apply_chat_template( + "video", batch_size, return_tensors, "videos_input_name", "video_processor", MODALITY_INPUT_DATA["videos"] + ) + + @parameterized.expand([(1, "pt"), (2, "pt")]) # fast image processors supports only torchvision + def test_apply_chat_template_image(self, batch_size: int, return_tensors: str): + self._test_apply_chat_template( + "image", batch_size, return_tensors, "images_input_name", "image_processor", MODALITY_INPUT_DATA["images"] + ) + + @require_torch + def test_apply_chat_template_video_frame_sampling(self): + processor = self.get_processor() + + if processor.chat_template is None: + self.skipTest("Processor has no chat template") + + signature = inspect.signature(processor.__call__) + if "videos" not in {*signature.parameters.keys()} or ( + signature.parameters.get("videos") is not None + and signature.parameters["videos"].annotation == inspect._empty + ): + self.skipTest("Processor doesn't accept videos at input") + + messages = [ + [ + { + "role": "user", + "content": [ + { + "type": "video", + "url": "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/720/Big_Buck_Bunny_720_10s_10MB.mp4", + }, + {"type": "text", "text": "What is shown in this video?"}, + ], + }, + ] + ] + + num_frames = 3 + out_dict_with_video = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + num_frames=num_frames, + return_tensors="pt", + ) + self.assertTrue(self.videos_input_name in out_dict_with_video) + self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 1) + self.assertEqual(len(out_dict_with_video[self.videos_input_name][0]), num_frames) + + # Load with `fps` arg + fps = 1 + out_dict_with_video = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + fps=fps, + return_tensors="pt", + ) + self.assertTrue(self.videos_input_name in out_dict_with_video) + self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 1) + self.assertEqual(len(out_dict_with_video[self.videos_input_name][0]), fps * 10) + + # Whan `do_sample_frames=False` no sampling is done and whole video is loaded, even if number of frames is passed + fps = 1 + out_dict_with_video = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + do_sample_frames=False, + fps=fps, + return_tensors="pt", + ) + self.assertTrue(self.videos_input_name in out_dict_with_video) + self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 1) + self.assertEqual(len(out_dict_with_video[self.videos_input_name][0]), 300) + + # Load with `fps` and `num_frames` args, should raise an error + with self.assertRaises(ValueError): + out_dict_with_video = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + fps=fps, + num_frames=num_frames, + ) + + # Load without any arg should load the whole video + out_dict_with_video = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + ) + self.assertTrue(self.videos_input_name in out_dict_with_video) + self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 1) + self.assertEqual(len(out_dict_with_video[self.videos_input_name][0]), 300) + + # Load video as a list of frames (i.e. images). NOTE: each frame should have same size + # because we assume they come from one video + messages[0][0]["content"][0] = { + "type": "video", + "url": [ + "https://www.ilankelman.org/stopsigns/australia.jpg", + "https://www.ilankelman.org/stopsigns/australia.jpg", + ], + } + out_dict_with_video = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + ) + self.assertTrue(self.videos_input_name in out_dict_with_video) + self.assertEqual(len(out_dict_with_video[self.videos_input_name]), 1) + self.assertEqual(len(out_dict_with_video[self.videos_input_name][0]), 2) + + @require_librosa + @require_av + def test_chat_template_audio_from_video(self): + processor = self.get_processor() + if processor.chat_template is None: + self.skipTest("Processor has no chat template") + + signature = inspect.signature(processor.__call__) + if "videos" not in {*signature.parameters.keys()} or ( + signature.parameters.get("videos") is not None + and signature.parameters["videos"].annotation == inspect._empty + ): + self.skipTest(f"{self.processor_class} does not support video inputs") + + if "feature_extractor" not in self.processor_class.attributes: + self.skipTest(f"feature_extractor attribute not present in {self.processor_class}") + + video_file_path = hf_hub_download( + repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset" + ) + messages = [ + { + "role": "user", + "content": [ + {"type": "video", "path": video_file_path}, + {"type": "text", "text": "Which of these animals is making the sound?"}, + ], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "It is a cow."}], + }, + { + "role": "user", + "content": [ + {"type": "text", "text": "Tell me all about this animal."}, + ], + }, + ] + + formatted_prompt = processor.apply_chat_template([messages], add_generation_prompt=True, tokenize=False) + self.assertEqual(len(formatted_prompt), 1) # batch size=1 + + out_dict = processor.apply_chat_template( + messages, + add_generation_prompt=True, + tokenize=True, + return_dict=True, + return_tensors="np", + load_audio_from_video=True, + ) + self.assertTrue(self.audio_input_name in out_dict) + self.assertTrue(self.videos_input_name in out_dict) + + # should always have input_ids and attention_mask + self.assertEqual(len(out_dict["input_ids"]), 1) # batch-size=1 + self.assertEqual(len(out_dict["attention_mask"]), 1) # batch-size=1 + self.assertEqual(len(out_dict[self.audio_input_name]), 1) # 1 audio in the conversation + self.assertEqual(len(out_dict[self.videos_input_name]), 1) # 1 video in the conversation + + def test_chat_template_jinja_kwargs(self): + """Tests that users can pass any kwargs and they will be used in jinja templates.""" + processor = self.get_processor() + if processor.chat_template is None: + self.skipTest("Processor has no chat template") + + messages = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "Which of these animals is making the sound?"}, + ], + }, + { + "role": "assistant", + "content": [{"type": "text", "text": "It is a cow."}], + }, + ] + + dummy_template = ( + "{% for message in messages %}" + "{% if add_system_prompt %}" + "{{'You are a helpful assistant.'}}" + "{% endif %}" + "{% if (message['role'] != 'assistant') %}" + "{{'<|special_start|>' + message['role'] + '\n' + message['content'][0]['text'] + '<|special_end|>' + '\n'}}" + "{% elif (message['role'] == 'assistant')%}" + "{{'<|special_start|>' + message['role'] + '\n'}}" + "{{message['content'][0]['text'] + '<|special_end|>' + '\n'}}" + "{% endif %}" + "{% endfor %}" + ) + + formatted_prompt = processor.apply_chat_template( + messages, add_system_prompt=True, tokenize=False, chat_template=dummy_template + ) + expected_prompt = "You are a helpful assistant.<|special_start|>user\nWhich of these animals is making the sound?<|special_end|>\nYou are a helpful assistant.<|special_start|>assistant\nIt is a cow.<|special_end|>\n" + self.assertEqual(formatted_prompt, expected_prompt) + + @require_torch + def test_apply_chat_template_assistant_mask(self): + processor = self.get_processor() + + if processor.chat_template is None: + self.skipTest("Processor has no chat template") + + messages = [ + [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What is the capital of France?"}, + ], + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": "The capital of France is Paris."}, + ], + }, + { + "role": "user", + "content": [ + {"type": "text", "text": "What about Italy?"}, + ], + }, + { + "role": "assistant", + "content": [ + {"type": "text", "text": "The capital of Italy is Rome."}, + ], + }, + ] + ] + + dummy_template = ( + "{% for message in messages %}" + "{% if (message['role'] != 'assistant') %}" + "{{'<|special_start|>' + message['role'] + '\n' + message['content'][0]['text'] + '<|special_end|>' + '\n'}}" + "{% elif (message['role'] == 'assistant')%}" + "{{'<|special_start|>' + message['role'] + '\n'}}" + "{% generation %}" + "{{message['content'][0]['text'] + '<|special_end|>' + '\n'}}" + "{% endgeneration %}" + "{% endif %}" + "{% endfor %}" + ) + + inputs = processor.apply_chat_template( + messages, + add_generation_prompt=False, + tokenize=True, + return_dict=True, + return_tensors="pt", + return_assistant_tokens_mask=True, + chat_template=dummy_template, + ) + self.assertTrue("assistant_masks" in inputs) + self.assertEqual(len(inputs["assistant_masks"]), len(inputs["input_ids"])) + + mask = inputs["assistant_masks"].bool() + assistant_ids = inputs["input_ids"][mask] + + assistant_text = ( + "The capital of France is Paris.<|special_end|>\nThe capital of Italy is Rome.<|special_end|>\n" + ) + + # Some tokenizers add extra spaces which aren't then removed when decoding, so we need to check token ids + # if we can't get identical text outputs + text_is_same = assistant_text == processor.decode(assistant_ids, clean_up_tokenization_spaces=True) + ids_is_same = processor.tokenizer.encode(assistant_text, add_special_tokens=False), assistant_ids.tolist() + self.assertTrue(text_is_same or ids_is_same) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_sequence_feature_extraction_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_sequence_feature_extraction_common.py new file mode 100644 index 0000000000000000000000000000000000000000..6fd55978e4cef7f436138aa5b56ccf89219cae1f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_sequence_feature_extraction_common.py @@ -0,0 +1,392 @@ +# Copyright 2021 HuggingFace 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. + + +import numpy as np + +from transformers import BatchFeature +from transformers.testing_utils import require_torch + +from .test_feature_extraction_common import FeatureExtractionSavingTestMixin + + +class SequenceFeatureExtractionTestMixin(FeatureExtractionSavingTestMixin): + # to overwrite at feature extractactor specific tests + feat_extract_tester = None + feature_extraction_class = None + + @property + def feat_extract_dict(self): + return self.feat_extract_tester.prepare_feat_extract_dict() + + def test_feat_extract_common_properties(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + self.assertTrue(hasattr(feat_extract, "feature_size")) + self.assertTrue(hasattr(feat_extract, "sampling_rate")) + self.assertTrue(hasattr(feat_extract, "padding_value")) + + def test_batch_feature(self): + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + self.assertTrue(all(len(x) == len(y) for x, y in zip(speech_inputs, processed_features[input_name]))) + + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) + processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="np") + + batch_features_input = processed_features[input_name] + + if len(batch_features_input.shape) < 3: + batch_features_input = batch_features_input[:, :, None] + + self.assertTrue( + batch_features_input.shape + == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) + ) + + @require_torch + def test_batch_feature_pt(self): + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(equal_length=True) + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}, tensor_type="pt") + + batch_features_input = processed_features[input_name] + + if len(batch_features_input.shape) < 3: + batch_features_input = batch_features_input[:, :, None] + + self.assertTrue( + batch_features_input.shape + == (self.feat_extract_tester.batch_size, len(speech_inputs[0]), self.feat_extract_tester.feature_size) + ) + + def _check_padding(self, numpify=False): + def _inputs_have_equal_length(input): + length = len(input[0]) + for input_slice in input[1:]: + if len(input_slice) != length: + return False + return True + + def _inputs_are_equal(input_1, input_2): + if len(input_1) != len(input_2): + return False + + for input_slice_1, input_slice_2 in zip(input_1, input_2): + if not np.allclose(np.asarray(input_slice_1), np.asarray(input_slice_2), atol=1e-3): + return False + return True + + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(numpify=numpify) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + pad_diff = self.feat_extract_tester.seq_length_diff + pad_max_length = self.feat_extract_tester.max_seq_length + pad_diff + pad_min_length = self.feat_extract_tester.min_seq_length + batch_size = self.feat_extract_tester.batch_size + feature_size = self.feat_extract_tester.feature_size + + # test padding for list[int] + numpy + input_1 = feat_extract.pad(processed_features, padding=False) + input_1 = input_1[input_name] + + input_2 = feat_extract.pad(processed_features, padding="longest") + input_2 = input_2[input_name] + + input_3 = feat_extract.pad(processed_features, padding="max_length", max_length=len(speech_inputs[-1])) + input_3 = input_3[input_name] + + input_4 = feat_extract.pad(processed_features, padding="longest", return_tensors="np") + input_4 = input_4[input_name] + + # max_length parameter has to be provided when setting `padding="max_length"` + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, padding="max_length")[input_name] + + input_5 = feat_extract.pad( + processed_features, padding="max_length", max_length=pad_max_length, return_tensors="np" + ) + input_5 = input_5[input_name] + + self.assertFalse(_inputs_have_equal_length(input_1)) + self.assertTrue(_inputs_have_equal_length(input_2)) + self.assertTrue(_inputs_have_equal_length(input_3)) + self.assertTrue(_inputs_are_equal(input_2, input_3)) + self.assertTrue(len(input_1[0]) == pad_min_length) + self.assertTrue(len(input_1[1]) == pad_min_length + pad_diff) + self.assertTrue(input_4.shape[:2] == (batch_size, len(input_3[0]))) + self.assertTrue(input_5.shape[:2] == (batch_size, pad_max_length)) + + if feature_size > 1: + self.assertTrue(input_4.shape[2] == input_5.shape[2] == feature_size) + + # test padding for `pad_to_multiple_of` for list[int] + numpy + input_6 = feat_extract.pad(processed_features, pad_to_multiple_of=10) + input_6 = input_6[input_name] + + input_7 = feat_extract.pad(processed_features, padding="longest", pad_to_multiple_of=10) + input_7 = input_7[input_name] + + input_8 = feat_extract.pad( + processed_features, padding="max_length", pad_to_multiple_of=10, max_length=pad_max_length + ) + input_8 = input_8[input_name] + + input_9 = feat_extract.pad( + processed_features, + padding="max_length", + pad_to_multiple_of=10, + max_length=pad_max_length, + return_tensors="np", + ) + input_9 = input_9[input_name] + + self.assertTrue(all(len(x) % 10 == 0 for x in input_6)) + self.assertTrue(_inputs_are_equal(input_6, input_7)) + + expected_mult_pad_length = pad_max_length if pad_max_length % 10 == 0 else (pad_max_length // 10 + 1) * 10 + self.assertTrue(all(len(x) == expected_mult_pad_length for x in input_8)) + self.assertEqual(input_9.shape[:2], (batch_size, expected_mult_pad_length)) + + if feature_size > 1: + self.assertTrue(input_9.shape[2] == feature_size) + + # Check padding value is correct + padding_vector_sum = (np.ones(self.feat_extract_tester.feature_size) * feat_extract.padding_value).sum() + self.assertTrue( + abs(np.asarray(input_2[0])[pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) + < 1e-3 + ) + self.assertTrue( + abs( + np.asarray(input_2[1])[pad_min_length + pad_diff :].sum() + - padding_vector_sum * (pad_max_length - pad_min_length - pad_diff) + ) + < 1e-3 + ) + self.assertTrue( + abs( + np.asarray(input_2[2])[pad_min_length + 2 * pad_diff :].sum() + - padding_vector_sum * (pad_max_length - pad_min_length - 2 * pad_diff) + ) + < 1e-3 + ) + self.assertTrue( + abs(input_5[0, pad_min_length:].sum() - padding_vector_sum * (pad_max_length - pad_min_length)) < 1e-3 + ) + self.assertTrue( + abs(input_9[0, pad_min_length:].sum() - padding_vector_sum * (expected_mult_pad_length - pad_min_length)) + < 1e-3 + ) + + def _check_truncation(self, numpify=False): + def _inputs_have_equal_length(input): + length = len(input[0]) + for input_slice in input[1:]: + if len(input_slice) != length: + return False + return True + + def _inputs_are_equal(input_1, input_2): + if len(input_1) != len(input_2): + return False + + for input_slice_1, input_slice_2 in zip(input_1, input_2): + if not np.allclose(np.asarray(input_slice_1), np.asarray(input_slice_2), atol=1e-3): + return False + return True + + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common(numpify=numpify) + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + # truncate to smallest + input_1 = feat_extract.pad( + processed_features, padding="max_length", max_length=len(speech_inputs[0]), truncation=True + ) + input_1 = input_1[input_name] + + input_2 = feat_extract.pad(processed_features, padding="max_length", max_length=len(speech_inputs[0])) + input_2 = input_2[input_name] + + self.assertTrue(_inputs_have_equal_length(input_1)) + self.assertFalse(_inputs_have_equal_length(input_2)) + + # truncate to smallest with np + input_3 = feat_extract.pad( + processed_features, + padding="max_length", + max_length=len(speech_inputs[0]), + return_tensors="np", + truncation=True, + ) + input_3 = input_3[input_name] + + input_4 = feat_extract.pad( + processed_features, padding="max_length", max_length=len(speech_inputs[0]), return_tensors="np" + ) + input_4 = input_4[input_name] + + self.assertTrue(_inputs_have_equal_length(input_3)) + self.assertTrue(input_3.shape[1] == len(speech_inputs[0])) + + # since truncation forces padding to be smaller than longest input + # function can't return `np.ndarray`, but has to return list + self.assertFalse(_inputs_have_equal_length(input_4)) + + # truncate to middle + input_5 = feat_extract.pad( + processed_features, + padding="max_length", + max_length=len(speech_inputs[1]), + truncation=True, + return_tensors="np", + ) + input_5 = input_5[input_name] + + input_6 = feat_extract.pad( + processed_features, padding="max_length", max_length=len(speech_inputs[1]), truncation=True + ) + input_6 = input_6[input_name] + + input_7 = feat_extract.pad( + processed_features, padding="max_length", max_length=len(speech_inputs[1]), return_tensors="np" + ) + input_7 = input_7[input_name] + + self.assertTrue(input_5.shape[1] == len(speech_inputs[1])) + self.assertTrue(_inputs_have_equal_length(input_5)) + self.assertTrue(_inputs_have_equal_length(input_6)) + self.assertTrue(_inputs_are_equal(input_5, input_6)) + + # since truncation forces padding to be smaller than longest input + # function can't return `np.ndarray`, but has to return list + self.assertFalse(_inputs_have_equal_length(input_7)) + self.assertTrue(len(input_7[-1]) == len(speech_inputs[-1])) + + # padding has to be max_length when setting `truncation=True` + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, truncation=True)[input_name] + + # padding has to be max_length when setting `truncation=True` + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, padding="longest", truncation=True)[input_name] + + # padding has to be max_length when setting `truncation=True` + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, padding="longest", truncation=True)[input_name] + + # max_length parameter has to be provided when setting `truncation=True` and padding="max_length" + with self.assertRaises(ValueError): + feat_extract.pad(processed_features, padding="max_length", truncation=True)[input_name] + + # test truncation for `pad_to_multiple_of` for list[int] + numpy + pad_to_multiple_of = 12 + input_8 = feat_extract.pad( + processed_features, + padding="max_length", + max_length=len(speech_inputs[0]), + pad_to_multiple_of=pad_to_multiple_of, + truncation=True, + ) + input_8 = input_8[input_name] + + input_9 = feat_extract.pad( + processed_features, + padding="max_length", + max_length=len(speech_inputs[0]), + pad_to_multiple_of=pad_to_multiple_of, + ) + input_9 = input_9[input_name] + + # retrieve expected_length as multiple of pad_to_multiple_of + expected_length = len(speech_inputs[0]) + if expected_length % pad_to_multiple_of != 0: + expected_length = ((len(speech_inputs[0]) // pad_to_multiple_of) + 1) * pad_to_multiple_of + + self.assertTrue(len(input_8[0]) == expected_length) + self.assertTrue(_inputs_have_equal_length(input_8)) + self.assertFalse(_inputs_have_equal_length(input_9)) + + def test_padding_from_list(self): + self._check_padding(numpify=False) + + def test_padding_from_array(self): + self._check_padding(numpify=True) + + def test_truncation_from_list(self): + self._check_truncation(numpify=False) + + def test_truncation_from_array(self): + self._check_truncation(numpify=True) + + @require_torch + def test_padding_accepts_tensors_pt(self): + feat_extract = self.feature_extraction_class(**self.feat_extract_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + input_name = feat_extract.model_input_names[0] + + processed_features = BatchFeature({input_name: speech_inputs}) + + input_np = feat_extract.pad(processed_features, padding="longest", return_tensors="np")[input_name] + input_pt = feat_extract.pad(processed_features, padding="longest", return_tensors="pt")[input_name] + + self.assertTrue(abs(input_np.astype(np.float32).sum() - input_pt.numpy().astype(np.float32).sum()) < 1e-2) + + def test_attention_mask(self): + feat_dict = self.feat_extract_dict + feat_dict["return_attention_mask"] = True + feat_extract = self.feature_extraction_class(**feat_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + input_lengths = [len(x) for x in speech_inputs] + input_name = feat_extract.model_input_names[0] + + processed = BatchFeature({input_name: speech_inputs}) + + processed = feat_extract.pad(processed, padding="longest", return_tensors="np") + self.assertIn("attention_mask", processed) + self.assertListEqual(list(processed.attention_mask.shape), list(processed[input_name].shape[:2])) + self.assertListEqual(processed.attention_mask.sum(-1).tolist(), input_lengths) + + def test_attention_mask_with_truncation(self): + feat_dict = self.feat_extract_dict + feat_dict["return_attention_mask"] = True + feat_extract = self.feature_extraction_class(**feat_dict) + speech_inputs = self.feat_extract_tester.prepare_inputs_for_common() + input_lengths = [len(x) for x in speech_inputs] + input_name = feat_extract.model_input_names[0] + + processed = BatchFeature({input_name: speech_inputs}) + max_length = min(input_lengths) + + processed_pad = feat_extract.pad( + processed, padding="max_length", max_length=max_length, truncation=True, return_tensors="np" + ) + self.assertIn("attention_mask", processed_pad) + self.assertListEqual( + list(processed_pad.attention_mask.shape), [processed_pad[input_name].shape[0], max_length] + ) + self.assertListEqual( + processed_pad.attention_mask[:, :max_length].sum(-1).tolist(), [max_length for x in speech_inputs] + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_tokenization_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_tokenization_common.py new file mode 100644 index 0000000000000000000000000000000000000000..b70a7786405a853508da2a19ea643803b446b37a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_tokenization_common.py @@ -0,0 +1,4692 @@ +# Copyright 2019 HuggingFace 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. + +import copy +import functools +import inspect +import itertools +import json +import os +import pickle +import re +import shutil +import tempfile +import traceback +import unittest +from collections import OrderedDict +from functools import lru_cache +from itertools import takewhile +from pathlib import Path +from typing import TYPE_CHECKING, Any, Optional, Union + +from parameterized import parameterized + +from transformers import ( + AlbertTokenizer, + AlbertTokenizerFast, + BertTokenizer, + BertTokenizerFast, + PreTrainedTokenizer, + PreTrainedTokenizerBase, + PreTrainedTokenizerFast, + SpecialTokensMixin, + Trainer, + TrainingArguments, + is_torch_available, + logging, +) +from transformers.testing_utils import ( + check_json_file_has_correct_format, + get_tests_dir, + require_jinja, + require_read_token, + require_tokenizers, + require_torch, + run_test_in_subprocess, + slow, +) +from transformers.tokenization_utils import AddedToken + + +if is_torch_available(): + import torch + import torch.nn as nn + + +if TYPE_CHECKING: + from transformers import PretrainedConfig, PreTrainedModel, TFPreTrainedModel + + +def use_cache_if_possible(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + use_cache = kwargs.pop("use_cache", True) + + underline_func = func + if "functools" in str(func): + underline_func = func.__wrapped__ + + if not use_cache: + return underline_func(*args, **kwargs) + if any(not arg.__hash__ for arg in args): + return underline_func(*args, **kwargs) + elif any(not kwarg.__hash__ for kwarg in kwargs.values()): + return underline_func(*args, **kwargs) + + cached = func(*args, **kwargs) + copied = copy.deepcopy(cached) + + if hasattr(copied, "_tokenizer") and "tests.models.clip.test_tokenization_clip.CLIPTokenizationTest" in str( + args[0] + ): + copied._tokenizer = cached._tokenizer + + if hasattr(copied, "sp_model"): + copied.sp_model = cached.sp_model + + return copied + + return wrapper + + +logger = logging.get_logger(__name__) + +NON_ENGLISH_TAGS = ["chinese", "dutch", "french", "finnish", "german", "multilingual"] + +SMALL_TRAINING_CORPUS = [ + ["This is the first sentence.", "This is the second one."], + ["This sentence (contains #) over symbols and numbers 12 3.", "But not this one."], +] + + +def filter_non_english(_, pretrained_name: str): + """Filter all the model for non-english language""" + return not any(lang in pretrained_name for lang in NON_ENGLISH_TAGS) + + +def filter_roberta_detectors(_, pretrained_name: str): + return "detector" not in pretrained_name + + +def merge_model_tokenizer_mappings( + model_mapping: dict["PretrainedConfig", Union["PreTrainedModel", "TFPreTrainedModel"]], + tokenizer_mapping: dict["PretrainedConfig", tuple["PreTrainedTokenizer", "PreTrainedTokenizerFast"]], +) -> dict[ + Union["PreTrainedTokenizer", "PreTrainedTokenizerFast"], + tuple["PretrainedConfig", Union["PreTrainedModel", "TFPreTrainedModel"]], +]: + configurations = list(model_mapping.keys()) + model_tokenizer_mapping = OrderedDict([]) + + for configuration in configurations: + if configuration in model_mapping and configuration in tokenizer_mapping: + model = model_mapping[configuration] + tokenizer = tokenizer_mapping[configuration][0] + tokenizer_fast = tokenizer_mapping[configuration][1] + + if tokenizer is not None: + if configuration.__name__.startswith(tokenizer.__name__.replace("Tokenizer", "")): + model_tokenizer_mapping.update({tokenizer: (configuration, model)}) + if tokenizer_fast is not None: + if configuration.__name__.startswith(tokenizer_fast.__name__.replace("TokenizerFast", "")): + model_tokenizer_mapping.update({tokenizer_fast: (configuration, model)}) + + return model_tokenizer_mapping + + +def _test_subword_regularization_tokenizer(in_queue, out_queue, timeout): + error = None + + try: + inputs = in_queue.get(timeout=timeout) + tokenizer = inputs["tokenizer"] + sp_model_kwargs = inputs["sp_model_kwargs"] + test_sentencepiece_ignore_case = inputs["test_sentencepiece_ignore_case"] + + unittest.TestCase().assertTrue(hasattr(tokenizer, "sp_model_kwargs")) + unittest.TestCase().assertIsNotNone(tokenizer.sp_model_kwargs) + unittest.TestCase().assertTrue(isinstance(tokenizer.sp_model_kwargs, dict)) + unittest.TestCase().assertDictEqual(tokenizer.sp_model_kwargs, sp_model_kwargs) + check_subword_sampling(tokenizer, test_sentencepiece_ignore_case=test_sentencepiece_ignore_case) + + except Exception: + error = f"{traceback.format_exc()}" + + results = {"error": error} + out_queue.put(results, timeout=timeout) + out_queue.join() + + +def check_subword_sampling( + tokenizer: PreTrainedTokenizer, + text: Optional[str] = None, + test_sentencepiece_ignore_case: bool = True, +) -> None: + """ + Check if the tokenizer generates different results when subword regularization is enabled. + + Subword regularization augments training data with subword sampling. + This has a random component. + + Args: + tokenizer: The tokenizer to check. + text: The text to use for the checks. + test_sentencepiece_ignore_case: See `TokenizerTesterMixin.test_sentencepiece_ignore_case`. + """ + text = "This is a test for subword regularization." if text is None else text + if test_sentencepiece_ignore_case: + text = text.lower() + + tokens_list = [] + for _ in range(5): + tokens_list.append(tokenizer.tokenize(text)) + + # the list of different pairs of tokens_list + combinations = itertools.combinations(tokens_list, 2) + + # check of sampling is done + subword_sampling_found = False + for combination in combinations: + if combination[0] != combination[1]: + subword_sampling_found = True + unittest.TestCase().assertTrue(subword_sampling_found) + + # check if converting back to original text works + for tokens in tokens_list: + if test_sentencepiece_ignore_case: + unittest.TestCase().assertEqual(text, tokenizer.convert_tokens_to_string(tokens).lower()) + else: + unittest.TestCase().assertEqual(text, tokenizer.convert_tokens_to_string(tokens)) + + +class TokenizerTesterMixin: + tokenizer_class = None + rust_tokenizer_class = None + test_slow_tokenizer = True + test_rust_tokenizer = True + space_between_special_tokens = False + from_pretrained_kwargs = None + from_pretrained_filter = None + from_pretrained_id = None + from_pretrained_vocab_key = "vocab_file" + test_seq2seq = True + + # set to True to test a sentencepiece tokenizer + test_sentencepiece = False + + # set to True to ignore casing when testing a sentencepiece tokenizer + # test_sentencepiece must also be set to True + test_sentencepiece_ignore_case = False + + @classmethod + def setUpClass(cls) -> None: + # Tokenizer.filter makes it possible to filter which Tokenizer to case based on all the + # information available in Tokenizer (name, rust class, python class, vocab key name) + cls.from_pretrained_id = ( + [cls.from_pretrained_id] if isinstance(cls.from_pretrained_id, str) else cls.from_pretrained_id + ) + + cls.tokenizers_list = [] + if cls.test_rust_tokenizer: + cls.tokenizers_list = [ + ( + cls.rust_tokenizer_class, + pretrained_id, + cls.from_pretrained_kwargs if cls.from_pretrained_kwargs is not None else {}, + ) + for pretrained_id in cls.from_pretrained_id + ] + else: + cls.tokenizers_list = [] + with open(f"{get_tests_dir()}/fixtures/sample_text.txt", encoding="utf-8") as f_data: + cls._data = f_data.read().replace("\n\n", "\n").strip() + + cls.tmpdirname = tempfile.mkdtemp() + + @classmethod + def tearDownClass(cls): + shutil.rmtree(cls.tmpdirname, ignore_errors=True) + + def get_input_output_texts(self, tokenizer): + input_txt = self.get_clean_sequence(tokenizer)[0] + return input_txt, input_txt + + def get_clean_sequence(self, tokenizer, with_prefix_space=False, max_length=20, min_length=5) -> tuple[str, list]: + # the length of the tokenizer does not always represent the tokens that it can encode: what if there are holes? + toks = [ + (i, tokenizer.decode([i], clean_up_tokenization_spaces=False)) for i in set(tokenizer.get_vocab().values()) + ] + toks = list(filter(lambda t: re.match(r"^[ a-zA-Z]+$", t[1]), toks)) + toks = list(filter(lambda t: [t[0]] == tokenizer.encode(t[1], add_special_tokens=False), toks)) + if max_length is not None and len(toks) > max_length: + toks = toks[:max_length] + if min_length is not None and len(toks) < min_length and len(toks) > 0: + while len(toks) < min_length: + toks = toks + toks + # toks_str = [t[1] for t in toks] + toks_ids = [t[0] for t in toks] + + # Ensure consistency + output_txt = tokenizer.decode(toks_ids, clean_up_tokenization_spaces=False) + if " " not in output_txt and len(toks_ids) > 1: + output_txt = ( + tokenizer.decode([toks_ids[0]], clean_up_tokenization_spaces=False) + + " " + + tokenizer.decode(toks_ids[1:], clean_up_tokenization_spaces=False) + ) + if with_prefix_space: + output_txt = " " + output_txt + output_ids = tokenizer.encode(output_txt, add_special_tokens=False) + return output_txt, output_ids + + def get_tokenizers(self, fast=True, **kwargs) -> list[PreTrainedTokenizerBase]: + if fast and self.test_rust_tokenizer and self.test_slow_tokenizer: + return [self.get_tokenizer(**kwargs), self.get_rust_tokenizer(**kwargs)] + elif fast and self.test_rust_tokenizer: + return [self.get_rust_tokenizer(**kwargs)] + elif self.test_slow_tokenizer: + return [self.get_tokenizer(**kwargs)] + else: + raise ValueError("This tokenizer class has no tokenizer to be tested.") + + @classmethod + @use_cache_if_possible + @lru_cache(maxsize=64) + def get_tokenizer(cls, pretrained_name=None, **kwargs) -> PreTrainedTokenizer: + pretrained_name = pretrained_name or cls.tmpdirname + return cls.tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + @classmethod + @use_cache_if_possible + @lru_cache(maxsize=64) + def get_rust_tokenizer(cls, pretrained_name=None, **kwargs) -> PreTrainedTokenizerFast: + pretrained_name = pretrained_name or cls.tmpdirname + return cls.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + def tokenizer_integration_test_util( + self, + expected_encoding: dict, + model_name: str, + revision: Optional[str] = None, + sequences: Optional[list[str]] = None, + decode_kwargs: Optional[dict[str, Any]] = None, + padding: bool = True, + ): + """ + Util for integration test. + + Text is tokenized and then reverted back to text. Both results are then checked. + + Args: + expected_encoding: + The expected result of the tokenizer output. + model_name: + The model name of the tokenizer to load and use. + revision: + The full git revision number of the model. This is to pin the + tokenizer config and to avoid that tests start to fail if the + config gets changed upstream. + sequences: + Can overwrite the texts that are used to check the tokenizer. + This is useful if the tokenizer supports non english languages + like france. + decode_kwargs: + Additional args for the ``decode`` function which reverts the + tokenized text back to a string. + padding: + Activates and controls padding of the tokenizer. + """ + decode_kwargs = {} if decode_kwargs is None else decode_kwargs + + if sequences is None: + sequences = [ + "Transformers (formerly known as pytorch-transformers and pytorch-pretrained-bert) provides " + "general-purpose architectures (BERT, GPT-2, RoBERTa, XLM, DistilBert, XLNet...) for Natural " + "Language Understanding (NLU) and Natural Language Generation (NLG) with over 32+ pretrained " + "models in 100+ languages and deep interoperability between Jax, PyTorch and TensorFlow.", + "BERT is designed to pre-train deep bidirectional representations from unlabeled text by jointly " + "conditioning on both left and right context in all layers.", + "The quick brown fox jumps over the lazy dog.", + ] + + if self.test_sentencepiece_ignore_case: + sequences = [sequence.lower() for sequence in sequences] + + tokenizer_classes = [self.tokenizer_class] + if self.test_rust_tokenizer: + tokenizer_classes.append(self.rust_tokenizer_class) + + for tokenizer_class in tokenizer_classes: + tokenizer = tokenizer_class.from_pretrained( + model_name, + revision=revision, # to pin the tokenizer version + ) + + encoding = tokenizer(sequences, padding=padding) + decoded_sequences = [ + tokenizer.decode(seq, skip_special_tokens=True, **decode_kwargs) for seq in encoding["input_ids"] + ] + + encoding_data = encoding.data + self.assertDictEqual(encoding_data, expected_encoding) + + for expected, decoded in zip(sequences, decoded_sequences): + if self.test_sentencepiece_ignore_case: + expected = expected.lower() + self.assertEqual(expected, decoded) + + def assert_padded_input_match(self, input_r: list, input_p: list, max_length: int, pad_token_id: int): + # Ensure we match max_length + self.assertEqual(len(input_r), max_length) + self.assertEqual(len(input_p), max_length) + + # Ensure the number of padded tokens is the same + padded_tokens_r = list(takewhile(lambda i: i == pad_token_id, reversed(input_r))) + padded_tokens_p = list(takewhile(lambda i: i == pad_token_id, reversed(input_p))) + self.assertSequenceEqual(padded_tokens_r, padded_tokens_p) + + def assert_batch_padded_input_match( + self, + input_r: dict, + input_p: dict, + max_length: int, + pad_token_id: int, + model_main_input_name: str = "input_ids", + ): + for i_r in input_r.values(): + ( + self.assertEqual(len(i_r), 2), + self.assertEqual(len(i_r[0]), max_length), + self.assertEqual(len(i_r[1]), max_length), + ) + ( + self.assertEqual(len(i_r), 2), + self.assertEqual(len(i_r[0]), max_length), + self.assertEqual(len(i_r[1]), max_length), + ) + + for i_r, i_p in zip(input_r[model_main_input_name], input_p[model_main_input_name]): + self.assert_padded_input_match(i_r, i_p, max_length, pad_token_id) + + for i_r, i_p in zip(input_r["attention_mask"], input_p["attention_mask"]): + self.assertSequenceEqual(i_r, i_p) + + @staticmethod + def convert_batch_encode_plus_format_to_encode_plus(batch_encode_plus_sequences): + # Switch from batch_encode_plus format: {'input_ids': [[...], [...]], ...} + # to the list of examples/ encode_plus format: [{'input_ids': [...], ...}, {'input_ids': [...], ...}] + return [ + {value: batch_encode_plus_sequences[value][i] for value in batch_encode_plus_sequences} + for i in range(len(batch_encode_plus_sequences["input_ids"])) + ] + + # TODO: this test can be combined with `test_sentencepiece_tokenize_and_convert_tokens_to_string` after the latter is extended to all tokenizers. + def test_tokenize_special_tokens(self): + """Test `tokenize` with special tokens.""" + tokenizers = self.get_tokenizers(fast=True, do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + SPECIAL_TOKEN_1 = "[SPECIAL_TOKEN_1]" + SPECIAL_TOKEN_2 = "[SPECIAL_TOKEN_2]" + + # Both methods should add the token to `_additional_special_tokens` and `added_tokens_decoder` + tokenizer.add_tokens([SPECIAL_TOKEN_1], special_tokens=True) + tokenizer.add_special_tokens( + {"additional_special_tokens": [SPECIAL_TOKEN_2]}, replace_additional_special_tokens=False + ) + + token_1 = tokenizer.tokenize(SPECIAL_TOKEN_1) + token_2 = tokenizer.tokenize(SPECIAL_TOKEN_2) + + self.assertEqual(len(token_1), 1) + self.assertEqual(len(token_2), 1) + self.assertEqual(token_1[0], SPECIAL_TOKEN_1) + # next is failing for almost all the Fast tokenizers now. + # self.assertEqual(token_2[0], SPECIAL_TOKEN_2) + + # TODO: this test could be extended to all tokenizers - not just the sentencepiece + def test_sentencepiece_tokenize_and_convert_tokens_to_string(self): + """Test ``_tokenize`` and ``convert_tokens_to_string``.""" + if not self.test_sentencepiece: + self.skipTest(reason="test_sentencepiece is set to False") + + tokenizer = self.get_tokenizer() + text = "This is text to test the tokenizer." + + if self.test_sentencepiece_ignore_case: + text = text.lower() + + tokens = tokenizer.tokenize(text) + + self.assertTrue(len(tokens) > 0) + + # check if converting back to original text works + reverse_text = tokenizer.convert_tokens_to_string(tokens) + + if self.test_sentencepiece_ignore_case: + reverse_text = reverse_text.lower() + + self.assertEqual(reverse_text, text) + + special_tokens = tokenizer.all_special_tokens + special_tokens_string = tokenizer.convert_tokens_to_string(special_tokens) + for special_token in special_tokens: + self.assertIn(special_token, special_tokens_string) + + if self.test_rust_tokenizer: + rust_tokenizer = self.get_rust_tokenizer() + special_tokens_string_rust = rust_tokenizer.convert_tokens_to_string(special_tokens) + self.assertEqual(special_tokens_string, special_tokens_string_rust) + + def test_sentencepiece_tokenize_and_decode(self): + if not self.test_sentencepiece: + self.skipTest(reason="test_sentencepiece is set to False") + + text = "This is text to test the tokenizer." + if self.test_rust_tokenizer: + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + slow_ids = tokenizer(text).input_ids + fast_ids = rust_tokenizer(text).input_ids + self.assertEqual(slow_ids, fast_ids) + + slow_decoded = tokenizer.decode(slow_ids) + fast_decoded = rust_tokenizer.decode(slow_ids) + self.assertEqual(slow_decoded, fast_decoded) + + def test_subword_regularization_tokenizer(self) -> None: + if not self.test_sentencepiece: + self.skipTest(reason="test_sentencepiece is set to False") + + # Subword regularization is only available for the slow tokenizer. + sp_model_kwargs = {"enable_sampling": True, "alpha": 0.1, "nbest_size": -1} + tokenizer = self.get_tokenizer(sp_model_kwargs=sp_model_kwargs) + + run_test_in_subprocess( + test_case=self, + target_func=_test_subword_regularization_tokenizer, + inputs={ + "tokenizer": tokenizer, + "sp_model_kwargs": sp_model_kwargs, + "test_sentencepiece_ignore_case": self.test_sentencepiece_ignore_case, + }, + ) + + def test_pickle_subword_regularization_tokenizer(self) -> None: + if not self.test_sentencepiece: + self.skipTest(reason="test_sentencepiece is set to False") + + """Google pickle __getstate__ __setstate__ if you are struggling with this.""" + # Subword regularization is only available for the slow tokenizer. + sp_model_kwargs = {"enable_sampling": True, "alpha": 0.1, "nbest_size": -1} + tokenizer = self.get_tokenizer(sp_model_kwargs=sp_model_kwargs) + tokenizer_bin = pickle.dumps(tokenizer) + del tokenizer + tokenizer_new = pickle.loads(tokenizer_bin) + + run_test_in_subprocess( + test_case=self, + target_func=_test_subword_regularization_tokenizer, + inputs={ + "tokenizer": tokenizer_new, + "sp_model_kwargs": sp_model_kwargs, + "test_sentencepiece_ignore_case": self.test_sentencepiece_ignore_case, + }, + ) + + def test_save_sentencepiece_tokenizer(self) -> None: + if not self.test_sentencepiece or not self.test_slow_tokenizer: + self.skipTest(reason="test_sentencepiece or test_slow_tokenizer is set to False") + # We want to verify that we will be able to save the tokenizer even if the original files that were used to + # build the tokenizer have been deleted in the meantime. + text = "This is text to test the tokenizer." + + tokenizer_slow_1 = self.get_tokenizer() + encoding_tokenizer_slow_1 = tokenizer_slow_1(text) + + tmpdirname_1 = tempfile.mkdtemp() + tmpdirname_2 = tempfile.mkdtemp() + + tokenizer_slow_1.save_pretrained(tmpdirname_1) + tokenizer_slow_2 = self.tokenizer_class.from_pretrained(tmpdirname_1) + encoding_tokenizer_slow_2 = tokenizer_slow_2(text) + + shutil.rmtree(tmpdirname_1) + tokenizer_slow_2.save_pretrained(tmpdirname_2) + + tokenizer_slow_3 = self.tokenizer_class.from_pretrained(tmpdirname_2) + encoding_tokenizer_slow_3 = tokenizer_slow_3(text) + shutil.rmtree(tmpdirname_2) + + self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_2) + self.assertEqual(encoding_tokenizer_slow_1, encoding_tokenizer_slow_3) + + def test_model_input_names_signature(self): + accepted_model_main_input_names = [ + "input_ids", # nlp models + "input_values", # speech models + ] + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + # first name of model_input_names has to correspond to main model input name + # to make sure `tokenizer.pad(...)` works correctly + self.assertTrue(tokenizer.model_input_names[0] in accepted_model_main_input_names) + + def test_rust_tokenizer_signature(self): + if not self.test_rust_tokenizer: + self.skipTest(reason="test_rust_tokenizer is set to False") + + signature = inspect.signature(self.rust_tokenizer_class.__init__) + + self.assertIn("tokenizer_file", signature.parameters) + self.assertIsNone(signature.parameters["tokenizer_file"].default) + + def test_tokenizer_slow_store_full_signature(self): + if not self.test_slow_tokenizer: + self.skipTest(reason="test_slow_tokenizer is set to False") + + signature = inspect.signature(self.tokenizer_class.__init__) + tokenizer = self.get_tokenizer() + + for parameter_name, parameter in signature.parameters.items(): + if parameter.default != inspect.Parameter.empty: + self.assertIn(parameter_name, tokenizer.init_kwargs) + + def test_tokenizer_fast_store_full_signature(self): + if not self.test_rust_tokenizer: + self.skipTest(reason="test_rust_tokenizer is set to False") + + signature = inspect.signature(self.rust_tokenizer_class.__init__) + tokenizer = self.get_rust_tokenizer() + + for parameter_name, parameter in signature.parameters.items(): + if parameter.default != inspect.Parameter.empty and parameter_name not in [ + "vocab_file", + "merges_file", + "tokenizer_file", + ]: + self.assertIn(parameter_name, tokenizer.init_kwargs) + + def test_rust_and_python_full_tokenizers(self): + if not self.test_rust_tokenizer: + self.skipTest(reason="test_rust_tokenizer is set to False") + + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + tokenizer = self.get_tokenizer() + rust_tokenizer = self.get_rust_tokenizer() + + sequence, _ = self.get_input_output_texts(tokenizer) + + # We don't have an exact equivalence on `tokenize()` between Rust and Slow + # Slow tokenizer only split tokens, Rust tokenizers will replace with + # tokens = tokenizer.tokenize(sequence) + # rust_tokens = rust_tokenizer.tokenize(sequence) + # self.assertListEqual(tokens, rust_tokens) + + ids = tokenizer.encode(sequence, add_special_tokens=False) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=False) + self.assertListEqual(ids, rust_ids) + + ids = tokenizer.encode(sequence, add_special_tokens=True) + rust_ids = rust_tokenizer.encode(sequence, add_special_tokens=True) + self.assertListEqual(ids, rust_ids) + + def test_tokenizers_common_properties(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + attributes_list = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token", + ] + for attr in attributes_list: + self.assertTrue(hasattr(tokenizer, attr)) + self.assertTrue(hasattr(tokenizer, attr + "_id")) + + self.assertTrue(hasattr(tokenizer, "additional_special_tokens")) + self.assertTrue(hasattr(tokenizer, "additional_special_tokens_ids")) + + attributes_list = [ + "model_max_length", + "init_inputs", + "init_kwargs", + ] + if not isinstance(tokenizer, PreTrainedTokenizerFast): + attributes_list += [ + "added_tokens_encoder", + "added_tokens_decoder", + ] + for attr in attributes_list: + self.assertTrue(hasattr(tokenizer, attr)) + + def test_tokenizers_common_ids_setters(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + attributes_list = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token", + ] + + vocab = tokenizer.get_vocab() + token_id_to_test_setters = next(iter(vocab.values())) + token_to_test_setters = tokenizer.convert_ids_to_tokens( + token_id_to_test_setters, skip_special_tokens=False + ) + + for attr in attributes_list: + setattr(tokenizer, attr + "_id", None) + self.assertEqual(getattr(tokenizer, attr), None) + self.assertEqual(getattr(tokenizer, attr + "_id"), None) + + setattr(tokenizer, attr + "_id", token_id_to_test_setters) + self.assertEqual(getattr(tokenizer, attr), token_to_test_setters) + self.assertEqual(getattr(tokenizer, attr + "_id"), token_id_to_test_setters) + + setattr(tokenizer, "additional_special_tokens_ids", []) + self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), []) + self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), []) + + setattr(tokenizer, "additional_special_tokens_ids", [token_id_to_test_setters]) + self.assertListEqual(getattr(tokenizer, "additional_special_tokens"), [token_to_test_setters]) + self.assertListEqual(getattr(tokenizer, "additional_special_tokens_ids"), [token_id_to_test_setters]) + + @parameterized.expand([(True,), (False,)]) + def test_tokenizers_special_tokens_properties_unset(self, verbose): + tokenizers = self.get_tokenizers(verbose=verbose) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + attributes_list = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token", + "additional_special_tokens", + ] + for attr in attributes_list: + setattr(tokenizer, attr, None) + self.assertIsNone(getattr(tokenizer, attr)) + + def test_save_and_load_tokenizer(self): + # safety check on max_len default value so we are sure the test works + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + self.assertNotEqual(tokenizer.model_max_length, 42) + + # Now let's start the test + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + sample_text = " He is very happy, UNwant\u00e9d,running" + before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) + before_vocab = tokenizer.get_vocab() + tokenizer.save_pretrained(tmpdirname) + + after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname) + after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False) + after_vocab = after_tokenizer.get_vocab() + self.assertListEqual(before_tokens, after_tokens) + self.assertDictEqual(before_vocab, after_vocab) + + shutil.rmtree(tmpdirname) + + tokenizers = self.get_tokenizers(model_max_length=42) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + sample_text = " He is very happy, UNwant\u00e9d,running" + tokenizer.add_tokens(["bim", "bambam"]) + additional_special_tokens = tokenizer.additional_special_tokens + additional_special_tokens.append("new_additional_special_token") + tokenizer.add_special_tokens( + {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False + ) + before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) + before_vocab = tokenizer.get_vocab() + tokenizer.save_pretrained(tmpdirname) + + after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname) + after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False) + after_vocab = after_tokenizer.get_vocab() + self.assertListEqual(before_tokens, after_tokens) + + self.assertDictEqual(before_vocab, after_vocab) + self.assertIn("bim", after_vocab) + self.assertIn("bambam", after_vocab) + self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens) + self.assertEqual(after_tokenizer.model_max_length, 42) + + tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43) + self.assertEqual(tokenizer.model_max_length, 43) + + shutil.rmtree(tmpdirname) + + # Test that we can also use the non-legacy saving format for fast tokenizers + tokenizers = self.get_tokenizers(model_max_length=42) + for tokenizer in tokenizers: + if not tokenizer.is_fast: + continue + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Isolate this from the other tests because we save additional tokens/etc + tmpdirname = tempfile.mkdtemp() + + sample_text = " He is very happy, UNwant\u00e9d,running" + tokenizer.add_tokens(["bim", "bambam"]) + additional_special_tokens = tokenizer.additional_special_tokens + additional_special_tokens.append("new_additional_special_token") + tokenizer.add_special_tokens( + {"additional_special_tokens": additional_special_tokens}, replace_additional_special_tokens=False + ) + before_tokens = tokenizer.encode(sample_text, add_special_tokens=False) + before_vocab = tokenizer.get_vocab() + tokenizer.save_pretrained(tmpdirname) + + after_tokenizer = tokenizer.__class__.from_pretrained(tmpdirname) + after_tokens = after_tokenizer.encode(sample_text, add_special_tokens=False) + after_vocab = after_tokenizer.get_vocab() + self.assertListEqual(before_tokens, after_tokens) + self.assertDictEqual(before_vocab, after_vocab) + self.assertIn("bim", after_vocab) + self.assertIn("bambam", after_vocab) + self.assertIn("new_additional_special_token", after_tokenizer.additional_special_tokens) + self.assertEqual(after_tokenizer.model_max_length, 42) + + tokenizer = tokenizer.__class__.from_pretrained(tmpdirname, model_max_length=43) + self.assertEqual(tokenizer.model_max_length, 43) + + shutil.rmtree(tmpdirname) + + def test_pickle_tokenizer(self): + """Google pickle __getstate__ __setstate__ if you are struggling with this.""" + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + self.assertIsNotNone(tokenizer) + + text = "Munich and Berlin are nice cities" + subwords = tokenizer.tokenize(text) + + filename = os.path.join(self.tmpdirname, "tokenizer.bin") + with open(filename, "wb") as handle: + pickle.dump(tokenizer, handle) + + with open(filename, "rb") as handle: + tokenizer_new = pickle.load(handle) + + subwords_loaded = tokenizer_new.tokenize(text) + + self.assertListEqual(subwords, subwords_loaded) + + @require_tokenizers + def test_pickle_added_tokens(self): + tok1 = AddedToken("", rstrip=True, lstrip=True, normalized=False, single_word=True) + tok2 = pickle.loads(pickle.dumps(tok1)) + + self.assertEqual(tok1.__getstate__(), tok2.__getstate__()) + + def test_added_tokens_do_lower_case(self): + tokenizers = self.get_tokenizers(do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if not hasattr(tokenizer, "do_lower_case") or not tokenizer.do_lower_case: + continue + + special_token = tokenizer.all_special_tokens[0] + + text = special_token + " aaaaa bbbbbb low cccccccccdddddddd l " + special_token + text2 = special_token + " AAAAA BBBBBB low CCCCCCCCCDDDDDDDD l " + special_token + + toks_before_adding = tokenizer.tokenize(text) # toks before adding new_toks + + new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd", "AAAAA BBBBBB", "CCCCCCCCCDDDDDDDD"] + added = tokenizer.add_tokens([AddedToken(tok, lstrip=True, rstrip=True) for tok in new_toks]) + + toks_after_adding = tokenizer.tokenize(text) + toks_after_adding2 = tokenizer.tokenize(text2) + + # Rust tokenizers don't lowercase added tokens at the time calling `tokenizer.add_tokens`, + # while python tokenizers do, so new_toks 0 and 2 would be treated as the same, so do new_toks 1 and 3. + self.assertIn(added, [2, 4]) + + self.assertListEqual(toks_after_adding, toks_after_adding2) + self.assertTrue( + len(toks_before_adding) > len(toks_after_adding), # toks_before_adding should be longer + ) + + # Check that none of the special tokens are lowercased + sequence_with_special_tokens = "A " + " yEs ".join(tokenizer.all_special_tokens) + " B" + # Convert the tokenized list to str as some special tokens are tokenized like normal tokens + # which have a prefix spacee e.g. the mask token of Albert, and cannot match the original + # special tokens exactly. + tokenized_sequence = "".join(tokenizer.tokenize(sequence_with_special_tokens)) + + for special_token in tokenizer.all_special_tokens: + self.assertTrue(special_token in tokenized_sequence or special_token.lower() in tokenized_sequence) + + tokenizers = self.get_tokenizers(do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if hasattr(tokenizer, "do_lower_case") and tokenizer.do_lower_case: + continue + + special_token = tokenizer.all_special_tokens[0] + + text = special_token + " aaaaa bbbbbb low cccccccccdddddddd l " + special_token + text2 = special_token + " AAAAA BBBBBB low CCCCCCCCCDDDDDDDD l " + special_token + + toks_before_adding = tokenizer.tokenize(text) # toks before adding new_toks + + new_toks = ["aaaaa bbbbbb", "cccccccccdddddddd", "AAAAA BBBBBB", "CCCCCCCCCDDDDDDDD"] + added = tokenizer.add_tokens([AddedToken(tok, lstrip=True, rstrip=True) for tok in new_toks]) + self.assertIn(added, [2, 4]) + + toks_after_adding = tokenizer.tokenize(text) + toks_after_adding2 = tokenizer.tokenize(text2) + + self.assertEqual(len(toks_after_adding), len(toks_after_adding2)) # Length should still be the same + self.assertNotEqual( + toks_after_adding[1], toks_after_adding2[1] + ) # But at least the first non-special tokens should differ + self.assertTrue( + len(toks_before_adding) > len(toks_after_adding), # toks_before_adding should be longer + ) + + # TODO @ArthurZ Nuke this + def test_add_tokens_tokenizer(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + vocab_size = tokenizer.vocab_size + all_size = len(tokenizer) + + self.assertNotEqual(vocab_size, 0) + + # We usually have added tokens from the start in tests (but also otherwise) because our vocab fixtures are + # smaller than the original vocabs - let's not assert this + # self.assertEqual(vocab_size, all_size) + + new_toks = [ + AddedToken("aaaaa bbbbbb", rstrip=True, lstrip=True), + AddedToken("cccccccccdddddddd", rstrip=True, lstrip=True), + ] + added_toks = tokenizer.add_tokens(new_toks) + vocab_size_2 = tokenizer.vocab_size + all_size_2 = len(tokenizer) + + self.assertNotEqual(vocab_size_2, 0) + self.assertEqual(vocab_size, vocab_size_2) + self.assertEqual(added_toks, len(new_toks)) + self.assertEqual(all_size_2, all_size + len(new_toks)) + + tokens = tokenizer.encode("aaaaa bbbbbb low cccccccccdddddddd l", add_special_tokens=False) + + self.assertGreaterEqual(len(tokens), 4) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-2], tokenizer.vocab_size - 1) + + new_toks_2 = { + "eos_token": AddedToken(">>>>|||<||<<|<<", rstrip=True, lstrip=True), + "pad_token": AddedToken("<<<<<|||>|>>>>|>", rstrip=True, lstrip=True), + } + added_toks_2 = tokenizer.add_special_tokens(new_toks_2) + vocab_size_3 = tokenizer.vocab_size + all_size_3 = len(tokenizer) + + self.assertNotEqual(vocab_size_3, 0) + self.assertEqual(vocab_size, vocab_size_3) + self.assertEqual(added_toks_2, len(new_toks_2)) + self.assertEqual(all_size_3, all_size_2 + len(new_toks_2)) + + tokens = tokenizer.encode( + ">>>>|||<||<<|<< aaaaa bbbbbb low cccccccccdddddddd <<<<<|||>|>>>>|> l", add_special_tokens=False + ) + + self.assertGreaterEqual(len(tokens), 6) + self.assertGreater(tokens[0], tokenizer.vocab_size - 1) + self.assertGreater(tokens[0], tokens[1]) + + self.assertGreater(tokens[-2], tokenizer.vocab_size - 1) + self.assertGreater(tokens[-2], tokens[-3]) + self.assertEqual(tokens[0], tokenizer.eos_token_id) + self.assertEqual(tokens[-2], tokenizer.pad_token_id) + + def test_add_special_tokens(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + input_text, ids = self.get_clean_sequence(tokenizer) + + special_token = AddedToken("[SPECIAL_TOKEN]", lstrip=True, rstrip=True) + + tokenizer.add_special_tokens({"cls_token": special_token}) + special_token = str(special_token) + encoded_special_token = tokenizer.encode(special_token, add_special_tokens=False) + self.assertEqual(len(encoded_special_token), 1) + + text = tokenizer.decode(ids + encoded_special_token, clean_up_tokenization_spaces=False) + encoded = tokenizer.encode(text, add_special_tokens=False) + + input_encoded = tokenizer.encode(input_text, add_special_tokens=False) + special_token_id = tokenizer.encode(special_token, add_special_tokens=False) + self.assertEqual(encoded, input_encoded + special_token_id) + + decoded = tokenizer.decode(encoded, skip_special_tokens=True) + self.assertTrue(special_token not in decoded) + + def test_internal_consistency(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + input_text, output_text = self.get_input_output_texts(tokenizer) + + tokens = tokenizer.tokenize(input_text) + ids = tokenizer.convert_tokens_to_ids(tokens) + ids_2 = tokenizer.encode(input_text, add_special_tokens=False) + self.assertListEqual(ids, ids_2) + + tokens_2 = tokenizer.convert_ids_to_tokens(ids) + self.assertNotEqual(len(tokens_2), 0) + text_2 = tokenizer.decode(ids) + self.assertIsInstance(text_2, str) + + self.assertEqual(text_2, output_text) + + @require_tokenizers + def test_encode_decode_with_spaces(self): + tokenizers = self.get_tokenizers(do_lower_case=False, fast=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + new_toks = [ + # These are added tokens, they will be normalized.... + AddedToken("[ABC]", normalized=True, lstrip=True, rstrip=True), + AddedToken("[DEF]", normalized=True, lstrip=True, rstrip=True), + AddedToken("GHI IHG", normalized=True, lstrip=True, rstrip=True), + ] + tokenizer.add_tokens(new_toks) + tokenizer.add_tokens([AddedToken("[SAMPLE]", normalized=True)], special_tokens=True) + input = "[ABC][DEF][ABC]GHI IHG[DEF]" + if self.space_between_special_tokens: + output = "[ABC] [DEF] [ABC] GHI IHG [DEF]" + else: + output = input + encoded = tokenizer.encode(input, add_special_tokens=False) + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=self.space_between_special_tokens) + + self.assertIn(decoded, [output, output.lower()]) + return + # TODO @ArthurZ Refactor testing as now the do_normalize works for special and non special + encoded = tokenizer.encode("[ABC] [DEF][SAMPLE]", add_special_tokens=False) + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True, skip_special_tokens=False) + self.assertIn(decoded, ["[ABC] [DEF] [SAMPLE]", "[ABC] [DEF] [SAMPLE]".lower()]) + + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True, skip_special_tokens=True) + self.assertIn(decoded, ["[ABC] [DEF]", "[ABC] [DEF]".lower()]) + + encoded = tokenizer.encode("[ABC][SAMPLE][DEF]", add_special_tokens=False) + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=True) + self.assertIn(decoded, ["[ABC] [SAMPLE] [DEF]", "[ABC][SAMPLE][DEF]".lower()]) + + decoded = tokenizer.decode(encoded, spaces_between_special_tokens=False) + self.assertIn(decoded, ["[ABC][SAMPLE][DEF]", "[ABC][SAMPLE][DEF]".lower()]) + + def test_mask_output(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if ( + tokenizer.build_inputs_with_special_tokens.__qualname__.split(".")[0] != "PreTrainedTokenizer" + and "token_type_ids" in tokenizer.model_input_names + ): + seq_0 = "Test this method." + seq_1 = "With these inputs." + information = tokenizer.encode_plus(seq_0, seq_1, add_special_tokens=True) + sequences, mask = information["input_ids"], information["token_type_ids"] + self.assertEqual(len(sequences), len(mask)) + + def test_token_type_ids(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0 = "Test this method." + + # We want to have sequence 0 and sequence 1 are tagged + # respectively with 0 and 1 token_ids + # (regardless of whether the model use token type ids) + # We use this assumption in the QA pipeline among other place + output = tokenizer(seq_0, return_token_type_ids=True) + self.assertIn(0, output["token_type_ids"]) + + def test_sequence_ids(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + if not tokenizer.is_fast: + continue + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0 = "Test this method." + seq_1 = "With these inputs." + + # We want to have sequence 0 and sequence 1 are tagged + # respectively with 0 and 1 token_ids + # (regardless of whether the model use token type ids) + # We use this assumption in the QA pipeline among other place + output = tokenizer(seq_0) + self.assertIn(0, output.sequence_ids()) + + output = tokenizer(seq_0, seq_1) + self.assertIn(0, output.sequence_ids()) + self.assertIn(1, output.sequence_ids()) + + if tokenizer.num_special_tokens_to_add(pair=True): + self.assertIn(None, output.sequence_ids()) + + @require_jinja + def test_chat_template(self): + dummy_template = "{% for message in messages %}{{message['role'] + message['content']}}{% endfor %}" + dummy_conversation = [ + {"role": "system", "content": "system message"}, + {"role": "user", "content": "user message"}, + {"role": "assistant", "content": "assistant message"}, + ] + expected_output = "systemsystem messageuseruser messageassistantassistant message" + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=False, return_dict=False + ) + self.assertEqual(output, expected_output) # Test we can pass chat_template arg + + # Check that no error raised when tokenize=True + output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=True, return_dict=False + ) + dict_output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=True, return_dict=True + ) + self.assertEqual(dict_output["input_ids"], output) # Test return_dict behaviour matches + + tokenizer.chat_template = dummy_template + self.assertEqual(tokenizer.chat_template, dummy_template) # Test property setter + output = tokenizer.apply_chat_template(dummy_conversation, tokenize=False, return_dict=False) + self.assertEqual(output, expected_output) # Test chat_template attribute is used if no arg is passed + # Check that no error raised + tokenizer.apply_chat_template(dummy_conversation, tokenize=True, return_dict=False) + + with tempfile.TemporaryDirectory() as tmp_dir_name: + save_files = tokenizer.save_pretrained(tmp_dir_name, save_jinja_files=False) + # Check we aren't saving a chat_template.jinja file + self.assertFalse(any(file.endswith("chat_template.jinja") for file in save_files)) + new_tokenizer = tokenizer.from_pretrained(tmp_dir_name) + + self.assertEqual(new_tokenizer.chat_template, dummy_template) # Test template has persisted + output = new_tokenizer.apply_chat_template(dummy_conversation, tokenize=False, return_dict=False) + self.assertEqual(output, expected_output) # Test output is the same after reloading + # Check that no error raised + new_tokenizer.apply_chat_template(dummy_conversation, tokenize=True, return_dict=False) + + with tempfile.TemporaryDirectory() as tmp_dir_name: + save_files = tokenizer.save_pretrained(tmp_dir_name) + # Check we are saving a chat_template.jinja file + self.assertTrue(any(file.endswith("chat_template.jinja") for file in save_files)) + chat_template_file = Path(tmp_dir_name) / "chat_template.jinja" + self.assertTrue(chat_template_file.is_file()) + self.assertEqual(chat_template_file.read_text(), dummy_template) + config_dict = json.loads((Path(tmp_dir_name) / "tokenizer_config.json").read_text()) + # Assert the chat template is not in the config when it's saved as a separate file + self.assertNotIn("chat_template", config_dict) + new_tokenizer = tokenizer.from_pretrained(tmp_dir_name) + + self.assertEqual(new_tokenizer.chat_template, dummy_template) # Test template has persisted + output = new_tokenizer.apply_chat_template(dummy_conversation, tokenize=False, return_dict=False) + self.assertEqual(output, expected_output) # Test output is the same after reloading + # Check that no error raised + new_tokenizer.apply_chat_template(dummy_conversation, tokenize=True, return_dict=False) + + @require_jinja + def test_chat_template_save_loading(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + signature = inspect.signature(tokenizer.__init__) + if "chat_template" not in {*signature.parameters.keys()}: + self.skipTest("tokenizer doesn't accept chat templates at input") + tokenizer.chat_template = "test template" + with tempfile.TemporaryDirectory() as tmpdirname: + tokenizer.save_pretrained(tmpdirname) + self.assertTrue(Path(tmpdirname, "chat_template.jinja").is_file()) + self.assertFalse(Path(tmpdirname, "chat_template.json").is_file()) + self.assertFalse(Path(tmpdirname, "additional_chat_templates").is_dir()) + reloaded_tokenizer = self.tokenizer_class.from_pretrained(tmpdirname) + self.assertEqual(tokenizer.chat_template, reloaded_tokenizer.chat_template) + # When we save as single files, tokenizers and tokenizers share a chat template, which means + # the reloaded tokenizer should get the chat template as well + self.assertEqual(reloaded_tokenizer.chat_template, reloaded_tokenizer.tokenizer.chat_template) + + with tempfile.TemporaryDirectory() as tmpdirname: + tokenizer.chat_template = {"default": "a", "secondary": "b"} + tokenizer.save_pretrained(tmpdirname) + self.assertTrue(Path(tmpdirname, "chat_template.jinja").is_file()) + self.assertFalse(Path(tmpdirname, "chat_template.json").is_file()) + self.assertTrue(Path(tmpdirname, "additional_chat_templates").is_dir()) + reloaded_tokenizer = self.tokenizer_class.from_pretrained(tmpdirname) + self.assertEqual(tokenizer.chat_template, reloaded_tokenizer.chat_template) + # When we save as single files, tokenizers and tokenizers share a chat template, which means + # the reloaded tokenizer should get the chat template as well + self.assertEqual(reloaded_tokenizer.chat_template, reloaded_tokenizer.tokenizer.chat_template) + + with tempfile.TemporaryDirectory() as tmpdirname: + tokenizer.chat_template = {"default": "a", "secondary": "b"} + tokenizer.save_pretrained(tmpdirname, save_jinja_files=False) + self.assertFalse(Path(tmpdirname, "chat_template.jinja").is_file()) + self.assertFalse(Path(tmpdirname, "chat_template.json").is_file()) + self.assertFalse(Path(tmpdirname, "additional_chat_templates").is_dir()) + reloaded_tokenizer = self.tokenizer_class.from_pretrained(tmpdirname) + self.assertEqual(tokenizer.chat_template, reloaded_tokenizer.chat_template) + # When we save as single files, tokenizers and tokenizers share a chat template, which means + # the reloaded tokenizer should get the chat template as well + self.assertEqual(reloaded_tokenizer.chat_template, reloaded_tokenizer.tokenizer.chat_template) + + @require_jinja + def test_chat_template_batched(self): + dummy_template = "{% for message in messages %}{{message['role'] + message['content']}}{% endfor %}" + dummy_conversations = [ + [ + {"role": "system", "content": "system message"}, + {"role": "user", "content": "user message"}, + {"role": "assistant", "content": "assistant message"}, + ], + [ + {"role": "system", "content": "system message 2"}, + {"role": "user", "content": "user message 2"}, + {"role": "assistant", "content": "assistant message 2"}, + ], + ] + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + output = tokenizer.apply_chat_template( + dummy_conversations, chat_template=dummy_template, tokenize=False + ) + self.assertEqual( + output, + [ + "systemsystem messageuseruser messageassistantassistant message", + "systemsystem message 2useruser message 2assistantassistant message 2", + ], + ) + one_element_output = tokenizer.apply_chat_template( + dummy_conversations[:1], chat_template=dummy_template, tokenize=False + ) + self.assertEqual( + one_element_output, ["systemsystem messageuseruser messageassistantassistant message"] + ) # Assert that list structure is retained even with one element + tokenizer.apply_chat_template( + dummy_conversations, chat_template=dummy_template, tokenize=True + ) # Check that no error raised + + @require_jinja + def test_jinja_loopcontrols(self): + break_template = """ + {%- for message in messages %} + {{- message.role + " " + message.content }} + {%- if loop.first %} + {%- break %} + {%- endif %} + {%- endfor %}""".strip() + + dummy_conversation = [ + {"role": "system", "content": "1"}, + {"role": "user", "content": "2"}, + {"role": "assistant", "content": "3"}, + ] + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + break_output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=break_template, tokenize=False + ) + self.assertEqual(break_output, "system 1") # Loop should break after first iter + + @require_jinja + def test_jinja_strftime(self): + strftime_template = """{{- strftime_now("%Y-%m-%d") }}""".strip() + + dummy_conversation = [ + {"role": "system", "content": "1"}, + {"role": "user", "content": "2"}, + {"role": "assistant", "content": "3"}, + ] + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + strftime_output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=strftime_template, tokenize=False + ) + + # Assert that we get a date formatted as expected + self.assertEqual(len(strftime_output), 10) + self.assertEqual(len(strftime_output.split("-")), 3) + + @require_torch + @require_jinja + def test_chat_template_return_assistant_tokens_mask(self): + dummy_template = ( + "{% for message in messages %}" + "{% if (message['role'] != 'assistant') %}" + "{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}" + "{% elif (message['role'] == 'assistant')%}" + "{{'<|im_start|>' + message['role'] + '\n'}}" + "{% generation %}" + "{{message['content'] + '<|im_end|>'}}" + "{% endgeneration %}" + "{{'\n'}}" + "{% endif %}" + "{% endfor %}" + ) + conversations = [ + [ + {"role": "system", "content": "system message"}, + {"role": "user", "content": "user message"}, + {"role": "assistant", "content": "start turn 1 assistant message. end turn 1"}, + {"role": "user", "content": "user message 2"}, + {"role": "assistant", "content": "start turn 2 assistant message. end turn 2"}, + ], + [ + {"role": "system", "content": "system message 3"}, + {"role": "user", "content": "user message 3"}, + {"role": "assistant", "content": "start turn 3 assistant message. end turn 3"}, + {"role": "user", "content": "user message 4"}, + {"role": "assistant", "content": "start turn 4 assistant message. end turn 4"}, + ], + ] + + # These are the prefix and suffix strings of all the assistant messages. Used to find the assistant substring + # in the entire chat string, and then find the corresponding tokens in the tokenized output. + assistant_prefix_suffix = [ + [("start turn 1", "end turn 1<|im_end|>"), ("start turn 2", "end turn 2<|im_end|>")], + [("start turn 3", "end turn 3<|im_end|>"), ("start turn 4", "end turn 4<|im_end|>")], + ] + for tokenizer, pretrained_name, _ in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + if not self.test_rust_tokenizer: + self.skipTest(reason="No fast tokenizer defined") + + tokenizer_r = self.get_rust_tokenizer(pretrained_name) + self._check_no_pad_token_padding(tokenizer_r, conversations) + + tokenizer_r.padding_side = "right" + + # check batched + output = tokenizer_r.apply_chat_template( + conversations, + chat_template=dummy_template, + tokenize=True, + return_assistant_tokens_mask=True, + return_dict=True, + ) + + output_pt = tokenizer_r.apply_chat_template( + conversations, + chat_template=dummy_template, + tokenize=True, + padding=True, + return_assistant_tokens_mask=True, + return_dict=True, + return_tensors="pt", + ) + + self.assertEqual(type(output_pt["assistant_masks"]), torch.Tensor) + self.assertEqual(output_pt["assistant_masks"].shape, output_pt["input_ids"].shape) + + for i, conv in enumerate(conversations): + chat_string = tokenizer_r.apply_chat_template(conv, tokenize=False, chat_template=dummy_template) + assistant_start = output.char_to_token(i, chat_string.index(assistant_prefix_suffix[i][0][0])) + assistant_end = output.char_to_token( + i, + chat_string.index(assistant_prefix_suffix[i][0][1]) + + len(assistant_prefix_suffix[i][0][1]) + - 1, + ) + + assistant_start2 = output.char_to_token(i, chat_string.index(assistant_prefix_suffix[i][1][0])) + assistant_end2 = output.char_to_token( + i, + chat_string.index(assistant_prefix_suffix[i][1][1]) + + len(assistant_prefix_suffix[i][1][1]) + - 1, + ) + + # assert 1 in first assistant message + self.assertEqual( + output["assistant_masks"][i][assistant_start : assistant_end + 1], + [1] * (assistant_end - assistant_start + 1), + ) + self.assertTrue( + (output_pt["assistant_masks"][i, assistant_start : assistant_end + 1] == 1).all(), + ) + + # assert 1 second assistant message + self.assertEqual( + output["assistant_masks"][i][assistant_start2 : assistant_end2 + 1], + [1] * (assistant_end2 - assistant_start2 + 1), + ) + self.assertTrue( + (output_pt["assistant_masks"][i, assistant_start2 : assistant_end2 + 1] == 1).all(), + ) + + # assert 0 in user/system indices + self.assertEqual(output["assistant_masks"][i][:assistant_start], [0] * assistant_start) + self.assertTrue((output_pt["assistant_masks"][i, :assistant_start] == 0).all()) + + self.assertEqual( + output["assistant_masks"][i][assistant_end + 1 : assistant_start2], + [0] * (assistant_start2 - assistant_end - 1), + ) + self.assertTrue( + (output_pt["assistant_masks"][i, assistant_end + 1 : assistant_start2] == 0).all(), + ) + + # check not batched + output = tokenizer_r.apply_chat_template( + conversations[0], + chat_template=dummy_template, + tokenize=True, + return_assistant_tokens_mask=True, + return_dict=True, + ) + output_pt = tokenizer_r.apply_chat_template( + conversations[0], + chat_template=dummy_template, + tokenize=True, + return_assistant_tokens_mask=True, + return_dict=True, + return_tensors="pt", + ) + + self.assertEqual(type(output_pt["assistant_masks"]), torch.Tensor) + self.assertEqual(output_pt["assistant_masks"].shape, output_pt["input_ids"].shape) + + chat_string = tokenizer_r.apply_chat_template( + conversations[0], tokenize=False, chat_template=dummy_template + ) + assistant_start = output.char_to_token(0, chat_string.index(assistant_prefix_suffix[0][0][0])) + assistant_end = output.char_to_token( + 0, chat_string.index(assistant_prefix_suffix[0][0][1]) + len(assistant_prefix_suffix[0][0][1]) - 1 + ) + assistant_start2 = output.char_to_token(0, chat_string.index(assistant_prefix_suffix[0][1][0])) + assistant_end2 = output.char_to_token( + 0, chat_string.index(assistant_prefix_suffix[0][1][1]) + len(assistant_prefix_suffix[0][1][1]) - 1 + ) + + # assert 1 in assistant indices + self.assertEqual( + output["assistant_masks"][assistant_start : assistant_end + 1], + [1] * (assistant_end - assistant_start + 1), + ) + self.assertTrue( + (output_pt["assistant_masks"][assistant_start : assistant_end + 1] == 1).all(), + ) + self.assertEqual( + output["assistant_masks"][assistant_start2 : assistant_end2 + 1], + [1] * (assistant_end2 - assistant_start2 + 1), + ) + self.assertTrue( + (output_pt["assistant_masks"][assistant_start2 : assistant_end2 + 1] == 1).all(), + ) + + # assert 0 in user/system indices + self.assertEqual(output["assistant_masks"][:assistant_start], [0] * assistant_start) + self.assertTrue((output_pt["assistant_masks"][0, :assistant_start] == 0).all()) + self.assertEqual( + output["assistant_masks"][assistant_end + 1 : assistant_start2], + [0] * (assistant_start2 - assistant_end - 1), + ) + self.assertTrue( + (output_pt["assistant_masks"][0, assistant_end + 1 : assistant_start2] == 0).all(), + ) + + @require_jinja + def test_chat_template_return_assistant_tokens_mask_truncated(self): + dummy_template = ( + "{% for message in messages %}" + "{% if (message['role'] != 'assistant') %}" + "{{'<|im_start|>' + message['role'] + '\n' + message['content'] + '<|im_end|>' + '\n'}}" + "{% elif (message['role'] == 'assistant')%}" + "{{'<|im_start|>' + message['role'] + '\n'}}" + "{% generation %}" + "{{message['content'] + '<|im_end|>'}}" + "{% endgeneration %}" + "{{'\n'}}" + "{% endif %}" + "{% endfor %}" + ) + conversations = [ + [ + {"role": "system", "content": "system message"}, + {"role": "user", "content": "user message"}, + { + "role": "assistant", + "content": ( + "start turn assistant. long string to be truncated, long string to be truncated, " + "long string to be truncated, long string to be truncated, long string to be truncated" + ), + }, + {"role": "user", "content": "another user message"}, + ], + [ + {"role": "system", "content": "system message"}, + {"role": "user", "content": "user message"}, + { + "role": "assistant", + "content": ( + "start turn assistant. long string to be truncated, long string to be truncated, " + "long string to be truncated, long string to be truncated, long string to be truncated" + ), + }, + {"role": "user", "content": "another user message"}, + ], + ] + + for tokenizer, pretrained_name, _ in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + if not self.test_rust_tokenizer: + self.skipTest(reason="No fast tokenizer defined") + + tokenizer_r = self.get_rust_tokenizer(pretrained_name) + + # Find where to truncate, as the amount of tokens is different for different tokenizers and I want the + # truncation to happen in the middle of the assistant content. + full_encoding = tokenizer_r.apply_chat_template( + conversations[0], + chat_template=dummy_template, + tokenize=True, + return_dict=True, + ) + chat_string = tokenizer_r.apply_chat_template( + conversations[0], tokenize=False, chat_template=dummy_template + ) + truncation_position = full_encoding.char_to_token(chat_string.index(", long string to be truncated,")) + + # check batched + output = tokenizer_r.apply_chat_template( + conversations, + chat_template=dummy_template, + tokenize=True, + return_assistant_tokens_mask=True, + max_length=truncation_position, + truncation=True, + return_dict=True, + ) + for i, conv in enumerate(conversations): + chat_string = tokenizer_r.apply_chat_template(conv, tokenize=False, chat_template=dummy_template) + assistant_start = output.char_to_token(i, chat_string.index("start turn assistant")) + + # assert 1 from assistant_start to the end because the rest is truncated. + self.assertEqual( + output["assistant_masks"][i][assistant_start:], + [1] * (len(output["assistant_masks"][i]) - assistant_start), + ) + + # check not batched + output = tokenizer_r.apply_chat_template( + conversations[0], + chat_template=dummy_template, + tokenize=True, + return_assistant_tokens_mask=True, + return_dict=True, + max_length=truncation_position, + truncation=True, + ) + + chat_string = tokenizer_r.apply_chat_template( + conversations[0], tokenize=False, chat_template=dummy_template + ) + assistant_start = output.char_to_token(0, chat_string.index("start turn assistant")) + + # assert 1 from assistant_start to the end because the rest is truncated. + self.assertEqual( + output["assistant_masks"][assistant_start:], + [1] * (len(output["assistant_masks"]) - assistant_start), + ) + + @require_jinja + def test_continue_final_message(self): + dummy_template = """ + {%- for message in messages %} + {{- "<|im_start|>" + message['role'] + "\n" + message['content'] + "<|im_end|>" + "\n"}} + {%- endfor %}""" + dummy_conversation = [ + {"role": "system", "content": "system message"}, + {"role": "user", "content": "user message"}, + {"role": "assistant", "content": "assistant message"}, + ] + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=False, continue_final_message=False + ) + self.assertEqual( + output, + "<|im_start|>system\nsystem message<|im_end|>\n<|im_start|>user\nuser message<|im_end|>\n<|im_start|>assistant\nassistant message<|im_end|>\n", + ) + prefill_output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=False, continue_final_message=True + ) + # Assert that the final message is unterminated + self.assertEqual( + prefill_output, + "<|im_start|>system\nsystem message<|im_end|>\n<|im_start|>user\nuser message<|im_end|>\n<|im_start|>assistant\nassistant message", + ) + + @require_jinja + def test_continue_final_message_with_trim(self): + """Regression test for chat templates with trimming: https://github.com/huggingface/transformers/pull/34214""" + + dummy_template = """ + {%- for message in messages %} + {{- "<|im_start|>" + message['role'] + "\n" + message['content'] | trim + "<|im_end|>" + "\n"}} + {%- endfor %}""" + dummy_conversation = [ + {"role": "system", "content": "system message"}, + {"role": "user", "content": "user message"}, + {"role": "assistant", "content": "assistant message "}, # Note the trailing whitespace + ] + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=False, continue_final_message=False + ) + self.assertEqual( + output, + "<|im_start|>system\nsystem message<|im_end|>\n<|im_start|>user\nuser message<|im_end|>\n<|im_start|>assistant\nassistant message<|im_end|>\n", + ) + prefill_output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=False, continue_final_message=True + ) + # Assert that the final message is unterminated + self.assertEqual( + prefill_output, + "<|im_start|>system\nsystem message<|im_end|>\n<|im_start|>user\nuser message<|im_end|>\n<|im_start|>assistant\nassistant message", + ) + + @require_jinja + def test_continue_final_message_with_decoy_earlier_message(self): + """Regression test for chat templates where an earlier message has similar content to the final message + https://github.com/huggingface/transformers/issues/35433""" + + dummy_template = """ + {%- for message in messages %} + {{- "<|im_start|>" + message['role'] + "\n" + message['content'] | trim + "<|im_end|>" + "\n"}} + {%- endfor %}""" + dummy_conversation = [ + {"role": "user", "content": "hi 0"}, + {"role": "assistant", "content": "bye: 0"}, + {"role": "user", "content": "hi 1"}, + {"role": "assistant", "content": "bye: "}, + ] + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + prefill_output = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template, tokenize=False, continue_final_message=True + ) + # Assert that the final message is unterminated + self.assertEqual( + prefill_output, + "<|im_start|>user\nhi 0<|im_end|>\n<|im_start|>assistant\nbye: 0<|im_end|>\n<|im_start|>user\nhi 1<|im_end|>\n<|im_start|>assistant\nbye:", + ) + + @require_jinja + def test_chat_template_dict(self): + dummy_template_1 = "{{'a'}}" + dummy_template_2 = "{{'b'}}" + dummy_conversation = [ + {"role": "user", "content": "user message"}, + ] + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokenizer.chat_template = {"template1": dummy_template_1, "template2": dummy_template_2} + output1 = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template_1, tokenize=False + ) + output1_via_dict = tokenizer.apply_chat_template( + dummy_conversation, chat_template="template1", tokenize=False + ) + self.assertEqual(output1, output1_via_dict) + output2 = tokenizer.apply_chat_template( + dummy_conversation, chat_template=dummy_template_2, tokenize=False + ) + output2_via_dict = tokenizer.apply_chat_template( + dummy_conversation, chat_template="template2", tokenize=False + ) + self.assertEqual(output2, output2_via_dict) + + @require_jinja + def test_chat_template_dict_saving(self): + dummy_template_1 = "{{'a'}}" + dummy_template_2 = "{{'b'}}" + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + for save_jinja_files in (True, False): + tokenizer.chat_template = {"default": dummy_template_1, "template2": dummy_template_2} + with tempfile.TemporaryDirectory() as tmp_dir_name: + # Test that save_jinja_files is ignored when there's a dict of multiple templates + tokenizer.save_pretrained(tmp_dir_name, save_jinja_files=save_jinja_files) + if save_jinja_files: + config_dict = json.load(open(os.path.join(tmp_dir_name, "tokenizer_config.json"))) + self.assertNotIn("chat_template", config_dict) + self.assertTrue(os.path.exists(os.path.join(tmp_dir_name, "chat_template.jinja"))) + self.assertTrue( + os.path.exists(os.path.join(tmp_dir_name, "additional_chat_templates/template2.jinja")) + ) + else: + config_dict = json.load(open(os.path.join(tmp_dir_name, "tokenizer_config.json"))) + # Assert that chat templates are correctly serialized as lists of dictionaries + self.assertEqual( + config_dict["chat_template"], + [ + {"name": "default", "template": "{{'a'}}"}, + {"name": "template2", "template": "{{'b'}}"}, + ], + ) + self.assertFalse(os.path.exists(os.path.join(tmp_dir_name, "chat_template.jinja"))) + new_tokenizer = tokenizer.from_pretrained(tmp_dir_name) + # Assert that the serialized list is correctly reconstructed as a single dict + self.assertEqual(new_tokenizer.chat_template, tokenizer.chat_template) + + @require_jinja + def test_chat_template_file_priority(self): + dummy_template1 = "a" + dummy_template2 = "b" + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + with tempfile.TemporaryDirectory() as tmp_dir_name: + tokenizer.chat_template = dummy_template1 + tokenizer.save_pretrained(tmp_dir_name, save_jinja_files=False) + with Path(tmp_dir_name, "chat_template.jinja").open("w") as f: + f.write(dummy_template2) + new_tokenizer = tokenizer.from_pretrained(tmp_dir_name) + # Assert the file template clobbers any template in the config + self.assertEqual(new_tokenizer.chat_template, dummy_template2) + + def test_number_of_added_tokens(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0 = "Test this method." + seq_1 = "With these inputs." + + sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=False) + attached_sequences = tokenizer.encode(seq_0, seq_1, add_special_tokens=True) + + # Method is implemented (e.g. not GPT-2) + if len(attached_sequences) != 2: + self.assertEqual( + tokenizer.num_special_tokens_to_add(pair=True), len(attached_sequences) - len(sequences) + ) + + def test_maximum_encoding_length_single_input(self): + tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20) + + sequence = tokenizer.encode(seq_0, add_special_tokens=False) + total_length = len(sequence) + + self.assertGreater( + total_length, 4, "Issue with the testing sequence, please update it, it's too short" + ) + + # Test with max model input length + model_max_length = tokenizer.model_max_length + self.assertEqual(model_max_length, 100) + seq_1 = seq_0 * model_max_length + + sequence1 = tokenizer(seq_1, add_special_tokens=False) + total_length1 = len(sequence1["input_ids"]) + self.assertGreater( + total_length1, + model_max_length, + "Issue with the testing sequence, please update it, it's too short", + ) + + # Simple + padding_strategies = ( + [False, True, "longest"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False] + ) + for padding_state in padding_strategies: + with self.subTest(f"Padding: {padding_state}"): + for truncation_state in [True, "longest_first", "only_first"]: + with self.subTest(f"Truncation: {truncation_state}"): + output = tokenizer(seq_1, padding=padding_state, truncation=truncation_state) + self.assertEqual(len(output["input_ids"]), model_max_length) + + output = tokenizer([seq_1], padding=padding_state, truncation=truncation_state) + self.assertEqual(len(output["input_ids"][0]), model_max_length) + + # Simple with no truncation + # Reset warnings + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer(seq_1, padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer([seq_1], padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"][0]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + # Overflowing tokens + stride = 2 + information = tokenizer( + seq_0, + max_length=total_length - 2, + add_special_tokens=False, + stride=stride, + truncation="longest_first", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + truncated_sequence = information["input_ids"][0] + overflowing_tokens = information["input_ids"][1] + self.assertEqual(len(information["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), total_length - 2) + self.assertEqual(truncated_sequence, sequence[:-2]) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :]) + else: + truncated_sequence = information["input_ids"] + overflowing_tokens = information["overflowing_tokens"] + + self.assertEqual(len(truncated_sequence), total_length - 2) + self.assertEqual(truncated_sequence, sequence[:-2]) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, sequence[-(2 + stride) :]) + + def test_maximum_encoding_length_pair_input(self): + tokenizers = self.get_tokenizers(do_lower_case=False, model_max_length=100) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Build a sequence from our model's vocabulary + stride = 2 + seq_0, ids = self.get_clean_sequence(tokenizer, max_length=20) + if len(ids) <= 2 + stride: + seq_0 = (seq_0 + " ") * (2 + stride) + ids = None + + seq0_tokens = tokenizer.encode(seq_0, add_special_tokens=False) + self.assertGreater(len(seq0_tokens), 2 + stride) + + seq_1 = "This is another sentence to be encoded." + seq1_tokens = tokenizer.encode(seq_1, add_special_tokens=False) + if abs(len(seq0_tokens) - len(seq1_tokens)) <= 2: + seq1_tokens = seq1_tokens + seq1_tokens + seq_1 = tokenizer.decode(seq1_tokens, clean_up_tokenization_spaces=False) + seq1_tokens = tokenizer.encode(seq_1, add_special_tokens=False) + + self.assertGreater(len(seq1_tokens), 2 + stride) + + smallest = seq1_tokens if len(seq0_tokens) > len(seq1_tokens) else seq0_tokens + + # We are not using the special tokens - a bit too hard to test all the tokenizers with this + # TODO try this again later + sequence = tokenizer.encode(seq_0, seq_1, add_special_tokens=False) # , add_prefix_space=False) + + # Test with max model input length + model_max_length = tokenizer.model_max_length + self.assertEqual(model_max_length, 100) + seq_2 = seq_0 * model_max_length + self.assertGreater(len(seq_2), model_max_length) + + sequence1 = tokenizer(seq_1, add_special_tokens=False) + total_length1 = len(sequence1["input_ids"]) + sequence2 = tokenizer(seq_2, seq_1, add_special_tokens=False) + total_length2 = len(sequence2["input_ids"]) + self.assertLess( + total_length1, model_max_length - 10, "Issue with the testing sequence, please update it." + ) + self.assertGreater( + total_length2, model_max_length, "Issue with the testing sequence, please update it." + ) + + # Simple + padding_strategies = ( + [False, True, "longest"] if tokenizer.pad_token and tokenizer.pad_token_id >= 0 else [False] + ) + for padding_state in padding_strategies: + with self.subTest(f"{tokenizer.__class__.__name__} Padding: {padding_state}"): + for truncation_state in [True, "longest_first", "only_first"]: + with self.subTest(f"{tokenizer.__class__.__name__} Truncation: {truncation_state}"): + output = tokenizer(seq_2, seq_1, padding=padding_state, truncation=truncation_state) + self.assertEqual(len(output["input_ids"]), model_max_length) + + output = tokenizer( + [seq_2], [seq_1], padding=padding_state, truncation=truncation_state + ) + self.assertEqual(len(output["input_ids"][0]), model_max_length) + + # Simple + output = tokenizer(seq_1, seq_2, padding=padding_state, truncation="only_second") + self.assertEqual(len(output["input_ids"]), model_max_length) + + output = tokenizer([seq_1], [seq_2], padding=padding_state, truncation="only_second") + self.assertEqual(len(output["input_ids"][0]), model_max_length) + + # Simple with no truncation + # Reset warnings + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer(seq_1, seq_2, padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + tokenizer.deprecation_warnings = {} + with self.assertLogs("transformers", level="WARNING") as cm: + output = tokenizer([seq_1], [seq_2], padding=padding_state, truncation=False) + self.assertNotEqual(len(output["input_ids"][0]), model_max_length) + self.assertEqual(len(cm.records), 1) + self.assertTrue( + cm.records[0].message.startswith( + "Token indices sequence length is longer than the specified maximum sequence length" + " for this model" + ) + ) + + truncated_first_sequence = tokenizer.encode(seq_0, add_special_tokens=False)[:-2] + tokenizer.encode( + seq_1, add_special_tokens=False + ) + truncated_second_sequence = ( + tokenizer.encode(seq_0, add_special_tokens=False) + + tokenizer.encode(seq_1, add_special_tokens=False)[:-2] + ) + truncated_longest_sequence = ( + truncated_first_sequence if len(seq0_tokens) > len(seq1_tokens) else truncated_second_sequence + ) + + overflow_first_sequence = tokenizer.encode(seq_0, add_special_tokens=False)[ + -(2 + stride) : + ] + tokenizer.encode(seq_1, add_special_tokens=False) + overflow_second_sequence = ( + tokenizer.encode(seq_0, add_special_tokens=False) + + tokenizer.encode(seq_1, add_special_tokens=False)[-(2 + stride) :] + ) + overflow_longest_sequence = ( + overflow_first_sequence if len(seq0_tokens) > len(seq1_tokens) else overflow_second_sequence + ) + + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + information = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation="longest_first", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + truncated_sequence = information["input_ids"][0] + overflowing_tokens = information["input_ids"][1] + self.assertEqual(len(information["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_longest_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride + len(smallest)) + self.assertEqual(overflowing_tokens, overflow_longest_sequence) + else: + # No overflowing tokens when using 'longest' in python tokenizers + with self.assertRaises(ValueError) as context: + information = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation="longest_first", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + + self.assertTrue( + context.exception.args[0].startswith( + "Not possible to return overflowing tokens for pair of sequences with the " + "`longest_first`. Please select another truncation strategy than `longest_first`, " + "for instance `only_second` or `only_first`." + ) + ) + + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + information = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation=True, + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + truncated_sequence = information["input_ids"][0] + overflowing_tokens = information["input_ids"][1] + self.assertEqual(len(information["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_longest_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride + len(smallest)) + self.assertEqual(overflowing_tokens, overflow_longest_sequence) + else: + # No overflowing tokens when using 'longest' in python tokenizers + with self.assertRaises(ValueError) as context: + information = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation=True, + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + + self.assertTrue( + context.exception.args[0].startswith( + "Not possible to return overflowing tokens for pair of sequences with the " + "`longest_first`. Please select another truncation strategy than `longest_first`, " + "for instance `only_second` or `only_first`." + ) + ) + + information_first_truncated = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation="only_first", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + truncated_sequence = information_first_truncated["input_ids"][0] + overflowing_tokens = information_first_truncated["input_ids"][1] + self.assertEqual(len(information_first_truncated["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_first_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride + len(seq1_tokens)) + self.assertEqual(overflowing_tokens, overflow_first_sequence) + else: + truncated_sequence = information_first_truncated["input_ids"] + overflowing_tokens = information_first_truncated["overflowing_tokens"] + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_first_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, seq0_tokens[-(2 + stride) :]) + + information_second_truncated = tokenizer( + seq_0, + seq_1, + max_length=len(sequence) - 2, + add_special_tokens=False, + stride=stride, + truncation="only_second", + return_overflowing_tokens=True, + # add_prefix_space=False, + ) + # Overflowing tokens are handled quite differently in slow and fast tokenizers + if isinstance(tokenizer, PreTrainedTokenizerFast): + truncated_sequence = information_second_truncated["input_ids"][0] + overflowing_tokens = information_second_truncated["input_ids"][1] + self.assertEqual(len(information_second_truncated["input_ids"]), 2) + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_second_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride + len(seq0_tokens)) + self.assertEqual(overflowing_tokens, overflow_second_sequence) + else: + truncated_sequence = information_second_truncated["input_ids"] + overflowing_tokens = information_second_truncated["overflowing_tokens"] + + self.assertEqual(len(truncated_sequence), len(sequence) - 2) + self.assertEqual(truncated_sequence, truncated_second_sequence) + + self.assertEqual(len(overflowing_tokens), 2 + stride) + self.assertEqual(overflowing_tokens, seq1_tokens[-(2 + stride) :]) + + # TODO: FIXME @ArthurZucker + @unittest.skip( + reason="start to fail after # 29473. See https://github.com/huggingface/transformers/pull/29473#pullrequestreview-1945687810" + ) + @slow + @require_read_token + def test_encode_decode_fast_slow_all_tokens(self): + if self.rust_tokenizer_class is not None: + pretrained_name = self.from_pretrained_id + + slow_tokenizer = self.get_tokenizer(pretrained_name, legacy=False) + with self.subTest(f"{pretrained_name}"): + rust_tokenizer = self.get_rust_tokenizer(pretrained_name, from_slow=True, legacy=False) + input_full_vocab_ids = list( + range(len(slow_tokenizer)) + ) # TODO let's maybe shuffle this! And run it 4 times. This way we cover more cmbinations + input_full_vocab_string = rust_tokenizer.convert_tokens_to_string( + rust_tokenizer.convert_ids_to_tokens(input_full_vocab_ids) + ) + print(f"Length of the input string that is tested: {len(input_full_vocab_string)}") + + for chunk in range(0, len(input_full_vocab_string) - 1024, 1024): + string_to_check = input_full_vocab_string[chunk : chunk + 1024] + with self.subTest(f"{(chunk / len(input_full_vocab_string)) * 100}%"): + slow_encode = slow_tokenizer.encode(string_to_check) + fast_encode = rust_tokenizer.encode(string_to_check) + self.assertEqual( + slow_encode, + fast_encode, + "Hint: the following tokenization diff were obtained for slow vs fast:\n " + f"elements in slow: {set(slow_tokenizer.tokenize(string_to_check)) - set(rust_tokenizer.tokenize(string_to_check))} \nvs\n " + f"elements in fast: {set(rust_tokenizer.tokenize(string_to_check)) - set(slow_tokenizer.tokenize(string_to_check))} \n" + f"string used : {string_to_check}", + ) + print(f"Length of the input ids that is tested: {len(input_full_vocab_ids)}") + for chunk in range(0, len(input_full_vocab_ids) - 100, 100): + ids_to_decode = input_full_vocab_ids[chunk : chunk + 100] + with self.subTest(f"{(chunk / len(input_full_vocab_string)) * 100}%"): + self.assertEqual( + slow_tokenizer.decode( + ids_to_decode, + space_between_special_tokens=False, + clean_up_tokenization_spaces=False, + ), + rust_tokenizer.decode( + ids_to_decode, + space_between_special_tokens=False, + clean_up_tokenization_spaces=False, + ), + f"Hint here are the tokens being decoded.: {slow_tokenizer.convert_ids_to_tokens(ids_to_decode)}", + ) + + # def test_encode_input_type(self): + # tokenizers = self.get_tokenizers(do_lower_case=False) + # for tokenizer in tokenizers: + # with self.subTest(f"{tokenizer.__class__.__name__}"): + # sequence = "Let's encode this sequence" + + # tokens = sequence.split() # tokenizer.tokenize(sequence) + # # input_ids = tokenizer.convert_tokens_to_ids(tokens) + # formatted_input = tokenizer.encode(sequence, add_special_tokens=True, add_prefix_space=False) + + # self.assertEqual( + # tokenizer.encode(tokens, is_split_into_words=True, add_special_tokens=True), formatted_input + # ) + # # This is not supported with the Rust tokenizers + # # self.assertEqual(tokenizer.encode(input_ids, add_special_tokens=True), formatted_input) + + # def test_swap_special_token(self): + # tokenizers = self.get_tokenizers(do_lower_case=False) + # for tokenizer in tokenizers: + # with self.subTest(f"{tokenizer.__class__.__name__}"): + # # Our mask token + # mask = "" + # # We take a single word in the middle of the vocabulary + # all_tokens = sorted(tokenizer.get_vocab().keys()) + # word = tokenizer.decode(tokenizer.encode(all_tokens[len(all_tokens)//2], add_special_tokens=False)[:1]) + + # sequence_0 = "Encode " + word + " sequence" + # sequence_masked_0 = "Encode " + mask + " sequence" + + # sequence_1 = word + " this sequence" + # sequence_masked_1 = mask + " this sequence" + + # # Add tokens so that masked token isn't split + # # tokens = [AddedToken(t, lstrip=True, normalized=False) for t in sequence.split()] + # # tokenizer.add_tokens(tokens) + # tokenizer.add_special_tokens( + # {"mask_token": AddedToken(mask, normalized=False)} + # ) # Eat left space on Byte-level BPE tokenizers + # mask_ind = tokenizer.convert_tokens_to_ids(mask) + + # # Test first masked sequence + # encoded_0 = tokenizer.encode(sequence_0, add_special_tokens=False) + # encoded_masked = tokenizer.encode(sequence_masked_0, add_special_tokens=False) + # self.assertEqual(len(encoded_masked), len(encoded_0)) + # mask_loc = encoded_masked.index(mask_ind) + # encoded_masked[mask_loc] = encoded_0[mask_loc] + + # self.assertEqual(encoded_masked, encoded_0) + + # # Test second masked sequence + # encoded_1 = tokenizer.encode(sequence_1, add_special_tokens=False) + # encoded_masked = tokenizer.encode(sequence_masked_1, add_special_tokens=False) + # self.assertEqual(len(encoded_masked), len(encoded_1)) + # mask_loc = encoded_masked.index(mask_ind) + # encoded_masked[mask_loc] = encoded_1[mask_loc] + + # self.assertEqual(encoded_masked, encoded_1) + + def test_special_tokens_mask(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence_0 = "Encode this." + # Testing single inputs + encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False) + encoded_sequence_dict = tokenizer.encode_plus( + sequence_0, + add_special_tokens=True, + return_special_tokens_mask=True, # , add_prefix_space=False + ) + encoded_sequence_w_special = encoded_sequence_dict["input_ids"] + special_tokens_mask = encoded_sequence_dict["special_tokens_mask"] + self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special)) + + filtered_sequence = [x for i, x in enumerate(encoded_sequence_w_special) if not special_tokens_mask[i]] + self.assertEqual(encoded_sequence, filtered_sequence) + + def test_special_tokens_mask_input_pairs(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence_0 = "Encode this." + sequence_1 = "This one too please." + encoded_sequence = tokenizer.encode(sequence_0, add_special_tokens=False) + encoded_sequence += tokenizer.encode(sequence_1, add_special_tokens=False) + encoded_sequence_dict = tokenizer.encode_plus( + sequence_0, + sequence_1, + add_special_tokens=True, + return_special_tokens_mask=True, + # add_prefix_space=False, + ) + encoded_sequence_w_special = encoded_sequence_dict["input_ids"] + special_tokens_mask = encoded_sequence_dict["special_tokens_mask"] + self.assertEqual(len(special_tokens_mask), len(encoded_sequence_w_special)) + + filtered_sequence = [ + (x if not special_tokens_mask[i] else None) for i, x in enumerate(encoded_sequence_w_special) + ] + filtered_sequence = [x for x in filtered_sequence if x is not None] + self.assertEqual(encoded_sequence, filtered_sequence) + + def test_padding_side_in_kwargs(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + if self.test_rust_tokenizer: + tokenizer_r = self.get_rust_tokenizer(pretrained_name, padding_side="left", **kwargs) + self.assertEqual(tokenizer_r.padding_side, "left") + + tokenizer_r = self.get_rust_tokenizer(pretrained_name, padding_side="right", **kwargs) + self.assertEqual(tokenizer_r.padding_side, "right") + + self.assertRaises( + ValueError, + self.rust_tokenizer_class.from_pretrained, + pretrained_name, + padding_side="unauthorized", + **kwargs, + ) + + if self.test_slow_tokenizer: + tokenizer_p = self.get_tokenizer(pretrained_name, padding_side="left", **kwargs) + self.assertEqual(tokenizer_p.padding_side, "left") + + tokenizer_p = self.get_tokenizer(pretrained_name, padding_side="right", **kwargs) + self.assertEqual(tokenizer_p.padding_side, "right") + + self.assertRaises( + ValueError, + self.tokenizer_class.from_pretrained, + pretrained_name, + padding_side="unauthorized", + **kwargs, + ) + + def test_truncation_side_in_kwargs(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + if self.test_rust_tokenizer: + tokenizer_r = self.get_rust_tokenizer(pretrained_name, truncation_side="left", **kwargs) + self.assertEqual(tokenizer_r.truncation_side, "left") + + tokenizer_r = self.get_rust_tokenizer(pretrained_name, truncation_side="right", **kwargs) + self.assertEqual(tokenizer_r.truncation_side, "right") + + self.assertRaises( + ValueError, + self.rust_tokenizer_class.from_pretrained, + pretrained_name, + truncation_side="unauthorized", + **kwargs, + ) + + if self.test_slow_tokenizer: + tokenizer_p = self.get_tokenizer(pretrained_name, truncation_side="left", **kwargs) + self.assertEqual(tokenizer_p.truncation_side, "left") + + tokenizer_p = self.get_tokenizer(pretrained_name, truncation_side="right", **kwargs) + self.assertEqual(tokenizer_p.truncation_side, "right") + + self.assertRaises( + ValueError, + self.tokenizer_class.from_pretrained, + pretrained_name, + truncation_side="unauthorized", + **kwargs, + ) + + def test_right_and_left_padding(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence = "Sequence" + padding_size = 10 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequence) + + padding_idx = tokenizer.pad_token_id + + # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "right" + encoded_sequence = tokenizer.encode(sequence) + sequence_length = len(encoded_sequence) + padded_sequence = tokenizer.encode( + sequence, max_length=sequence_length + padding_size, padding="max_length" + ) + padded_sequence_length = len(padded_sequence) + self.assertEqual(sequence_length + padding_size, padded_sequence_length) + self.assertEqual(encoded_sequence + [padding_idx] * padding_size, padded_sequence) + + # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + tokenizer.padding_side = "left" + encoded_sequence = tokenizer.encode(sequence) + sequence_length = len(encoded_sequence) + padded_sequence = tokenizer.encode( + sequence, max_length=sequence_length + padding_size, padding="max_length" + ) + padded_sequence_length = len(padded_sequence) + self.assertEqual(sequence_length + padding_size, padded_sequence_length) + self.assertEqual([padding_idx] * padding_size + encoded_sequence, padded_sequence) + + # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_padding' + encoded_sequence = tokenizer.encode(sequence) + sequence_length = len(encoded_sequence) + + tokenizer.padding_side = "right" + padded_sequence_right = tokenizer.encode(sequence, padding=True) + padded_sequence_right_length = len(padded_sequence_right) + self.assertEqual(sequence_length, padded_sequence_right_length) + self.assertEqual(encoded_sequence, padded_sequence_right) + + tokenizer.padding_side = "left" + padded_sequence_left = tokenizer.encode(sequence, padding="longest") + padded_sequence_left_length = len(padded_sequence_left) + self.assertEqual(sequence_length, padded_sequence_left_length) + self.assertEqual(encoded_sequence, padded_sequence_left) + + tokenizer.padding_side = "right" + padded_sequence_right = tokenizer.encode(sequence) + padded_sequence_right_length = len(padded_sequence_right) + self.assertEqual(sequence_length, padded_sequence_right_length) + self.assertEqual(encoded_sequence, padded_sequence_right) + + tokenizer.padding_side = "left" + padded_sequence_left = tokenizer.encode(sequence, padding=False) + padded_sequence_left_length = len(padded_sequence_left) + self.assertEqual(sequence_length, padded_sequence_left_length) + self.assertEqual(encoded_sequence, padded_sequence_left) + + def test_right_and_left_truncation(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence = "This is a test sequence" + + # RIGHT PADDING - Check that it correctly pads when a maximum length is specified along with the padding flag set to True + truncation_size = 3 + tokenizer.truncation_side = "right" + encoded_sequence = tokenizer.encode(sequence, add_special_tokens=False) + sequence_length = len(encoded_sequence) + # Remove EOS/BOS tokens + truncated_sequence = tokenizer.encode( + sequence, max_length=sequence_length - truncation_size, truncation=True, add_special_tokens=False + ) + truncated_sequence_length = len(truncated_sequence) + self.assertEqual(sequence_length, truncated_sequence_length + truncation_size) + self.assertEqual(encoded_sequence[:-truncation_size], truncated_sequence) + + # LEFT PADDING - Check that it correctly pads when a maximum length is specified along with the truncation flag set to True + tokenizer.truncation_side = "left" + sequence_length = len(encoded_sequence) + truncated_sequence = tokenizer.encode( + sequence, max_length=sequence_length - truncation_size, truncation=True, add_special_tokens=False + ) + truncated_sequence_length = len(truncated_sequence) + self.assertEqual(sequence_length, truncated_sequence_length + truncation_size) + self.assertEqual(encoded_sequence[truncation_size:], truncated_sequence) + + # RIGHT & LEFT PADDING - Check that nothing is done for 'longest' and 'no_truncation' + sequence_length = len(encoded_sequence) + + tokenizer.truncation_side = "right" + truncated_sequence_right = tokenizer.encode(sequence, truncation=True, add_special_tokens=False) + truncated_sequence_right_length = len(truncated_sequence_right) + self.assertEqual(sequence_length, truncated_sequence_right_length) + self.assertEqual(encoded_sequence, truncated_sequence_right) + + tokenizer.truncation_side = "left" + truncated_sequence_left = tokenizer.encode( + sequence, truncation="longest_first", add_special_tokens=False + ) + truncated_sequence_left_length = len(truncated_sequence_left) + self.assertEqual(sequence_length, truncated_sequence_left_length) + self.assertEqual(encoded_sequence, truncated_sequence_left) + + tokenizer.truncation_side = "right" + truncated_sequence_right = tokenizer.encode(sequence, add_special_tokens=False) + truncated_sequence_right_length = len(truncated_sequence_right) + self.assertEqual(sequence_length, truncated_sequence_right_length) + self.assertEqual(encoded_sequence, truncated_sequence_right) + + tokenizer.truncation_side = "left" + truncated_sequence_left = tokenizer.encode(sequence, truncation=False, add_special_tokens=False) + truncated_sequence_left_length = len(truncated_sequence_left) + self.assertEqual(sequence_length, truncated_sequence_left_length) + self.assertEqual(encoded_sequence, truncated_sequence_left) + + def test_padding_to_multiple_of(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.pad_token is None: + self.skipTest(reason="No padding token.") + else: + empty_tokens = tokenizer("", padding=True, pad_to_multiple_of=8) + normal_tokens = tokenizer("This is a sample input", padding=True, pad_to_multiple_of=8) + for key, value in empty_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + normal_tokens = tokenizer("This", pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertNotEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # Should also work with truncation + normal_tokens = tokenizer("This", padding=True, truncation=True, pad_to_multiple_of=8) + for key, value in normal_tokens.items(): + self.assertEqual(len(value) % 8, 0, f"BatchEncoding.{key} is not multiple of 8") + + # truncation to something which is not a multiple of pad_to_multiple_of raises an error + self.assertRaises( + ValueError, + tokenizer.__call__, + "This", + padding=True, + truncation=True, + max_length=12, + pad_to_multiple_of=8, + ) + + def test_padding_with_attention_mask(self): + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.pad_token is None: + self.skipTest(reason="No padding token.") + if "attention_mask" not in tokenizer.model_input_names: + self.skipTest(reason="This model does not use attention mask.") + + features = [ + {"input_ids": [1, 2, 3, 4, 5, 6], "attention_mask": [1, 1, 1, 1, 1, 0]}, + {"input_ids": [1, 2, 3], "attention_mask": [1, 1, 0]}, + ] + padded_features = tokenizer.pad(features) + if tokenizer.padding_side == "right": + self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [1, 1, 0, 0, 0, 0]]) + else: + self.assertListEqual(padded_features["attention_mask"], [[1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 0]]) + + @parameterized.expand([(True,), (False,)]) + def test_encode_plus_with_padding(self, use_padding_as_call_kwarg: bool): + """ + This test checks that padding works as expected when tokenizing a sequence. + Padding is expected to have no effect when the input is a single sequence and + the padding-strategy is not `max_length`. Otherwise it pads to the specified max-length + using tokenizer classes `padding_side` attribute. Also, we check that passing `padding_side` + as call time kwarg works same way as when one sets `tokenizer.padding_side` attribute. + """ + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequence = "Sequence" + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequence) + + padding_size = 10 + padding_idx = tokenizer.pad_token_id + token_type_padding_idx = tokenizer.pad_token_type_id + + encoded_sequence = tokenizer.encode_plus(sequence, return_special_tokens_mask=True) + input_ids = encoded_sequence["input_ids"] + special_tokens_mask = encoded_sequence["special_tokens_mask"] + sequence_length = len(input_ids) + + # Test 'longest' and 'no_padding' don't do anything + not_padded_sequence = tokenizer.encode_plus( + sequence, + padding=True, + return_special_tokens_mask=True, + ) + not_padded_input_ids = not_padded_sequence["input_ids"] + + not_padded_special_tokens_mask = not_padded_sequence["special_tokens_mask"] + not_padded_sequence_length = len(not_padded_input_ids) + + self.assertEqual(sequence_length, not_padded_sequence_length) + self.assertEqual(input_ids, not_padded_input_ids) + self.assertEqual(special_tokens_mask, not_padded_special_tokens_mask) + + not_padded_sequence = tokenizer.encode_plus( + sequence, + padding=False, + return_special_tokens_mask=True, + ) + not_padded_input_ids = not_padded_sequence["input_ids"] + + not_padded_special_tokens_mask = not_padded_sequence["special_tokens_mask"] + not_padded_sequence_length = len(not_padded_input_ids) + + self.assertEqual(sequence_length, not_padded_sequence_length) + self.assertEqual(input_ids, not_padded_input_ids) + self.assertEqual(special_tokens_mask, not_padded_special_tokens_mask) + + # Test right padding + tokenizer_kwargs_right = { + "max_length": sequence_length + padding_size, + "padding": "max_length", + "return_special_tokens_mask": True, + } + + if not use_padding_as_call_kwarg: + tokenizer.padding_side = "right" + else: + tokenizer_kwargs_right["padding_side"] = "right" + + right_padded_sequence = tokenizer.encode_plus(sequence, **tokenizer_kwargs_right) + right_padded_input_ids = right_padded_sequence["input_ids"] + + right_padded_special_tokens_mask = right_padded_sequence["special_tokens_mask"] + right_padded_sequence_length = len(right_padded_input_ids) + + self.assertEqual(sequence_length + padding_size, right_padded_sequence_length) + self.assertEqual(input_ids + [padding_idx] * padding_size, right_padded_input_ids) + self.assertEqual(special_tokens_mask + [1] * padding_size, right_padded_special_tokens_mask) + + # Test left padding + tokenizer_kwargs_left = { + "max_length": sequence_length + padding_size, + "padding": "max_length", + "return_special_tokens_mask": True, + } + + if not use_padding_as_call_kwarg: + tokenizer.padding_side = "left" + else: + tokenizer_kwargs_left["padding_side"] = "left" + + left_padded_sequence = tokenizer.encode_plus(sequence, **tokenizer_kwargs_left) + left_padded_input_ids = left_padded_sequence["input_ids"] + left_padded_special_tokens_mask = left_padded_sequence["special_tokens_mask"] + left_padded_sequence_length = len(left_padded_input_ids) + + self.assertEqual(sequence_length + padding_size, left_padded_sequence_length) + self.assertEqual([padding_idx] * padding_size + input_ids, left_padded_input_ids) + self.assertEqual([1] * padding_size + special_tokens_mask, left_padded_special_tokens_mask) + + if "token_type_ids" in tokenizer.model_input_names: + token_type_ids = encoded_sequence["token_type_ids"] + left_padded_token_type_ids = left_padded_sequence["token_type_ids"] + right_padded_token_type_ids = right_padded_sequence["token_type_ids"] + + self.assertEqual( + token_type_ids + [token_type_padding_idx] * padding_size, right_padded_token_type_ids + ) + self.assertEqual( + [token_type_padding_idx] * padding_size + token_type_ids, left_padded_token_type_ids + ) + + if "attention_mask" in tokenizer.model_input_names: + attention_mask = encoded_sequence["attention_mask"] + right_padded_attention_mask = right_padded_sequence["attention_mask"] + left_padded_attention_mask = left_padded_sequence["attention_mask"] + + self.assertEqual(attention_mask + [0] * padding_size, right_padded_attention_mask) + self.assertEqual([0] * padding_size + attention_mask, left_padded_attention_mask) + + def test_padding_warning_message_fast_tokenizer(self): + if not self.test_rust_tokenizer: + self.skipTest(reason="test_rust_tokenizer is set to False") + + sequence = "This is a text" + + tokenizer_fast = self.get_rust_tokenizer() + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer_fast, sequence) + + encoding_fast = tokenizer_fast(sequence) + + with self.assertLogs("transformers", level="WARNING") as cm: + tokenizer_fast.pad(encoding_fast) + self.assertEqual(len(cm.records), 1) + self.assertIn( + "Please note that with a fast tokenizer, using the `__call__` method is faster than using a method to" + " encode the text followed by a call to the `pad` method to get a padded encoding.", + cm.records[0].message, + ) + + if not self.test_slow_tokenizer: + self.skipTest(reason="test_slow_tokenizer is set to False") + + tokenizer_slow = self.get_tokenizer() + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer_slow, sequence) + + encoding_slow = tokenizer_slow(sequence) + + with self.assertLogs(level="WARNING") as cm: + # We want to assert there are no warnings, but the 'assertLogs' method does not support that. + # Therefore, we are adding a dummy warning, and then we will assert it is the only warning. + logger.warning("Dummy warning") + tokenizer_slow.pad(encoding_slow) + self.assertEqual(len(cm.records), 1) + self.assertIn( + "Dummy warning", + cm.records[0].message, + ) + + def test_separate_tokenizers(self): + # This tests that tokenizers don't impact others. Unfortunately the case where it fails is when + # we're loading an S3 configuration from a pre-trained identifier, and we have no way of testing those today. + + tokenizers = self.get_tokenizers(random_argument=True) + new_tokenizers = self.get_tokenizers(random_argument=False) + + for tokenizer, new_tokenizer in zip(tokenizers, new_tokenizers): + with self.subTest(f"{tokenizer.__class__.__name__}"): + self.assertTrue(tokenizer.init_kwargs["random_argument"]) + self.assertTrue(tokenizer.init_kwargs["random_argument"]) + self.assertFalse(new_tokenizer.init_kwargs["random_argument"]) + + def test_get_vocab(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + vocab_dict = tokenizer.get_vocab() + self.assertIsInstance(vocab_dict, dict) + self.assertGreaterEqual(len(tokenizer), len(vocab_dict)) + + vocab = [tokenizer.convert_ids_to_tokens(i) for i in range(len(tokenizer))] + self.assertEqual(len(vocab), len(tokenizer)) + + tokenizer.add_tokens(["asdfasdfasdfasdf"]) + vocab = [tokenizer.convert_ids_to_tokens(i) for i in range(len(tokenizer))] + self.assertEqual(len(vocab), len(tokenizer)) + + def test_conversion_reversible(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + vocab = tokenizer.get_vocab() + for word, ind in vocab.items(): + if word == tokenizer.unk_token: + continue + self.assertEqual(tokenizer.convert_tokens_to_ids(word), ind) + self.assertEqual(tokenizer.convert_ids_to_tokens(ind), word) + + def test_call(self): + # Tests that all call wrap to encode_plus and batch_encode_plus + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + # Test not batched + encoded_sequences_1 = tokenizer.encode_plus(sequences[0]) + encoded_sequences_2 = tokenizer(sequences[0]) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + # Test not batched pairs + encoded_sequences_1 = tokenizer.encode_plus(sequences[0], sequences[1]) + encoded_sequences_2 = tokenizer(sequences[0], sequences[1]) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + # Test batched + encoded_sequences_1 = tokenizer.batch_encode_plus(sequences) + encoded_sequences_2 = tokenizer(sequences) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + # Test batched pairs + encoded_sequences_1 = tokenizer.batch_encode_plus(list(zip(sequences, sequences))) + encoded_sequences_2 = tokenizer(sequences, sequences) + self.assertEqual(encoded_sequences_1, encoded_sequences_2) + + def test_batch_encode_plus_batch_sequence_length(self): + # Tests that all encoded values have the correct size + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + encoded_sequences = [tokenizer.encode_plus(sequence) for sequence in sequences] + encoded_sequences_batch = tokenizer.batch_encode_plus(sequences, padding=False) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + maximum_length = len( + max([encoded_sequence["input_ids"] for encoded_sequence in encoded_sequences], key=len) + ) + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences_padded = [ + tokenizer.encode_plus(sequence, max_length=maximum_length, padding="max_length") + for sequence in sequences + ] + + encoded_sequences_batch_padded = tokenizer.batch_encode_plus(sequences, padding=True) + self.assertListEqual( + encoded_sequences_padded, + self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch_padded), + ) + + # check 'longest' is unsensitive to a max length + encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(sequences, padding=True) + encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus( + sequences, max_length=maximum_length + 10, padding="longest" + ) + for key in encoded_sequences_batch_padded_1: + self.assertListEqual( + encoded_sequences_batch_padded_1[key], + encoded_sequences_batch_padded_2[key], + ) + + # check 'no_padding' is unsensitive to a max length + encoded_sequences_batch_padded_1 = tokenizer.batch_encode_plus(sequences, padding=False) + encoded_sequences_batch_padded_2 = tokenizer.batch_encode_plus( + sequences, max_length=maximum_length + 10, padding=False + ) + for key in encoded_sequences_batch_padded_1: + self.assertListEqual( + encoded_sequences_batch_padded_1[key], + encoded_sequences_batch_padded_2[key], + ) + + @require_tokenizers + def test_added_token_are_matched_longest_first(self): + if not self.test_slow_tokenizer: + self.skipTest(reason="This test is only for slow tokenizers") + + tokenizers = self.get_tokenizers(fast=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + try: + tokenizer.add_tokens([AddedToken("extra_id_1")]) + tokenizer.add_tokens([AddedToken("extra_id_100")]) + except Exception: + # Canine cannot add tokens which are not codepoints + self.skipTest(reason="Cannot add those Added tokens") + + # XXX: This used to split on `extra_id_1` first we're matching + # longest first now. + tokens = tokenizer.tokenize("This is some extra_id_100") + self.assertIn("extra_id_100", tokens) + + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokenizer.add_tokens([AddedToken("extra_id_100")]) + tokenizer.add_tokens([AddedToken("extra_id_1")]) + + tokens = tokenizer.tokenize("This is some extra_id_100") + self.assertIn("extra_id_100", tokens) + + @require_tokenizers + def test_added_token_serializable(self): + # TODO this is tested 10_000 times.... + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + new_token = AddedToken("new_token", lstrip=True) + tokenizer.add_tokens([new_token]) + + with tempfile.TemporaryDirectory() as tmp_dir_name: + tokenizer.save_pretrained(tmp_dir_name) + tokenizer.from_pretrained(tmp_dir_name) + + def test_batch_encode_plus_padding(self): + # Test that padded sequences are equivalent between batch_encode_plus and encode_plus + + # Right padding tests + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + max_length = 100 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences = [ + tokenizer.encode_plus(sequence, max_length=max_length, padding="max_length") + for sequence in sequences + ] + encoded_sequences_batch = tokenizer.batch_encode_plus( + sequences, max_length=max_length, padding="max_length" + ) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + # Left padding tests + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokenizer.padding_side = "left" + sequences = [ + "Testing batch encode plus", + "Testing batch encode plus with different sequence lengths", + "Testing batch encode plus with different sequence lengths correctly pads", + ] + + max_length = 100 + + # check correct behaviour if no pad_token_id exists and add it eventually + self._check_no_pad_token_padding(tokenizer, sequences) + + encoded_sequences = [ + tokenizer.encode_plus(sequence, max_length=max_length, padding="max_length") + for sequence in sequences + ] + encoded_sequences_batch = tokenizer.batch_encode_plus( + sequences, max_length=max_length, padding="max_length" + ) + self.assertListEqual( + encoded_sequences, self.convert_batch_encode_plus_format_to_encode_plus(encoded_sequences_batch) + ) + + def test_pretokenized_inputs(self): + # Test when inputs are pretokenized + + tokenizers = self.get_tokenizers(do_lower_case=False) # , add_prefix_space=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if hasattr(tokenizer, "add_prefix_space") and not tokenizer.add_prefix_space: + continue + + # Prepare a sequence from our tokenizer vocabulary + sequence, ids = self.get_clean_sequence(tokenizer, with_prefix_space=True, max_length=20) + # sequence = " " + sequence # To be sure the byte-level tokenizers are feeling good + token_sequence = sequence.split() + # sequence_no_prefix_space = sequence.strip() + + # Test encode for pretokenized inputs + output = tokenizer.encode(token_sequence, is_split_into_words=True, add_special_tokens=False) + output_sequence = tokenizer.encode(sequence, add_special_tokens=False) + self.assertEqual(output, output_sequence) + + output = tokenizer.encode(token_sequence, is_split_into_words=True, add_special_tokens=True) + output_sequence = tokenizer.encode(sequence, add_special_tokens=True) + self.assertEqual(output, output_sequence) + + # Test encode_plus for pretokenized inputs + output = tokenizer.encode_plus(token_sequence, is_split_into_words=True, add_special_tokens=False) + output_sequence = tokenizer.encode_plus(sequence, add_special_tokens=False) + for key in output: + self.assertEqual(output[key], output_sequence[key]) + output = tokenizer.encode_plus(token_sequence, is_split_into_words=True, add_special_tokens=True) + output_sequence = tokenizer.encode_plus(sequence, add_special_tokens=True) + for key in output: + self.assertEqual(output[key], output_sequence[key]) + + # Test batch_encode_plus for pretokenized inputs + sequence_batch = [sequence.strip()] * 2 + [sequence.strip() + " " + sequence.strip()] + token_sequence_batch = [s.split() for s in sequence_batch] + sequence_batch_cleaned_up_spaces = [" " + " ".join(s) for s in token_sequence_batch] + + output = tokenizer.batch_encode_plus( + token_sequence_batch, is_split_into_words=True, add_special_tokens=False + ) + output_sequence = tokenizer.batch_encode_plus( + sequence_batch_cleaned_up_spaces, add_special_tokens=False + ) + for key in output: + self.assertEqual(output[key], output_sequence[key]) + output = tokenizer.batch_encode_plus( + token_sequence_batch, is_split_into_words=True, add_special_tokens=True + ) + output_sequence = tokenizer.batch_encode_plus( + sequence_batch_cleaned_up_spaces, add_special_tokens=True + ) + for key in output: + self.assertEqual(output[key], output_sequence[key]) + + # Test encode for pretokenized inputs pairs + output = tokenizer.encode( + token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=False + ) + output_sequence = tokenizer.encode(sequence, sequence, add_special_tokens=False) + self.assertEqual(output, output_sequence) + output = tokenizer.encode( + token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=True + ) + output_sequence = tokenizer.encode(sequence, sequence, add_special_tokens=True) + self.assertEqual(output, output_sequence) + + # Test encode_plus for pretokenized inputs pairs + output = tokenizer.encode_plus( + token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=False + ) + output_sequence = tokenizer.encode_plus(sequence, sequence, add_special_tokens=False) + for key in output: + self.assertEqual(output[key], output_sequence[key]) + output = tokenizer.encode_plus( + token_sequence, token_sequence, is_split_into_words=True, add_special_tokens=True + ) + output_sequence = tokenizer.encode_plus(sequence, sequence, add_special_tokens=True) + for key in output: + self.assertEqual(output[key], output_sequence[key]) + + # Test batch_encode_plus for pretokenized inputs pairs + sequence_pair_batch = [(sequence.strip(), sequence.strip())] * 2 + [ + (sequence.strip() + " " + sequence.strip(), sequence.strip()) + ] + token_sequence_pair_batch = [tuple(s.split() for s in pair) for pair in sequence_pair_batch] + sequence_pair_batch_cleaned_up_spaces = [ + tuple(" " + " ".join(s) for s in pair) for pair in token_sequence_pair_batch + ] + + output = tokenizer.batch_encode_plus( + token_sequence_pair_batch, is_split_into_words=True, add_special_tokens=False + ) + output_sequence = tokenizer.batch_encode_plus( + sequence_pair_batch_cleaned_up_spaces, add_special_tokens=False + ) + for key in output: + self.assertEqual(output[key], output_sequence[key]) + output = tokenizer.batch_encode_plus( + token_sequence_pair_batch, is_split_into_words=True, add_special_tokens=True + ) + output_sequence = tokenizer.batch_encode_plus( + sequence_pair_batch_cleaned_up_spaces, add_special_tokens=True + ) + for key in output: + self.assertEqual(output[key], output_sequence[key]) + + def test_prepare_for_model(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + string_sequence = "Testing the prepare_for_model method." + ids = tokenizer.encode(string_sequence, add_special_tokens=False) + prepared_input_dict = tokenizer.prepare_for_model(ids, add_special_tokens=True) + + input_dict = tokenizer.encode_plus(string_sequence, add_special_tokens=True) + + self.assertEqual(input_dict, prepared_input_dict) + + def test_batch_encode_plus_overflowing_tokens(self): + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + string_sequences = ["Testing the prepare_for_model method.", "Test"] + + if tokenizer.pad_token is None: + tokenizer.add_special_tokens({"pad_token": "[PAD]"}) + + tokenizer.batch_encode_plus( + string_sequences, return_overflowing_tokens=True, truncation=True, padding=True, max_length=3 + ) + + def _check_no_pad_token_padding(self, tokenizer, sequences): + # if tokenizer does not have pad_token_id, an error should be thrown + if tokenizer.pad_token_id is None: + with self.assertRaises(ValueError): + if isinstance(sequences, list): + tokenizer.batch_encode_plus(sequences, padding="longest") + else: + tokenizer.encode_plus(sequences, padding=True) + + # add pad_token_id to pass subsequent tests + tokenizer.add_special_tokens({"pad_token": ""}) + + @require_torch + @slow + def test_torch_encode_plus_sent_to_model(self): + import torch + + from transformers import MODEL_MAPPING, TOKENIZER_MAPPING + + MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING) + + tokenizers = self.get_tokenizers(do_lower_case=False) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING: + self.skipTest(f"{tokenizer.__class__.__name__} is not in the MODEL_TOKENIZER") + + config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__] + config = config_class() + + if config.is_encoder_decoder or config.pad_token_id is None: + self.skipTest(reason="Model is not an encoder-decoder model or has no set pad token id") + + model = model_class(config) + + # Make sure the model contains at least the full vocabulary size in its embedding matrix + is_using_common_embeddings = hasattr(model.get_input_embeddings(), "weight") + if is_using_common_embeddings: + self.assertGreaterEqual(model.get_input_embeddings().weight.shape[0], len(tokenizer)) + + # Build sequence + first_ten_tokens = list(tokenizer.get_vocab().keys())[:10] + sequence = " ".join(first_ten_tokens) + encoded_sequence = tokenizer.encode_plus(sequence, return_tensors="pt") + + # Ensure that the BatchEncoding.to() method works. + encoded_sequence.to(model.device) + + batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors="pt") + # This should not fail + + with torch.no_grad(): # saves some time + model(**encoded_sequence) + model(**batch_encoded_sequence) + + # if self.test_rust_tokenizer: + # fast_tokenizer = self.get_rust_tokenizer() + # encoded_sequence_fast = fast_tokenizer.encode_plus(sequence, return_tensors="pt") + # batch_encoded_sequence_fast = fast_tokenizer.batch_encode_plus([sequence, sequence], return_tensors="pt") + # # This should not fail + # model(**encoded_sequence_fast) + # model(**batch_encoded_sequence_fast) + + @require_torch + @slow + def test_np_encode_plus_sent_to_model(self): + from transformers import MODEL_MAPPING, TOKENIZER_MAPPING + + MODEL_TOKENIZER_MAPPING = merge_model_tokenizer_mappings(MODEL_MAPPING, TOKENIZER_MAPPING) + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + if tokenizer.__class__ not in MODEL_TOKENIZER_MAPPING: + self.skipTest(f"{tokenizer.__class__.__name__} is not in the MODEL_TOKENIZER_MAPPING") + + config_class, model_class = MODEL_TOKENIZER_MAPPING[tokenizer.__class__] + config = config_class() + + if config.is_encoder_decoder or config.pad_token_id is None: + self.skipTest("Model is not an encoder-decoder model or has no set pad token id") + + # Build sequence + first_ten_tokens = list(tokenizer.get_vocab().keys())[:10] + sequence = " ".join(first_ten_tokens) + encoded_sequence = tokenizer.encode_plus(sequence, return_tensors="np") + batch_encoded_sequence = tokenizer.batch_encode_plus([sequence, sequence], return_tensors="np") + + # This is currently here to make ruff happy ! + if encoded_sequence is None: + raise ValueError("Cannot convert list to numpy tensor on encode_plus()") + + if batch_encoded_sequence is None: + raise ValueError("Cannot convert list to numpy tensor on batch_encode_plus()") + + if self.test_rust_tokenizer: + fast_tokenizer = self.get_rust_tokenizer() + encoded_sequence_fast = fast_tokenizer.encode_plus(sequence, return_tensors="np") + batch_encoded_sequence_fast = fast_tokenizer.batch_encode_plus( + [sequence, sequence], return_tensors="np" + ) + + # This is currently here to make ruff happy ! + if encoded_sequence_fast is None: + raise ValueError("Cannot convert list to numpy tensor on encode_plus() (fast)") + + if batch_encoded_sequence_fast is None: + raise ValueError("Cannot convert list to numpy tensor on batch_encode_plus() (fast)") + + @require_torch + def test_prepare_seq2seq_batch(self): + if not self.test_seq2seq: + self.skipTest(reason="test_seq2seq is set to False") + + tokenizers = self.get_tokenizers() + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + # Longer text that will definitely require truncation. + src_text = [ + " UN Chief Says There Is No Military Solution in Syria", + " Secretary-General Ban Ki-moon says his response to Russia's stepped up military support for" + " Syria is that 'there is no military solution' to the nearly five-year conflict and more weapons" + " will only worsen the violence and misery for millions of people.", + ] + tgt_text = [ + "Şeful ONU declară că nu există o soluţie militară în Siria", + "Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al" + ' Rusiei pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi' + " că noi arme nu vor face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.", + ] + try: + batch = tokenizer.prepare_seq2seq_batch( + src_texts=src_text, + tgt_texts=tgt_text, + max_length=3, + max_target_length=10, + return_tensors="pt", + src_lang="en_XX", # this should be ignored (for all but mbart) but not cause an error + ) + except NotImplementedError: + self.skipTest(reason="Encountered NotImplementedError calling prepare_seq2seq_batch") + self.assertEqual(batch.input_ids.shape[1], 3) + self.assertEqual(batch.labels.shape[1], 10) + # max_target_length will default to max_length if not specified + batch = tokenizer.prepare_seq2seq_batch( + src_text, tgt_texts=tgt_text, max_length=3, return_tensors="pt" + ) + self.assertEqual(batch.input_ids.shape[1], 3) + self.assertEqual(batch.labels.shape[1], 3) + + batch_encoder_only = tokenizer.prepare_seq2seq_batch( + src_texts=src_text, max_length=3, max_target_length=10, return_tensors="pt" + ) + self.assertEqual(batch_encoder_only.input_ids.shape[1], 3) + self.assertEqual(batch_encoder_only.attention_mask.shape[1], 3) + self.assertNotIn("decoder_input_ids", batch_encoder_only) + + def test_is_fast(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + # Check is_fast is set correctly + self.assertTrue(tokenizer_r.is_fast) + + if self.test_slow_tokenizer: + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + self.assertFalse(tokenizer_p.is_fast) + + def test_fast_only_inputs(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + + # Ensure None raise an error + self.assertRaises(TypeError, tokenizer_r.tokenize, None) + self.assertRaises(TypeError, tokenizer_r.encode, None) + self.assertRaises(TypeError, tokenizer_r.encode_plus, None) + self.assertRaises(TypeError, tokenizer_r.batch_encode_plus, None) + + def test_alignement_methods(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + + words = ["Wonderful", "no", "inspiration", "example", "with", "subtoken"] + text = " ".join(words) + batch_size = 3 + + encoding = tokenizer_r.encode_plus(text, add_special_tokens=False) + + batch_encoding = tokenizer_r.batch_encode_plus([text] * batch_size, add_special_tokens=False) + num_tokens = len(encoding["input_ids"]) + + last_word_index = len(words) - 1 + last_token_index = num_tokens - 1 + last_batch_index = batch_size - 1 + last_char_index = len(text) - 1 + + # words, tokens + self.assertEqual(len(encoding.words(0)), num_tokens) + self.assertEqual(max(encoding.words(0)), last_word_index) + self.assertEqual(min(encoding.words(0)), 0) + self.assertEqual(len(batch_encoding.words(last_batch_index)), num_tokens) + self.assertEqual(max(batch_encoding.words(last_batch_index)), last_word_index) + self.assertEqual(min(batch_encoding.words(last_batch_index)), 0) + self.assertEqual(len(encoding.tokens(0)), num_tokens) + + # Assert token_to_word + self.assertEqual(encoding.token_to_word(0), 0) + self.assertEqual(encoding.token_to_word(0, 0), 0) + self.assertEqual(encoding.token_to_word(last_token_index), last_word_index) + self.assertEqual(encoding.token_to_word(0, last_token_index), last_word_index) + self.assertEqual(batch_encoding.token_to_word(1, 0), 0) + self.assertEqual(batch_encoding.token_to_word(0, last_token_index), last_word_index) + self.assertEqual(batch_encoding.token_to_word(last_batch_index, last_token_index), last_word_index) + + # Assert word_to_tokens + self.assertEqual(encoding.word_to_tokens(0).start, 0) + self.assertEqual(encoding.word_to_tokens(0, 0).start, 0) + self.assertEqual(encoding.word_to_tokens(last_word_index).end, last_token_index + 1) + self.assertEqual(encoding.word_to_tokens(0, last_word_index).end, last_token_index + 1) + self.assertEqual(batch_encoding.word_to_tokens(1, 0).start, 0) + self.assertEqual(batch_encoding.word_to_tokens(0, last_word_index).end, last_token_index + 1) + self.assertEqual( + batch_encoding.word_to_tokens(last_batch_index, last_word_index).end, last_token_index + 1 + ) + + # Assert token_to_chars + self.assertEqual(encoding.token_to_chars(0).start, 0) + self.assertEqual(encoding.token_to_chars(0, 0).start, 0) + self.assertEqual(encoding.token_to_chars(last_token_index).end, last_char_index + 1) + self.assertEqual(encoding.token_to_chars(0, last_token_index).end, last_char_index + 1) + self.assertEqual(batch_encoding.token_to_chars(1, 0).start, 0) + self.assertEqual(batch_encoding.token_to_chars(0, last_token_index).end, last_char_index + 1) + self.assertEqual( + batch_encoding.token_to_chars(last_batch_index, last_token_index).end, last_char_index + 1 + ) + + # Assert char_to_token + self.assertEqual(encoding.char_to_token(0), 0) + self.assertEqual(encoding.char_to_token(0, 0), 0) + self.assertEqual(encoding.char_to_token(last_char_index), last_token_index) + self.assertEqual(encoding.char_to_token(0, last_char_index), last_token_index) + self.assertEqual(batch_encoding.char_to_token(1, 0), 0) + self.assertEqual(batch_encoding.char_to_token(0, last_char_index), last_token_index) + self.assertEqual(batch_encoding.char_to_token(last_batch_index, last_char_index), last_token_index) + + # Assert char_to_word + self.assertEqual(encoding.char_to_word(0), 0) + self.assertEqual(encoding.char_to_word(0, 0), 0) + self.assertEqual(encoding.char_to_word(last_char_index), last_word_index) + self.assertEqual(encoding.char_to_word(0, last_char_index), last_word_index) + self.assertEqual(batch_encoding.char_to_word(1, 0), 0) + self.assertEqual(batch_encoding.char_to_word(0, last_char_index), last_word_index) + self.assertEqual(batch_encoding.char_to_word(last_batch_index, last_char_index), last_word_index) + + # Assert word_to_chars + self.assertEqual(encoding.word_to_chars(0).start, 0) + self.assertEqual(encoding.word_to_chars(0, 0).start, 0) + self.assertEqual(encoding.word_to_chars(last_word_index).end, last_char_index + 1) + self.assertEqual(encoding.word_to_chars(0, last_word_index).end, last_char_index + 1) + self.assertEqual(batch_encoding.word_to_chars(1, 0).start, 0) + self.assertEqual(batch_encoding.word_to_chars(0, last_word_index).end, last_char_index + 1) + self.assertEqual( + batch_encoding.word_to_chars(last_batch_index, last_word_index).end, last_char_index + 1 + ) + + # Assert token_to_sequence + self.assertEqual(encoding.token_to_sequence(num_tokens // 2), 0) + self.assertEqual(encoding.token_to_sequence(0, num_tokens // 2), 0) + self.assertEqual(batch_encoding.token_to_sequence(1, num_tokens // 2), 0) + self.assertEqual(batch_encoding.token_to_sequence(0, num_tokens // 2), 0) + self.assertEqual(batch_encoding.token_to_sequence(last_batch_index, num_tokens // 2), 0) + + # Pair of input sequences + + words = ["Wonderful", "no", "inspiration", "example", "with", "subtoken"] + text = " ".join(words) + pair_words = ["Amazing", "example", "full", "of", "inspiration"] + pair_text = " ".join(pair_words) + batch_size = 3 + index_word_in_first_seq = words.index("inspiration") + index_word_in_pair_seq = pair_words.index("inspiration") + index_char_in_first_seq = text.find("inspiration") + index_char_in_pair_seq = pair_text.find("inspiration") + + pair_encoding = tokenizer_r.encode_plus(text, pair_text, add_special_tokens=False) + + pair_batch_encoding = tokenizer_r.batch_encode_plus( + [(text, pair_text)] * batch_size, add_special_tokens=False + ) + num_tokens = len(encoding["input_ids"]) + + last_word_index = len(words) - 1 + last_token_index = num_tokens - 1 + last_batch_index = batch_size - 1 + last_char_index = len(text) - 1 + + # Assert word_to_tokens + self.assertNotEqual( + pair_encoding.word_to_tokens(index_word_in_first_seq, sequence_index=0).start, + pair_encoding.word_to_tokens(index_word_in_pair_seq, sequence_index=1).start, + ) + self.assertEqual( + pair_encoding["input_ids"][ + pair_encoding.word_to_tokens(index_word_in_first_seq, sequence_index=0).start + ], + pair_encoding["input_ids"][ + pair_encoding.word_to_tokens(index_word_in_pair_seq, sequence_index=1).start + ], + ) + self.assertNotEqual( + pair_batch_encoding.word_to_tokens(1, index_word_in_first_seq, sequence_index=0).start, + pair_batch_encoding.word_to_tokens(1, index_word_in_pair_seq, sequence_index=1).start, + ) + self.assertEqual( + pair_batch_encoding["input_ids"][1][ + pair_batch_encoding.word_to_tokens(1, index_word_in_first_seq, sequence_index=0).start + ], + pair_batch_encoding["input_ids"][1][ + pair_batch_encoding.word_to_tokens(1, index_word_in_pair_seq, sequence_index=1).start + ], + ) + + # Assert char_to_token + self.assertNotEqual( + pair_encoding.char_to_token(index_char_in_first_seq, sequence_index=0), + pair_encoding.char_to_token(index_char_in_pair_seq, sequence_index=1), + ) + self.assertEqual( + pair_encoding["input_ids"][pair_encoding.char_to_token(index_char_in_first_seq, sequence_index=0)], + pair_encoding["input_ids"][pair_encoding.char_to_token(index_char_in_pair_seq, sequence_index=1)], + ) + self.assertNotEqual( + pair_batch_encoding.char_to_token(1, index_char_in_first_seq, sequence_index=0), + pair_batch_encoding.char_to_token(1, index_char_in_pair_seq, sequence_index=1), + ) + self.assertEqual( + pair_batch_encoding["input_ids"][1][ + pair_batch_encoding.char_to_token(1, index_char_in_first_seq, sequence_index=0) + ], + pair_batch_encoding["input_ids"][1][ + pair_batch_encoding.char_to_token(1, index_char_in_pair_seq, sequence_index=1) + ], + ) + + # Assert char_to_word + self.assertNotEqual( + pair_encoding.char_to_word(index_char_in_first_seq, sequence_index=0), + pair_encoding.char_to_word(index_char_in_pair_seq, sequence_index=1), + ) + self.assertEqual( + words[pair_encoding.char_to_word(index_char_in_first_seq, sequence_index=0)], + pair_words[pair_encoding.char_to_word(index_char_in_pair_seq, sequence_index=1)], + ) + self.assertNotEqual( + pair_batch_encoding.char_to_word(1, index_char_in_first_seq, sequence_index=0), + pair_batch_encoding.char_to_word(1, index_char_in_pair_seq, sequence_index=1), + ) + self.assertEqual( + words[pair_batch_encoding.char_to_word(1, index_char_in_first_seq, sequence_index=0)], + pair_words[pair_batch_encoding.char_to_word(1, index_char_in_pair_seq, sequence_index=1)], + ) + + # Assert word_to_chars + self.assertNotEqual( + pair_encoding.word_to_chars(index_word_in_first_seq, sequence_index=0).start, + pair_encoding.word_to_chars(index_word_in_pair_seq, sequence_index=1).start, + ) + self.assertEqual( + text[pair_encoding.word_to_chars(index_word_in_first_seq, sequence_index=0).start], + pair_text[pair_encoding.word_to_chars(index_word_in_pair_seq, sequence_index=1).start], + ) + self.assertNotEqual( + pair_batch_encoding.word_to_chars(1, index_word_in_first_seq, sequence_index=0).start, + pair_batch_encoding.word_to_chars(1, index_word_in_pair_seq, sequence_index=1).start, + ) + self.assertEqual( + text[pair_batch_encoding.word_to_chars(1, index_word_in_first_seq, sequence_index=0).start], + pair_text[pair_batch_encoding.word_to_chars(1, index_word_in_pair_seq, sequence_index=1).start], + ) + + # Assert token_to_sequence + pair_encoding = tokenizer_r.encode_plus(text, pair_text, add_special_tokens=True) + + pair_sequence_ids = [ + pair_encoding.token_to_sequence(i) for i in range(len(pair_encoding["input_ids"])) + ] + self.assertIn(0, pair_sequence_ids) + self.assertIn(1, pair_sequence_ids) + if tokenizer_r.num_special_tokens_to_add(pair=True): + self.assertIn(None, pair_sequence_ids) + + pair_batch_encoding = tokenizer_r.batch_encode_plus( + [(text, pair_text)] * batch_size, add_special_tokens=True + ) + pair_batch_sequence_ids = [ + pair_batch_encoding.token_to_sequence(1, i) + for i in range(len(pair_batch_encoding["input_ids"][0])) + ] + self.assertIn(0, pair_batch_sequence_ids) + self.assertIn(1, pair_batch_sequence_ids) + if tokenizer_r.num_special_tokens_to_add(pair=True): + self.assertIn(None, pair_batch_sequence_ids) + + def test_tokenization_python_rust_equals(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + + # Ensure basic input match + input_p = tokenizer_p.encode_plus(self._data) + input_r = tokenizer_r.encode_plus(self._data) + + for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()): + self.assertSequenceEqual(input_p[key], input_r[key]) + + input_pairs_p = tokenizer_p.encode_plus(self._data, self._data) + input_pairs_r = tokenizer_r.encode_plus(self._data, self._data) + + for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()): + self.assertSequenceEqual(input_pairs_p[key], input_pairs_r[key]) + + # Ensure truncation match + input_p = tokenizer_p.encode_plus(self._data, max_length=512, truncation=True) + input_r = tokenizer_r.encode_plus(self._data, max_length=512, truncation=True) + + for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()): + self.assertSequenceEqual(input_p[key], input_r[key]) + + # Ensure truncation with stride match + input_p = tokenizer_p.encode_plus( + self._data, max_length=512, truncation=True, stride=3, return_overflowing_tokens=True + ) + input_r = tokenizer_r.encode_plus( + self._data, max_length=512, truncation=True, stride=3, return_overflowing_tokens=True + ) + + for key in filter(lambda x: x in ["input_ids", "token_type_ids", "attention_mask"], input_p.keys()): + self.assertSequenceEqual(input_p[key], input_r[key][0]) + + def test_num_special_tokens_to_add_equal(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + + # Check we have the same number of added_tokens for both pair and non-pair inputs. + self.assertEqual( + tokenizer_r.num_special_tokens_to_add(False), tokenizer_p.num_special_tokens_to_add(False) + ) + self.assertEqual( + tokenizer_r.num_special_tokens_to_add(True), tokenizer_p.num_special_tokens_to_add(True) + ) + + def test_max_length_equal(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + + # Check we have the correct max_length for both pair and non-pair inputs. + self.assertEqual(tokenizer_r.max_len_single_sentence, tokenizer_p.max_len_single_sentence) + self.assertEqual(tokenizer_r.max_len_sentences_pair, tokenizer_p.max_len_sentences_pair) + + def test_special_tokens_map_equal(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + # sometimes the tokenizer saved online is not the same + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + + # Assert the set of special tokens match. + self.assertSequenceEqual( + tokenizer_p.special_tokens_map.items(), + tokenizer_r.special_tokens_map.items(), + ) + + def test_add_tokens(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + + vocab_size = len(tokenizer_r) + self.assertEqual(tokenizer_r.add_tokens(""), 0) + self.assertEqual(tokenizer_r.add_tokens("testoken"), 1) + self.assertEqual(tokenizer_r.add_tokens(["testoken1", "testtoken2"]), 2) + self.assertEqual(len(tokenizer_r), vocab_size + 3) + + self.assertEqual(tokenizer_r.add_special_tokens({}), 0) + self.assertEqual(tokenizer_r.add_special_tokens({"bos_token": "[BOS]", "eos_token": "[EOS]"}), 2) + self.assertRaises( + AssertionError, tokenizer_r.add_special_tokens, {"additional_special_tokens": ""} + ) + self.assertEqual(tokenizer_r.add_special_tokens({"additional_special_tokens": [""]}), 1) + self.assertEqual( + tokenizer_r.add_special_tokens({"additional_special_tokens": ["", ""]}), 2 + ) + self.assertIn("", tokenizer_r.special_tokens_map["additional_special_tokens"]) + self.assertIsInstance(tokenizer_r.special_tokens_map["additional_special_tokens"], list) + self.assertGreaterEqual(len(tokenizer_r.special_tokens_map["additional_special_tokens"]), 2) + + self.assertEqual(len(tokenizer_r), vocab_size + 8) + + def test_offsets_mapping(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + + text = "Wonderful no inspiration example with subtoken" + pair = "Along with an awesome pair" + + # No pair + tokens_with_offsets = tokenizer_r.encode_plus( + text, return_special_tokens_mask=True, return_offsets_mapping=True, add_special_tokens=True + ) + added_tokens = tokenizer_r.num_special_tokens_to_add(False) + offsets = tokens_with_offsets["offset_mapping"] + + # Assert there is the same number of tokens and offsets + self.assertEqual(len(offsets), len(tokens_with_offsets["input_ids"])) + + # Assert there is online added_tokens special_tokens + self.assertEqual(sum(tokens_with_offsets["special_tokens_mask"]), added_tokens) + + # Pairs + tokens_with_offsets = tokenizer_r.encode_plus( + text, pair, return_special_tokens_mask=True, return_offsets_mapping=True, add_special_tokens=True + ) + added_tokens = tokenizer_r.num_special_tokens_to_add(True) + offsets = tokens_with_offsets["offset_mapping"] + + # Assert there is the same number of tokens and offsets + self.assertEqual(len(offsets), len(tokens_with_offsets["input_ids"])) + + # Assert there is online added_tokens special_tokens + self.assertEqual(sum(tokens_with_offsets["special_tokens_mask"]), added_tokens) + + def test_batch_encode_dynamic_overflowing(self): + """ + When calling batch_encode with multiple sequence it can returns different number of + overflowing encoding for each sequence: + [ + Sequence 1: [Encoding 1, Encoding 2], + Sequence 2: [Encoding 1], + Sequence 3: [Encoding 1, Encoding 2, ... Encoding N] + ] + This needs to be padded so that it can represented as a tensor + """ + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + tokenizer = self.get_rust_tokenizer(pretrained_name, **kwargs) + + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name}, {tokenizer.__class__.__name__})"): + if is_torch_available(): + returned_tensor = "pt" + else: + self.skipTest(reason="No expected framework (PT) found") + + if not tokenizer.pad_token or tokenizer.pad_token_id < 0: + self.skipTest(reason="This tokenizer has no padding token set, or pad_token_id < 0") + + tokens = tokenizer.encode_plus( + "HuggingFace is solving NLP one commit at a time", + max_length=6, + padding=True, + truncation=True, + return_tensors=returned_tensor, + return_overflowing_tokens=True, + ) + + for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()): + self.assertEqual(len(tokens[key].shape), 2) + + # Mono sample + tokens = tokenizer.batch_encode_plus( + ["HuggingFace is solving NLP one commit at a time"], + max_length=6, + padding=True, + truncation="only_first", + return_tensors=returned_tensor, + return_overflowing_tokens=True, + ) + + for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()): + self.assertEqual(len(tokens[key].shape), 2) + self.assertEqual(tokens[key].shape[-1], 6) + + # Multi sample + tokens = tokenizer.batch_encode_plus( + ["HuggingFace is solving NLP one commit at a time", "Very tiny input"], + max_length=6, + padding=True, + truncation="only_first", + return_tensors=returned_tensor, + return_overflowing_tokens=True, + ) + + for key in filter(lambda x: "overflow_to_sample_mapping" not in x, tokens.keys()): + self.assertEqual(len(tokens[key].shape), 2) + self.assertEqual(tokens[key].shape[-1], 6) + + def test_compare_pretokenized_inputs(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + + if hasattr(tokenizer_p, "add_prefix_space") and not tokenizer_p.add_prefix_space: + continue # Too hard to test for now + + # Input string + pretokenized_input_simple = "This is a sample input".split() + pretokenized_input_pair = "This is a sample pair".split() + + # Test encode for pretokenized inputs + output_r = tokenizer_r.encode( + pretokenized_input_simple, is_split_into_words=True, add_special_tokens=False + ) + output_p = tokenizer_p.encode( + pretokenized_input_simple, is_split_into_words=True, add_special_tokens=False + ) + self.assertEqual(output_p, output_r) + + kwargs = { + "is_split_into_words": True, + # "return_token_type_ids": True, # Use the defaults for each tokenizers + # "return_attention_mask": True, # Use the defaults for each tokenizers + "return_overflowing_tokens": False, + "return_special_tokens_mask": True, + "return_offsets_mapping": False, # Not implemented in python tokenizers + # "add_special_tokens": False, + } + batch_kwargs = { + "is_split_into_words": True, + # "return_token_type_ids": True, # Use the defaults for each tokenizers + # "return_attention_mask": True, # Use the defaults for each tokenizers + "return_overflowing_tokens": False, + "return_special_tokens_mask": True, + "return_offsets_mapping": False, # Not implemented in python tokenizers + # "add_special_tokens": False, + } + # Test encode_plus for pretokenized inputs + output_r = tokenizer_r.encode_plus(pretokenized_input_simple, **kwargs) + output_p = tokenizer_p.encode_plus(pretokenized_input_simple, **kwargs) + for key in output_p: + self.assertEqual(output_p[key], output_r[key]) + + # Test batch_encode_plus for pretokenized inputs + input_batch = ([pretokenized_input_simple] * 2) + [pretokenized_input_simple + pretokenized_input_pair] + output_r = tokenizer_r.batch_encode_plus(input_batch, **batch_kwargs) + output_p = tokenizer_p.batch_encode_plus(input_batch, **batch_kwargs) + for key in output_p: + self.assertEqual(output_p[key], output_r[key]) + + # Test encode for pretokenized inputs pairs + output_r = tokenizer_r.encode( + pretokenized_input_simple, pretokenized_input_pair, is_split_into_words=True + ) + output_p = tokenizer_p.encode( + pretokenized_input_simple, pretokenized_input_pair, is_split_into_words=True + ) + self.assertEqual(output_p, output_r) + + # Test encode_plus for pretokenized inputs + output_r = tokenizer_r.encode_plus(pretokenized_input_simple, pretokenized_input_pair, **kwargs) + output_p = tokenizer_p.encode_plus(pretokenized_input_simple, pretokenized_input_pair, **kwargs) + for key in output_p: + self.assertEqual(output_p[key], output_r[key]) + + # Test batch_encode_plus for pretokenized inputs + input_batch_pair = ([pretokenized_input_simple, pretokenized_input_pair] * 2) + [ + pretokenized_input_simple + pretokenized_input_pair, + pretokenized_input_pair, + ] + output_r = tokenizer_r.batch_encode_plus(input_batch_pair, **batch_kwargs) + output_p = tokenizer_p.batch_encode_plus(input_batch_pair, **batch_kwargs) + for key in output_p: + self.assertEqual(output_p[key], output_r[key]) + + def test_create_token_type_ids(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + input_simple = [1, 2, 3] + input_pair = [1, 2, 3] + + # Generate output + output_r = tokenizer_r.create_token_type_ids_from_sequences(input_simple) + output_p = tokenizer_p.create_token_type_ids_from_sequences(input_simple) + self.assertEqual(output_p, output_r) + + # Generate pair output + output_r = tokenizer_r.create_token_type_ids_from_sequences(input_simple, input_pair) + output_p = tokenizer_p.create_token_type_ids_from_sequences(input_simple, input_pair) + self.assertEqual(output_p, output_r) + + def test_build_inputs_with_special_tokens(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + # # Input string + # input_simple = tokenizer_p.tokenize("This is a sample input", add_special_tokens=False) + # input_pair = tokenizer_p.tokenize("This is a sample pair", add_special_tokens=False) + + # # Generate output + # output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple) + # output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple) + # self.assertEqual(output_p, output_r) + + # # Generate pair output + # output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple, input_pair) + # output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple, input_pair) + # self.assertEqual(output_p, output_r) + + input_pairs = [ + ("", ""), + ("", "This is a sample pair"), + ("This is a sample input", ""), + ("This is a sample input", "This is a sample pair"), + ] + + for sample_input, sample_pair in input_pairs: + # Input tokens id + input_simple = tokenizer_p.encode(sample_input, add_special_tokens=False) + input_pair = tokenizer_p.encode(sample_pair, add_special_tokens=False) + + # Generate output + output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple) + output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple) + self.assertEqual(output_p, output_r) + + # Generate pair output + output_r = tokenizer_r.build_inputs_with_special_tokens(input_simple, input_pair) + output_p = tokenizer_p.build_inputs_with_special_tokens(input_simple, input_pair) + self.assertEqual(output_p, output_r) + + def test_padding(self, max_length=50): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + + self.assertEqual(tokenizer_p.pad_token_id, tokenizer_r.pad_token_id) + pad_token_id = tokenizer_p.pad_token_id + + # Encode - Simple input + input_r = tokenizer_r.encode("This is a simple input", max_length=max_length, padding="max_length") + input_p = tokenizer_p.encode("This is a simple input", max_length=max_length, padding="max_length") + self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id) + + input_r = tokenizer_r.encode("This is a simple input", padding="longest") + input_p = tokenizer_p.encode("This is a simple input", padding=True) + self.assert_padded_input_match(input_r, input_p, len(input_r), pad_token_id) + + # Encode - Pair input + input_r = tokenizer_r.encode( + "This is a simple input", "This is a pair", max_length=max_length, padding="max_length" + ) + input_p = tokenizer_p.encode( + "This is a simple input", "This is a pair", max_length=max_length, padding="max_length" + ) + self.assert_padded_input_match(input_r, input_p, max_length, pad_token_id) + input_r = tokenizer_r.encode("This is a simple input", "This is a pair", padding=True) + input_p = tokenizer_p.encode("This is a simple input", "This is a pair", padding="longest") + self.assert_padded_input_match(input_r, input_p, len(input_r), pad_token_id) + + # Encode_plus - Simple input + input_r = tokenizer_r.encode_plus( + "This is a simple input", max_length=max_length, padding="max_length" + ) + input_p = tokenizer_p.encode_plus( + "This is a simple input", max_length=max_length, padding="max_length" + ) + self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id) + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + + input_r = tokenizer_r.encode_plus("This is a simple input", padding="longest") + input_p = tokenizer_p.encode_plus("This is a simple input", padding=True) + self.assert_padded_input_match( + input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id + ) + + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + + # Encode_plus - Pair input + input_r = tokenizer_r.encode_plus( + "This is a simple input", "This is a pair", max_length=max_length, padding="max_length" + ) + input_p = tokenizer_p.encode_plus( + "This is a simple input", "This is a pair", max_length=max_length, padding="max_length" + ) + self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id) + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + input_r = tokenizer_r.encode_plus("This is a simple input", "This is a pair", padding="longest") + input_p = tokenizer_p.encode_plus("This is a simple input", "This is a pair", padding=True) + self.assert_padded_input_match( + input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id + ) + self.assertSequenceEqual(input_r["attention_mask"], input_p["attention_mask"]) + + # Batch_encode_plus - Simple input + input_r = tokenizer_r.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + padding="max_length", + ) + input_p = tokenizer_p.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + padding="max_length", + ) + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + input_r = tokenizer_r.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + padding="longest", + ) + input_p = tokenizer_p.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], + max_length=max_length, + padding=True, + ) + self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id) + + input_r = tokenizer_r.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], padding="longest" + ) + input_p = tokenizer_p.batch_encode_plus( + ["This is a simple input 1", "This is a simple input 2"], padding=True + ) + self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id) + + # Batch_encode_plus - Pair input + input_r = tokenizer_r.batch_encode_plus( + [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ], + max_length=max_length, + truncation=True, + padding="max_length", + ) + input_p = tokenizer_p.batch_encode_plus( + [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ], + max_length=max_length, + truncation=True, + padding="max_length", + ) + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + input_r = tokenizer_r.batch_encode_plus( + [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ], + padding=True, + ) + input_p = tokenizer_p.batch_encode_plus( + [ + ("This is a simple input 1", "This is a simple input 2"), + ("This is a simple pair 1", "This is a simple pair 2"), + ], + padding="longest", + ) + self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id) + + # Using pad on single examples after tokenization + input_r = tokenizer_r.encode_plus("This is a input 1") + input_r = tokenizer_r.pad(input_r) + + input_p = tokenizer_p.encode_plus("This is a input 1") + input_p = tokenizer_p.pad(input_p) + + self.assert_padded_input_match( + input_r["input_ids"], input_p["input_ids"], len(input_r["input_ids"]), pad_token_id + ) + + # Using pad on single examples after tokenization + input_r = tokenizer_r.encode_plus("This is a input 1") + input_r = tokenizer_r.pad(input_r, max_length=max_length, padding="max_length") + + input_p = tokenizer_p.encode_plus("This is a input 1") + input_p = tokenizer_p.pad(input_p, max_length=max_length, padding="max_length") + + self.assert_padded_input_match(input_r["input_ids"], input_p["input_ids"], max_length, pad_token_id) + + # Using pad after tokenization + input_r = tokenizer_r.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_r = tokenizer_r.pad(input_r) + + input_p = tokenizer_p.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_p = tokenizer_p.pad(input_p) + + self.assert_batch_padded_input_match(input_r, input_p, len(input_r["input_ids"][0]), pad_token_id) + + # Using pad after tokenization + input_r = tokenizer_r.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_r = tokenizer_r.pad(input_r, max_length=max_length, padding="max_length") + + input_p = tokenizer_p.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_p = tokenizer_p.pad(input_p, max_length=max_length, padding="max_length") + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + # Test padding nested empty lists (in some use-cases, there is no any token id in the `input_ids` list). + input_r = tokenizer_r.pad({"input_ids": [[], []]}, max_length=max_length, padding="max_length") + input_p = tokenizer_p.pad({"input_ids": [[], []]}, max_length=max_length, padding="max_length") + self.assert_batch_padded_input_match(input_r, input_p, max_length, pad_token_id) + + def test_padding_different_model_input_name(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + self.assertEqual(tokenizer_p.pad_token_id, tokenizer_r.pad_token_id) + pad_token_id = tokenizer_p.pad_token_id + + input_r = tokenizer_r.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + input_p = tokenizer_r.batch_encode_plus( + ["This is a input 1", "This is a much longer input whilch should be padded"] + ) + + # rename encoded batch to "inputs" + input_r["inputs"] = input_r[tokenizer_r.model_input_names[0]] + del input_r[tokenizer_r.model_input_names[0]] + + input_p["inputs"] = input_p[tokenizer_p.model_input_names[0]] + del input_p[tokenizer_p.model_input_names[0]] + + # Renaming `input_ids` to `inputs` + tokenizer_r.model_input_names = ["inputs"] + tokenizer_r.model_input_names[1:] + tokenizer_p.model_input_names = ["inputs"] + tokenizer_p.model_input_names[1:] + + input_r = tokenizer_r.pad(input_r, padding="longest") + input_p = tokenizer_r.pad(input_p, padding="longest") + + max_length = len(input_p["inputs"][0]) + self.assert_batch_padded_input_match( + input_r, input_p, max_length, pad_token_id, model_main_input_name="inputs" + ) + + def test_save_pretrained(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # make sure that all ".json" files are saved in the correct format + for file_path in tokenizer_r_files + tokenizer_p_files: + if os.path.exists(file_path) and file_path.endswith(".json"): + check_json_file_has_correct_format(file_path) + + # Checks it save with the same files + the tokenizer.json file for the fast one + self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files)) + tokenizer_r_files = tuple(f for f in tokenizer_r_files if "tokenizer.json" not in f) + self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + # self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key)) + # self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id")) + + shutil.rmtree(tmpdirname2) + + # Save tokenizer rust, legacy_format=True + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=True) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # Checks it save with the same files + self.assertSequenceEqual(tokenizer_r_files, tokenizer_p_files) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + + shutil.rmtree(tmpdirname2) + + # Save tokenizer rust, legacy_format=False + tmpdirname2 = tempfile.mkdtemp() + + tokenizer_r_files = tokenizer_r.save_pretrained(tmpdirname2, legacy_format=False) + tokenizer_p_files = tokenizer_p.save_pretrained(tmpdirname2) + + # Checks it saved the tokenizer.json file + self.assertTrue(any("tokenizer.json" in f for f in tokenizer_r_files)) + + # Checks everything loads correctly in the same way + tokenizer_rp = tokenizer_r.from_pretrained(tmpdirname2) + tokenizer_pp = tokenizer_p.from_pretrained(tmpdirname2) + + # Check special tokens are set accordingly on Rust and Python + for key in tokenizer_pp.special_tokens_map: + self.assertTrue(hasattr(tokenizer_rp, key)) + + shutil.rmtree(tmpdirname2) + + def test_embeded_special_tokens(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + sentence = "A, AllenNLP sentence." + tokens_r = tokenizer_r.encode_plus( + sentence, + add_special_tokens=True, + ) + tokens_p = tokenizer_p.encode_plus( + sentence, + add_special_tokens=True, + ) + + for key in tokens_p: + self.assertEqual(tokens_r[key], tokens_p[key]) + + if "token_type_ids" in tokens_r: + self.assertEqual(sum(tokens_r["token_type_ids"]), sum(tokens_p["token_type_ids"])) + + tokens_r = tokenizer_r.convert_ids_to_tokens(tokens_r["input_ids"]) + tokens_p = tokenizer_p.convert_ids_to_tokens(tokens_p["input_ids"]) + self.assertSequenceEqual(tokens_r, tokens_p) + + def test_compare_add_special_tokens(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + + simple_num_special_tokens_to_add = tokenizer_r.num_special_tokens_to_add(pair=False) + # pair_num_special_tokens_to_add = tokenizer_r.num_special_tokens_to_add(pair=True) + + for text in ["", " "]: + # tokenize() + no_special_tokens = tokenizer_r.tokenize(text, add_special_tokens=False) + with_special_tokens = tokenizer_r.tokenize(text, add_special_tokens=True) + self.assertEqual( + len(no_special_tokens), len(with_special_tokens) - simple_num_special_tokens_to_add + ) + + # encode() + no_special_tokens = tokenizer_r.encode(text, add_special_tokens=False) + with_special_tokens = tokenizer_r.encode(text, add_special_tokens=True) + self.assertEqual( + len(no_special_tokens), len(with_special_tokens) - simple_num_special_tokens_to_add + ) + + # encode_plus() + no_special_tokens = tokenizer_r.encode_plus(text, add_special_tokens=False) + with_special_tokens = tokenizer_r.encode_plus(text, add_special_tokens=True) + for key in no_special_tokens: + self.assertEqual( + len(no_special_tokens[key]), + len(with_special_tokens[key]) - simple_num_special_tokens_to_add, + ) + + # # batch_encode_plus + no_special_tokens = tokenizer_r.batch_encode_plus([text, text], add_special_tokens=False) + with_special_tokens = tokenizer_r.batch_encode_plus([text, text], add_special_tokens=True) + for key in no_special_tokens: + for i_no, i_with in zip(no_special_tokens[key], with_special_tokens[key]): + self.assertEqual(len(i_no), len(i_with) - simple_num_special_tokens_to_add) + + def test_compare_prepare_for_model(self): + if not self.test_slow_tokenizer: + # as we don't have a slow version, we can't compare the outputs between slow and fast versions + self.skipTest(reason="test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_r = self.get_rust_tokenizer(pretrained_name, **kwargs) + tokenizer_p = self.get_tokenizer(pretrained_name, **kwargs) + string_sequence = "Asserting that both tokenizers are equal" + python_output = tokenizer_p.prepare_for_model( + tokenizer_p.encode(string_sequence, add_special_tokens=False) + ) + rust_output = tokenizer_r.prepare_for_model( + tokenizer_r.encode(string_sequence, add_special_tokens=False) + ) + for key in python_output: + self.assertEqual(python_output[key], rust_output[key]) + + def test_special_tokens_initialization(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + added_tokens = [AddedToken("", lstrip=True)] + tokenizer_r = self.get_rust_tokenizer( + pretrained_name, additional_special_tokens=added_tokens, **kwargs + ) + r_output = tokenizer_r.encode("Hey this is a token") + + special_token_id = tokenizer_r.encode("", add_special_tokens=False)[0] + + self.assertTrue(special_token_id in r_output) + + if self.test_slow_tokenizer: + # in rust fast, you lose the information of the AddedToken when initializing with `additional_special_tokens` + tokenizer_cr = self.get_rust_tokenizer( + pretrained_name, additional_special_tokens=added_tokens, **kwargs, from_slow=True + ) + tokenizer_p = self.get_tokenizer(pretrained_name, additional_special_tokens=added_tokens, **kwargs) + + p_output = tokenizer_p.encode("Hey this is a token") + + cr_output = tokenizer_cr.encode("Hey this is a token") + + self.assertEqual(p_output, r_output) + self.assertEqual(cr_output, r_output) + self.assertTrue(special_token_id in p_output) + self.assertTrue(special_token_id in cr_output) + + def test_special_tokens_initialization_with_non_empty_additional_special_tokens(self): + # This test no longer support rust tokenizers, because the only file that should be looked + # at by the fast tokenizer with the new saving format is `tokenizer_config.json`. + # The previous behaviour is very strange too. Fast tokenizer should not save 3 files, but just one. Can never do slow from fast. + tokenizer_list = [] + if self.test_slow_tokenizer: + tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())) + + for tokenizer_class, tokenizer_utils in tokenizer_list: + with tempfile.TemporaryDirectory() as tmp_dir: + tokenizer_utils.save_pretrained(tmp_dir) + # only legacy save will check this + tokenizer_path = "tokenizer_config.json" + with open(os.path.join(tmp_dir, tokenizer_path), encoding="utf-8") as json_file: + tokenizer_config = json.load(json_file) + + tokenizer_config["additional_special_tokens"] = ["an_additional_special_token"] + + with open(os.path.join(tmp_dir, tokenizer_path), "w", encoding="utf-8") as outfile: + json.dump(tokenizer_config, outfile) + + # the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes + # into account the new value of additional_special_tokens given in the "tokenizer_config.json" and + # "special_tokens_map.json" files + + # TODO ArthurZ ... Ok so for legacy we have to support this I guess..... (special_tokens_map + additional) + tokenizer_without_change_in_init = tokenizer_class.from_pretrained(tmp_dir) + self.assertIn( + "an_additional_special_token", tokenizer_without_change_in_init.additional_special_tokens + ) + self.assertIn("an_additional_special_token", tokenizer_without_change_in_init.get_vocab()) + self.assertEqual( + ["an_additional_special_token"], + tokenizer_without_change_in_init.convert_ids_to_tokens( + tokenizer_without_change_in_init.convert_tokens_to_ids(["an_additional_special_token"]) + ), + ) + + # Now we test that we can change the value of additional_special_tokens in the from_pretrained + new_added_tokens = [AddedToken("a_new_additional_special_token", lstrip=True)] + tokenizer = tokenizer_class.from_pretrained( + tmp_dir, + additional_special_tokens=new_added_tokens, + ) + + self.assertIn("a_new_additional_special_token", tokenizer.additional_special_tokens) + self.assertEqual( + ["a_new_additional_special_token"], + tokenizer.convert_ids_to_tokens( + tokenizer.convert_tokens_to_ids(["a_new_additional_special_token"]) + ), + ) + + def test_training_new_tokenizer(self): + # This feature only exists for fast tokenizers + if not self.test_rust_tokenizer: + self.skipTest(reason="test_rust_tokenizer is set to False") + + tokenizer = self.get_rust_tokenizer() + new_tokenizer = tokenizer.train_new_from_iterator(SMALL_TRAINING_CORPUS, 100) + + # Test we can use the new tokenizer with something not seen during training + inputs = new_tokenizer(["This is the first sentence", "This sentence is different 🤗."]) + self.assertEqual(len(inputs["input_ids"]), 2) + decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True) + expected_result = "This is the first sentence" + + if tokenizer.backend_tokenizer.normalizer is not None: + expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result) + self.assertEqual(expected_result, decoded_input) + + # We check that the parameters of the tokenizer remained the same + # Check we have the same number of added_tokens for both pair and non-pair inputs. + self.assertEqual(tokenizer.num_special_tokens_to_add(False), new_tokenizer.num_special_tokens_to_add(False)) + self.assertEqual(tokenizer.num_special_tokens_to_add(True), new_tokenizer.num_special_tokens_to_add(True)) + + # Check we have the correct max_length for both pair and non-pair inputs. + self.assertEqual(tokenizer.max_len_single_sentence, new_tokenizer.max_len_single_sentence) + self.assertEqual(tokenizer.max_len_sentences_pair, new_tokenizer.max_len_sentences_pair) + + # Assert the set of special tokens match as we didn't ask to change them + self.assertSequenceEqual( + tokenizer.all_special_tokens_extended, + new_tokenizer.all_special_tokens_extended, + ) + + self.assertDictEqual(tokenizer.special_tokens_map, new_tokenizer.special_tokens_map) + + def test_training_new_tokenizer_with_special_tokens_change(self): + # This feature only exists for fast tokenizers + if not self.test_rust_tokenizer: + self.skipTest(reason="test_rust_tokenizer is set to False") + + tokenizer = self.get_rust_tokenizer() + # Test with a special tokens map + class_signature = inspect.signature(tokenizer.__class__) + if "cls_token" in class_signature.parameters: + new_tokenizer = tokenizer.train_new_from_iterator( + SMALL_TRAINING_CORPUS, 100, special_tokens_map={tokenizer.cls_token: ""} + ) + cls_id = new_tokenizer.get_vocab()[""] + self.assertEqual(new_tokenizer.cls_token, "") + self.assertEqual(new_tokenizer.cls_token_id, cls_id) + + # Create a new mapping from the special tokens defined in the original tokenizer + special_tokens_list = SpecialTokensMixin.SPECIAL_TOKENS_ATTRIBUTES.copy() + special_tokens_list.remove("additional_special_tokens") + special_tokens_map = {} + for token in special_tokens_list: + if getattr(tokenizer, token) is not None: + special_token = getattr(tokenizer, token) + special_tokens_map[special_token] = f"{special_token}a" + + # Train new tokenizer + new_tokenizer = tokenizer.train_new_from_iterator( + SMALL_TRAINING_CORPUS, 100, special_tokens_map=special_tokens_map + ) + + # Check the changes + for token in special_tokens_list: + # Get the private one to avoid unnecessary warnings. + if getattr(tokenizer, token) is None: + continue + special_token = getattr(tokenizer, token) + if special_token in special_tokens_map: + new_special_token = getattr(new_tokenizer, token) + self.assertEqual(special_tokens_map[special_token], new_special_token) + + new_id = new_tokenizer.get_vocab()[new_special_token] + self.assertEqual(getattr(new_tokenizer, f"{token}_id"), new_id) + + # Check if the AddedToken / string format has been kept + for special_token in tokenizer.all_special_tokens_extended: + if isinstance(special_token, AddedToken) and special_token.content not in special_tokens_map: + # The special token must appear identically in the list of the new tokenizer. + self.assertTrue( + special_token in new_tokenizer.all_special_tokens_extended, + f"'{special_token}' should be in {new_tokenizer.all_special_tokens_extended}", + ) + elif isinstance(special_token, AddedToken): + # The special token must appear in the list of the new tokenizer as an object of type AddedToken with + # the same parameters as the old AddedToken except the content that the user has requested to change. + special_token_str = special_token.content + new_special_token_str = special_tokens_map[special_token_str] + + find = False + for candidate in new_tokenizer.all_special_tokens_extended: + if ( + isinstance(candidate, AddedToken) + and candidate.content == new_special_token_str + and candidate.lstrip == special_token.lstrip + and candidate.rstrip == special_token.rstrip + and candidate.normalized == special_token.normalized + and candidate.single_word == special_token.single_word + ): + find = True + break + special_token.content = new_special_token_str + self.assertTrue( + find, + f"'{special_token.__repr__()}' should appear as an `AddedToken` in the all_special_tokens_extended = " + f"{[k for k in new_tokenizer.all_special_tokens_extended if str(k) == new_special_token_str]} but it is missing" + ", this means that the new tokenizers did not keep the `rstrip`, `lstrip`, `normalized` etc attributes.", + ) + elif special_token not in special_tokens_map: + # The special token must appear identically in the list of the new tokenizer. + self.assertTrue( + special_token in new_tokenizer.all_special_tokens_extended, + f"'{special_token.__repr__()}' should be in {new_tokenizer.all_special_tokens_extended}", + ) + + else: + # The special token must appear in the list of the new tokenizer as an object of type string. + self.assertTrue(special_tokens_map[special_token] in new_tokenizer.all_special_tokens_extended) + + # Test we can use the new tokenizer with something not seen during training + inputs = new_tokenizer(["This is the first sentence", "This sentence is different 🤗."]) + self.assertEqual(len(inputs["input_ids"]), 2) + decoded_input = new_tokenizer.decode(inputs["input_ids"][0], skip_special_tokens=True) + expected_result = "This is the first sentence" + + if tokenizer.backend_tokenizer.normalizer is not None: + expected_result = tokenizer.backend_tokenizer.normalizer.normalize_str(expected_result) + self.assertEqual(expected_result, decoded_input) + + def test_tokenizer_mismatch_warning(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + with self.assertLogs("transformers", level="WARNING") as cm: + try: + if self.tokenizer_class == BertTokenizer: + AlbertTokenizer.from_pretrained(pretrained_name) + else: + BertTokenizer.from_pretrained(pretrained_name) + except OSError as e: + # Some tokenizer will raised an error before reaching the logged warning because there are no + # corresponding files to load + error_message = str(e) + except (TypeError, AttributeError): + # Some tokenizers cannot be loaded into the target tokenizer at all and errors are returned, + # here we just check that the warning has been logged before the error is raised + pass + finally: + logged_msg_target = ( + "The tokenizer class you load from this checkpoint is not the same type as the class " + "this function is called from." + ) + raised_error_msg_target = "Can't load tokenizer for" + self.assertTrue( + cm.records[0].message.startswith(logged_msg_target) + if len(cm.records) > 0 + else False or raised_error_msg_target in error_message + ) + try: + if self.rust_tokenizer_class == BertTokenizerFast: + AlbertTokenizerFast.from_pretrained(pretrained_name) + else: + BertTokenizerFast.from_pretrained(pretrained_name) + except (TypeError, AttributeError): + # Some tokenizers cannot be loaded into the target tokenizer at all and errors are returned, + # here we just check that the warning has been logged before the error is raised + pass + finally: + self.assertTrue( + cm.records[0].message.startswith( + "The tokenizer class you load from this checkpoint is not the same type as the class" + " this function is called from." + ) + ) + + @require_torch + def test_saving_tokenizer_trainer(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + with tempfile.TemporaryDirectory() as tmp_dir: + # Save the fast tokenizer files in a temporary directory + tokenizer_old = self.get_rust_tokenizer(pretrained_name, **kwargs, use_fast=True) + tokenizer_old.save_pretrained(tmp_dir, legacy_format=False) # save only fast version + + # Initialize toy model for the trainer + model = nn.Module() + + # Load tokenizer from a folder without legacy files + tokenizer = self.rust_tokenizer_class.from_pretrained(tmp_dir) + training_args = TrainingArguments(output_dir=tmp_dir, do_train=True, no_cuda=True) + trainer = Trainer(model=model, args=training_args, processing_class=tokenizer) + + # Should not raise an error + trainer.save_model(os.path.join(tmp_dir, "checkpoint")) + self.assertIn("tokenizer.json", os.listdir(os.path.join(tmp_dir, "checkpoint"))) + + def test_convert_tokens_to_string_format(self): + tokenizers = self.get_tokenizers(fast=True, do_lower_case=True) + for tokenizer in tokenizers: + with self.subTest(f"{tokenizer.__class__.__name__}"): + tokens = ["this", "is", "a", "test"] + string = tokenizer.convert_tokens_to_string(tokens) + + self.assertIsInstance(string, str) + + def test_save_slow_from_fast_and_reload_fast(self): + if not self.test_slow_tokenizer or not self.test_rust_tokenizer: + # we need both slow and fast versions + self.skipTest(reason="test_rust_tokenizer or test_slow_tokenizer is set to False") + + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + with tempfile.TemporaryDirectory() as tmp_dir_1: + # Here we check that even if we have initialized a fast tokenizer with a tokenizer_file we can + # still save only the slow version and use these saved files to rebuild a tokenizer + tokenizer_fast_old_1 = self.get_rust_tokenizer(pretrained_name, **kwargs, use_fast=True) + tokenizer_file = os.path.join(tmp_dir_1, "tokenizer.json") + tokenizer_fast_old_1.backend_tokenizer.save(tokenizer_file) + + tokenizer_fast_old_2 = self.get_rust_tokenizer( + pretrained_name, **kwargs, use_fast=True, tokenizer_file=tokenizer_file + ) + + tokenizer_fast_old_2.save_pretrained(tmp_dir_1, legacy_format=True) # save only slow version + + tokenizer_slow = self.tokenizer_class.from_pretrained(tmp_dir_1) + with tempfile.TemporaryDirectory() as tmp_dir_2: + tokenizer_slow.save_pretrained(tmp_dir_2) + + # Should not raise an error + self.rust_tokenizer_class.from_pretrained(tmp_dir_2) + + def test_split_special_tokens(self): + if not self.test_slow_tokenizer: + self.skipTest(reason="test_slow_tokenizer is set to False") + # Tests the expected appearance (or absence) of special token in encoded output, + # explicit values are not tested because tokenization is model dependent and can change + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + special_token = "" + special_sentence = f"Hey this is a {special_token} token" + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + tokenizer_rust = self.get_rust_tokenizer( + pretrained_name, additional_special_tokens=[special_token], split_special_tokens=True, **kwargs + ) + tokenizer_py = self.get_tokenizer( + pretrained_name, additional_special_tokens=[special_token], split_special_tokens=True, **kwargs + ) + + special_token_id = tokenizer_py.convert_tokens_to_ids(special_token) + encoded_special_token_unsplit = tokenizer_py.encode( + special_token, add_special_tokens=False, split_special_tokens=False + ) + self.assertTrue(special_token_id in encoded_special_token_unsplit) + + encoded_special_token_split = tokenizer_py.encode(special_token, add_special_tokens=False) + self.assertTrue(special_token_id not in encoded_special_token_split) + + py_tokens_output = tokenizer_py.tokenize(special_sentence) + rust_tokens_output = tokenizer_rust.tokenize(special_sentence) + + self.assertTrue(special_token not in py_tokens_output) + self.assertTrue(special_token not in rust_tokens_output) + + py_tokens_output_unsplit = tokenizer_py.tokenize(special_sentence, split_special_tokens=False) + rust_tokens_output_unsplit = tokenizer_rust.tokenize(special_sentence, split_special_tokens=False) + + self.assertTrue(special_token in py_tokens_output_unsplit) + self.assertTrue(special_token in rust_tokens_output_unsplit) + + py_tokens_output = tokenizer_py(special_sentence) + rust_tokens_output = tokenizer_rust(special_sentence) + + self.assertTrue(special_token_id not in py_tokens_output) + self.assertTrue(special_token_id not in rust_tokens_output) + + tmp_dir = tempfile.mkdtemp() + + try: + tokenizer_py.save_pretrained(tmp_dir) + fast_from_saved = self.tokenizer_class.from_pretrained(tmp_dir) + finally: + shutil.rmtree(tmp_dir) + + output_tokens_reloaded_split = fast_from_saved.tokenize(special_sentence) + self.assertTrue(special_token not in output_tokens_reloaded_split) + + output_tokens_reloaded_unsplit = fast_from_saved.tokenize(special_sentence, split_special_tokens=False) + self.assertTrue(special_token in output_tokens_reloaded_unsplit) + + def test_added_tokens_serialization(self): + # Utility to test the added vocab + def _test_added_vocab_and_eos(expected, tokenizer_class, expected_eos, temp_dir): + tokenizer = tokenizer_class.from_pretrained(temp_dir) + self.assertTrue(str(expected_eos) not in tokenizer.additional_special_tokens) + self.assertIn(new_eos, tokenizer.added_tokens_decoder.values()) + self.assertEqual(tokenizer.added_tokens_decoder[tokenizer.eos_token_id], new_eos) + self.assertTrue(all(item in tokenizer.added_tokens_decoder.items() for item in expected.items())) + return tokenizer + + new_eos = AddedToken("[NEW_EOS]", rstrip=False, lstrip=True, normalized=False, special=True) + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + # Load a slow tokenizer from the hub, init with the new token for fast to also include it + tokenizer = self.get_tokenizer(pretrained_name, eos_token=new_eos) + EXPECTED_ADDED_TOKENS_DECODER = tokenizer.added_tokens_decoder + with self.subTest("Hub -> Slow: Test loading a slow tokenizer from the hub)"): + self.assertEqual(tokenizer._special_tokens_map["eos_token"], new_eos) + self.assertIn(new_eos, list(tokenizer.added_tokens_decoder.values())) + + with tempfile.TemporaryDirectory() as tmp_dir_2: + tokenizer.save_pretrained(tmp_dir_2) + with self.subTest( + "Hub -> Slow -> Slow: Test saving this slow tokenizer and reloading it in the fast class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_2 + ) + + if self.rust_tokenizer_class is not None: + with self.subTest( + "Hub -> Slow -> Fast: Test saving this slow tokenizer and reloading it in the fast class" + ): + tokenizer_fast = _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_2 + ) + with tempfile.TemporaryDirectory() as tmp_dir_3: + tokenizer_fast.save_pretrained(tmp_dir_3) + with self.subTest( + "Hub -> Slow -> Fast -> Fast: Test saving this fast tokenizer and reloading it in the fast class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3 + ) + + with self.subTest( + "Hub -> Slow -> Fast -> Slow: Test saving this slow tokenizer and reloading it in the slow class" + ): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_3 + ) + + with self.subTest("Hub -> Fast: Test loading a fast tokenizer from the hub)"): + if self.rust_tokenizer_class is not None: + tokenizer_fast = self.get_rust_tokenizer(pretrained_name, eos_token=new_eos) + self.assertEqual(tokenizer_fast._special_tokens_map["eos_token"], new_eos) + self.assertIn(new_eos, list(tokenizer_fast.added_tokens_decoder.values())) + # We can't test the following because for BC we kept the default rstrip lstrip in slow not fast. Will comment once normalization is alright + with self.subTest("Hub -> Fast == Hub -> Slow: make sure slow and fast tokenizer match"): + # Fast tokenizer may have user_defined_symbols and control_symbols added, unlike slow + self.assertTrue( + all( + item in tokenizer.added_tokens_decoder.items() + for item in EXPECTED_ADDED_TOKENS_DECODER.items() + ) + ) + + EXPECTED_ADDED_TOKENS_DECODER = tokenizer_fast.added_tokens_decoder + with tempfile.TemporaryDirectory() as tmp_dir_4: + tokenizer_fast.save_pretrained(tmp_dir_4) + with self.subTest("Hub -> Fast -> Fast: saving Fast1 locally and loading"): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.rust_tokenizer_class, new_eos, tmp_dir_4 + ) + + with self.subTest("Hub -> Fast -> Slow: saving Fast1 locally and loading"): + _test_added_vocab_and_eos( + EXPECTED_ADDED_TOKENS_DECODER, self.tokenizer_class, new_eos, tmp_dir_4 + ) + + def test_special_token_addition(self): + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + # Create tokenizer and add an additional special token + tokenizer_1 = tokenizer.from_pretrained(pretrained_name) + tokenizer_1.add_special_tokens({"additional_special_tokens": [""]}) + self.assertEqual(tokenizer_1.additional_special_tokens, [""]) + with tempfile.TemporaryDirectory() as tmp_dir: + tokenizer_1.save_pretrained(tmp_dir) + # Load the above tokenizer and add the same special token a second time + tokenizer_2 = tokenizer.from_pretrained(pretrained_name) + tokenizer_2.add_special_tokens({"additional_special_tokens": [""]}) + self.assertEqual(tokenizer_2.additional_special_tokens, [""]) + + tokenizer_2.add_special_tokens({"additional_special_tokens": ["", ""]}) + self.assertEqual(tokenizer_2.additional_special_tokens, ["", ""]) + tokenizer_2.add_special_tokens({"additional_special_tokens": ["", ""]}) + self.assertEqual(tokenizer_2.additional_special_tokens, ["", ""]) + + tokenizer_2.add_special_tokens( + {"additional_special_tokens": [""]}, + replace_additional_special_tokens=False, + ) + self.assertEqual(tokenizer_2.additional_special_tokens, ["", "", ""]) + + def test_tokenizer_initialization_with_conflicting_key(self): + get_tokenizer_func = self.get_rust_tokenizer if self.test_rust_tokenizer else self.get_tokenizer + with self.assertRaises(AttributeError, msg="conflicts with the method"): + get_tokenizer_func(add_special_tokens=True) + + with self.assertRaises(AttributeError, msg="conflicts with the method"): + get_tokenizer_func(get_vocab=True) + + @parameterized.expand([(True,), (False,)]) + def test_rust_tokenizer_add_prefix_space(self, add_prefix_space): + if not self.test_rust_tokenizer: + self.skipTest(reason="test_rust_tokenizer is set to False") + + for tokenizer, pretrained_name, _ in self.tokenizers_list: + fast_tokenizer = tokenizer.from_pretrained(pretrained_name, add_prefix_space=add_prefix_space) + self.assertEqual(fast_tokenizer.add_prefix_space, add_prefix_space) + # Only the ByteLevel pre-tokenizer has the `add_prefix_space` attribute, we have to ensure that it's set correctly + if hasattr(fast_tokenizer.backend_tokenizer.pre_tokenizer, "add_prefix_space"): + self.assertEqual(fast_tokenizer.backend_tokenizer.pre_tokenizer.add_prefix_space, add_prefix_space) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_tokenization_mistral_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_tokenization_mistral_common.py new file mode 100644 index 0000000000000000000000000000000000000000..aa82df7b8c360c0f40c12d1ca9aadb5df0ba69f1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_tokenization_mistral_common.py @@ -0,0 +1,1725 @@ +# Copyright 2025 Mistral AI 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. + +import tempfile +import unittest + +import numpy as np +import torch +from huggingface_hub import hf_hub_download + +from transformers.models.auto.tokenization_auto import AutoTokenizer +from transformers.testing_utils import require_mistral_common +from transformers.tokenization_mistral_common import MistralCommonTokenizer +from transformers.tokenization_utils_base import BatchEncoding, TruncationStrategy +from transformers.utils import PaddingStrategy, is_mistral_common_available + + +if is_mistral_common_available(): + from mistral_common.exceptions import InvalidMessageStructureException + from mistral_common.protocol.instruct.request import ChatCompletionRequest + from mistral_common.tokens.tokenizers.mistral import MistralTokenizer + + +IMG_URL = "https://huggingface.co/datasets/raushan-testing-hf/images_test/resolve/main/picsum_237_200x300.jpg" +IMG_BASE_64 = """/9j/4QDeRXhpZgAASUkqAAgAAAAGABIBAwABAAAAAQAAABoBBQABAAAAVgAAABsBBQABAAAAXgAAACgBAwABAAAAAgAAABMCAwABAAAAAQAAAGmHBAABAAAAZgAAAAAAAABIAAAAAQAAAEgAAAABAAAABwAAkAcABAAAADAyMTABkQcABAAAAAECAwCGkgcAFgAAAMAAAAAAoAcABAAAADAxMDABoAMAAQAAAP//AAACoAQAAQAAAMgAAAADoAQAAQAAACwBAAAAAAAAQVNDSUkAAABQaWNzdW0gSUQ6IDIzN//bAEMACAYGBwYFCAcHBwkJCAoMFA0MCwsMGRITDxQdGh8eHRocHCAkLicgIiwjHBwoNyksMDE0NDQfJzk9ODI8LjM0Mv/bAEMBCQkJDAsMGA0NGDIhHCEyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMjIyMv/CABEIASwAyAMBIgACEQEDEQH/xAAbAAACAwEBAQAAAAAAAAAAAAADBAACBQEGB//EABgBAQEBAQEAAAAAAAAAAAAAAAABAgME/9oADAMBAAIQAxAAAAHRMQ3DqCpzAk9FQU51SWMK6IelhFws0BAdGL9M4iHNAAkwWq3VhAEcgRf5/n9MfRgfPZZ76eDLXt1fHQ9aXxtz37fzUmX0S/nPT4329+S2BagNdDx+8+mycXU3ne3FuctszLlviecnbjOdhXs6c5bhLVgWvIV2cbkfUSfN5jfu/LYlNZtXh9Q3rUtLl0PS9saVjUr5zyTvxkuQDL9KcK0IFfWXq7lUTh6gJzpaluHTM2FSLVNXQ8zeX2k8XMaGWs6YvBWohISAVCY0cs9aJXty6bqkBt24DtoVZX4MBlC/eVJOQLeHpUvSkVeACcJQQ4woaZanVUTo0Xq6Ezy3MJB0lYWnenZSxSEgS0vVXEiB7Z7A1laMFqsKBNDKcGjJIGitwoOAMFROrBwMDBd7UJOQMTnaGcNgQzMC2ti6QulekG2chsbyta6+e0kGEqQZqCNlWPSYLYBMd6HZINGBeuDIE7oo6ItS3BGEHEfTqevUhJrOQNa5jAeUNWwoYGLpWcuXjEzQXF3caWMMj2ecGVawRQoYOO9TaNjPlhk7SYXVhas7A5ah1sG9mqzUmN+XqWnXnDrnqneWDJNigYrcIdcpVgNTTaXEvDpAscHKgwnFB/See9Rz1yEmN+R4O/o5UtaE72oQgbgKMQW43WBUNw1M3WUWldUqYVX844Ow0sYWxNIzemNeX59GwtPLmZHrLSTTVmTRxQJSdLr2hTTzXYZOt1T5h00qRYxwBBl9IHrcaxZqTOvTKPGzUTnTPKZnrPG9cHAqTealr0Gs8pAu16aLGP0dCCF7BsU5rvZ0n6es56amdJrd5Y8kKn0v5P1C2ng1D378kS9GX4OQUdey3G5dM+3eVY4um5qZPp+PWRwObSNwX4zcowKWXIquee8r9M8b0xlcZX6ZFS1YhRFNB2mtz6YWV7PMufPv7G7GPpE7jd1GbLydkSzUpPp+omyRAYwNdSvLCBfvxFW3V521I9PvYnq+PRdm981IGguqTNyigdAICFhQPGNSpRdBkHUPAFTwo38ftzMO46tcJ49Z67ye7x6FvniNIakU5c/g9VSiOxKKtCuQnNHohXSMZNzwzU9m1eMQ+gs6z839F69SXP62LNoDVGZvGimPbXEKA9CEw5rw/8QAKRAAAgIBAwMEAgMBAQAAAAAAAQIAAxEEEiEQEzEFFCJBFTIgIzAzQv/aAAgBAQABBQL+wRQcdoYGBMNLCUPc3G2zgOWFe/PM25NiCLWQWXAGAcnIPy3zeIOShmebGw0dSz44AOcKs7mIw+RqLF/iE4inEZd0VNkOIrAMRunbwe05i1Yhr47MKgQz7+MG3Acy3UIs9/pwv5GjH5KqN6pVj8sgD+poT+RqMX1OpRV6pVZC6vPiIHQTumLc0N8OoIhulmp2B/V8Sz1K130mra1iwaDCy7W3WkknrmZm6bpmA9Eusqml9SVogVgcYHAIMwRNR6jXVL73ueaTSHUFKu0m0y5+f9dJrm05qtW9Hfar+pUVjVepWaiZ6Uad72op7S8gEhoa+4P5Y/wp1FtMe97IeqJuNFlVI37h5AGJu2n/ABFZMNY2YnHUQ9Mw5Kq877rPf27h6iM06hLT0xNvUKTFonZwGsIiNlNuS1LCbdn8agst8eIeqsVMAhM3TGYQAvcxNxZiSEbk1jYM8ixsOdxhHXJE7hIJ4z1MEx02mVjJtdeieXaVjl27riuYAG2beuOuemOuJiEYiylgob5Ole5mTC/bNulNY2tmY5I5Ccuvxm3hl/gD1BgnmADsBIwHcHxncGTwg/as/HAn0U6cEbeYRHXpjp5hgE89K/8AluxGQNLP0Hl8bF+Ko2IrjG7hR8XMzxvmYzTcZkY6/WckCeYpIh8rZFYRavlt32OeFmIQUHcbcH3TGQeJXLfM7bQgjqIJ9Y58Q8zxEMB43/GJ5KlV7Tut1ZRpWeHEqlnmoZt1Fdtsetqi3npyOhMyMffbDz9Tn+r7lRwzFtuk0L6skKYylYnC4yV4lo4X4x7rG0oXKE5PQCHw0MEqHF4BlfNZ61W8adNQk9syWX7So/VeSQIx6KxWM7P1RC5E3w9VP9Vh5q4usGHEEHmnNYfU3CMGtPbgGI7CMf4440yFnBHQj4mfVXNbH5f+tSP7B56aaz4vyft92KyY3nP8UX46etk6A87o0+q25sGHWPk9PPSuzbN5MEPhRHSY/gg3HsuqVbkPQQ8gdHXevgk9BB48FXxKWzCdoZhlHXDpMAwjpR/1yJ3MkjqpyPsxDw6c9Vh6acYDWb3boHn3DNN/2qRVDLvIhXonk8HPQnIZcdCIIelH6eXSosGrmzEPEH7nyPO2yLXqD0yRMxf2dcHM+s8/eOduZgQwI00+CFpzaAmbLKAj3gxrN3VP3UqYvbNZDA5mZXje6hxsIh8Zn0OJnnMB5oxtX+t7FDSrTe5R9NbSxbMpdK5YxYxYmIKuGqQi/QUmNorRF016mo4baI6wwTwIZtlDGCfVh4O5ugWHzNIm+86eoBEZ22YHtsxKAoVVYepabs2LaDDyCnGwwARxibuMwMRFcNPMKw4EyNzN10aXIwtndjC5iEshrcwrqAbk1NiW07G7pWd2C2fFiwyCmOmJyJvabzN03GBd0q0m8Lo9hBtVXuUT3VaRSyT+yIxjNmNia4EWFN0asr0zNxg5mQOmM/xpODXqiItjsgU797byQYF2n4Gbk3TaZZp0emwGm3uBgeo461iPUYR0Zt0UDOnWolSk4g2o2Vhs+AI21sAGZQFvxGIaepaXkecTiHqBK0zNomo0+B0roLShOxEtGWsGSy4SzM/9fEBWEsckZIHcYx+U1FGxyIQP4LKkXG2hZtSWaVHmn9OXPtq1j1VALp0adhFK10ztKG7ZI7YnELBQLGyXrm+th6o2UD5DHqBmDzpRldmQtQwKgI6c9skLT25yA+XnY2uK1M2xg8w8NeZ2gFtoKhVeaulrNMPJ6BZ4n3o/Cq+3jJ3T54IYQpvOxgvzAZSxKNgXsFNpZ8cbczacgWsTvnbdzcnZ1UbwJiVAGzSjsWsPiNsNgxv4LLMfJWcx13QZUFnwL9GB7zRz3mknvtIJ7/ST8hpIPUNHPyOjnqDUWW5mcqYTxSEZ6LdJVPyGkw+t0YP5DSmDXaWe90kOu0k99pBPfaKe80YnvNKZ7fS49tpRPa6cqdLpQBoNPj2mmz7PS59poVnt9JlvT6rJbobK52rBEoseUaGnZ7XR4Gl0UbQ6Yz2elydPoodNogo0ukM9lpZ7HS5bSaVCNJpCUbFrtwkaIfk37vxAczdEc4sxEwQUUTChc4hHxrHwIw2xYEUx61E2gztqY9STtLs//8QAHREAAgICAwEAAAAAAAAAAAAAAAEREiAwAhAhUP/aAAgBAwEBPwHbYsWZZlmWwklsWmw30lukt86NK1JbERs47UQVI1cUR21oqxYPQsuSxgXHN4LLwlEonCevDwk8xgqVxjr/xAAdEQADAAIDAQEAAAAAAAAAAAAAARECEhAgMCFg/9oACAECAQE/AfXQ0RojRGiHgScrGkSGTu0aCxnGTftqjT8C36N+uXqyizNl5ZM25xfhsh/Sc4vwy7YPo2LIeXddH2jIyMjFwxpkZGRkZGUpSlNx5UpSlKU//8QAMRAAAgECBAQFBAIBBQAAAAAAAAERAiEQEiAxIjIzQQMwUWGBE3GRoSNSQARCYrHw/9oACAEBAAY/Ap2wZkLLRGHoS6i25Jc30X0IsL0LG+FiWiUoWHFo30WNsLlsOY3OxPY6lKL1lqjmO7OQ5S9LORyRU8pwtNF5JUk5TlIjG7gspE9kXpsQQc0eyLvyuGpoyeNZ+pNLlaLwRTSqqjNVh7IhbGakXnQ70mem6LuDiuyKeGnGKURsbkXTPfz3ke5xVs3x9EJUkojDby51Wxl2wtUS2LhHD17F3Bm3IRBHfDi0yRpt5ear4J7+RfysplppxsSz2WxLJt/gN9hvCC2Edicf/XEPzNxx/Y+whsY3qgicI8rufOCLYIbw98L4TjfXfGO2i3cqnlpEsPckmdezZda99DZV7vGKYOGWXUaqV7lS8Cl/S8Pmr9xOVUnezLafY7aLYyZs32ReqPux/wCnfirxP6Ve/oX0z3KPCj+JX+SdqFvovqkqWjJVsP6X8lDW6f8A2ZvFoyJbKo4ozf2XfVKN8YWEaJER6j0ZqW0S6r9jNVfyraqlgmv8BjqeqPUeF9crCdMGyFKtrzeTcsXJ0IW5GXRHl5iNMYImURmXnuBkvZdyzkujbGx3LZvIgvjJY2I9iG4PpqrhTFDmruPhwl4I9T/kXT0SvJq9TNTse7Kkq8niq0dqjiQx1Omauxxb4xW4HdnElV8H8cplrk/TcDpqwsteX1Hl+cPRnFfC+KRMotVY2/JNz2MsH1KOVnacLIsiHpXaMLs3w2xz0o4qDL4apOGtfgvWvwdRfgfEmVUVKmB0sjGdW5c2WO1Rbw5+4o8H8HF4HiJ/YfC6fgcOSZLtYbmb/a9V2ba7saKbbk+hxbFxNsbNixsVJ/sdL8jsTbHlSLshoii0exfFU1JscSREmxys2M9Pk3M9KtjJmaOSTlRLn4O+FyOwspvcu0Q0ba7iinMzhTOFQz+Sr4IkWVZjla+SZcYbk5rfciXJfMb2LJ/IlB3PDa9dewuA5TYZfYvmJEosX2LykK432OZfJepDWYVaJoT9yq199eSll3hylyRXZYuScpKgvU19jmZMlpOJM4Vc4mV0++lJ7FKpd2zc3LF2RmZmk50Xf7OFYdZM6lJ1UT9ZE/W/R1WdVnW/R9Twq5nfTx15V6lP86fuzron6tJznUR1EdQ5zqHVOsdGmS/hI6FJ0KTpUkPwaTpUnF4SOkh5eBlmqvsXof4LUn8t39y/go6aJ+ijpSdKlHS/Z03+Tl/ZDo/ZtjsjftgjbBSMasbCWVD4UcqNljYnuKxsKUKw7En/xAAmEAEAAgICAwEBAAIDAQEAAAABABEhMUFREGFxgZEgobHB8eHw/9oACAEBAAE/IV4EPV8wznMb4WQbE64n5DMWqj43c2zCCVLvdkVEL6lAtChMPJ3DMLLxMhGXGql7sMI6rUXJoi8J6NzLDPOUBfacMYWkM6IVXZqZjz1iFShUhaKq4Tw7lCmKs19hFKY8Nsd3XyblX+SzeBK95Q7LQ8Sl3WcCmXUaasNXP9S2wwptR7S1MD3LNtYgL/dwFu0sqgEAphTJg6UVZOMe/tzYK6YXZYRtC0NYRVQVWQzC0y4vmDeX1AdTYOhxLMR2hejMSwRerPEMoi/fFwjEi3/BGOzESBoggMVQaI+mIbFPcRZAiXfHh+3W6V5lNxAuutxDIYz4xHyP+Ay1I+N+HZAi+rqA1H0zgY4I1+HHPtjbM3ZzLY3BXJwihEXFDf8AhjxR5V4GPnMsNolnSzGfD5n2RDnJlgjXDCrEI5pucH9S/wDDMqan5Klc1hg6GXr1GntlnUVmD6lHMWwtxBqQ1FumDgUDO4eiIm3A2zuU5fI2YjcDOWJMaQy6kTWwnCEu+N3KItoLdYq45v4Jt8HipTPDLa6lKF5gfCWS3NPBdkG8ErVQpw1+Sx8weRDPrmVjMWWJlg4dxd7exMQuI6t3AxKA8bgnCkOTQXMrM2xqY+QYIDbGKnqgD+mCH9kvMxs3L8WmGtHbF6sQitfrW5cizF8S1kC9xG/Xg+MiamlhHuXCnDUMNQFqci6HEQ5lnVjQD3IBvHwYHEVn1HbX/wAgFji+Iqu+vCEMGmbgKOoo1cTy5i8RM1/JzPpUFmq5iCzaUjZgwCoBxDOGy6ZboQwRge9EvSWYX7g+t9xBA59yzTiUD8czI/KflKsikzXf5FvEqsS0SGHyG6ZR3G1KzmMsOLZgU27lg5hVnEhWkI72CSuRiEzL4RHaVYK9XKV2kcg3FQeAlBY41M13HiZjvxcu1PSZ4mFRiqaY7lnuOpsNxQl4qUn/AMIhSwy0OiekspVwls36jsOIIL7g1dy9pkxMbnvnyN1T6qOfJdGZnCpkaxMBsvqZqqplRb9QD0o0Oa5l0hzASezFxCanJh6qDUzzuENGoe9Q1HsIQuiXRf1KhSLXEIX0fBPQQLcxrrXaZBS9wFtglANNblOeVvC5eDucS3sFaDmKB2Z0fs57On/kYpQqPP3ifxS5gISKtXFxLUL7IOfaXjycna9S4fBCsi2RKdqxtbqK9ylNQkBSYjSdzebJUv592bnSEb1PAl3wNGv/AAjZZZ9PvNfrCf8AcaN/JkDxzCjTzFXDGM4cf4Sl1UsFMSyXgjVw7qNcSwHMsa1FW9zdgww6uoz26OfGRo6ru+5gZr+Q9G71APtlzmMuceCyjK1IblBxmC4lwUlL3mGdo8rrM78yqZuUfiKLqO4FCo8S43LIQvj/AJjbsXqOsv8AUo8R9eQl1huOg9EV1KBC28vU5YqF4cSjrwlOqsxYq88RNfiNImLmLW4YkFtufsZaj8IQK0MdxzcwfD4pTtlfBBTacwb4ipITTmbViCjdwgLnmXC08Km5RXgQNbnALhYG4AYnyJrm+5S1pIArnxOIbj7ofcQZp7ZguXOfAzheIOB1LKTZNf4PiGXLxGuoSaAyi7qouZUVxLNIubQZmhf9mgPnMqwH7GanOSmOvvEs09IWXxNF1KgnMCUSw3NMy42/YhZKyxfg3QJhvapc2i+5o07jKPE31L+yUmD+poP9Soci4nVQWA3cfLvwy5Qt/oimOkoqskMhXEKj+iH69Ri5YMy5G2AwNe2YmNq+GFnZjNwK2PqPgEpMVepdtyuRqI5oEDgdtkVUvpMZrGh6nKDuKaIasuYWqXtHbGoDXqWLvmOHMyIDyXqEDedRFzg2StDBLRNX65GVMpiCteJfsll8WvEuLJ+Qmirj3K0cxaxjboIB+1EUc8zI3qV9ENPFR1jubDcqizniIU+SyYhlBgQZVKNOo89Er6PUu2lPKzlIGHJOI8m8zfgxXkfNTGqkE1WGCldD1GAlruOVUincbH3MQ0m+B/sEtklmxnWGWX5uGQlooN6iv6GO2mXeDCghLSFtm5gr91HdV1yRGMrvGpwpyEq3JWJCENw1UXmZ3EvAkFWVIXwP9lLq5e0H7Aq29y5hlS0TKT3ZZtc//AnRj5EW9wMqPqZBkQQMdihOgwMNL24EhsaluqRl+TlUQbvtiGFnl6g67nBSmC2cRA4maCbEXfgSvAXCgYOkqGgX1DQArKkGOQ3cz8ThzNn963NSmoIUa4uGr/vGkvn2zBVq5qCLd8cJZBjmOU/srw+GK0W2cwLr/aGMPw+AsgUyDrmM1IdQvZKAh7IpBYz1OT33HZZ1qP8AztB1DmHk8tszl+oFMn7EiqXvMtycQaMpK/wLsw3oruagDUS19ie5edQq4l+ofYzJtD2ylCr1xLYQ3i0rIqruDVkIKCpmZWFO4YUeo2FAcE2gHuKwdJsdwLHF1DrBAc5j5eYkXx9jVohmmLGCc3HsyRhxvYgKlT7LMP1MwRrH2GZmi0uhYJZV0MTrOEPVWSUWmvcAUm/BHaK8qglC/Y2ro4CdCukKzTBY/wCAhIowvA3zEVY3Bl+wO4V2WhAXV/IFY/lxfok9B6ZimXpMCWvW5cRpGO5qgQU9eptHX9iFvsqUrjpqWo0YZlsIqiSyWPENLlmw7KlZVmYAtfkXseJZffqbc14o11L+yuE+QILfcbQDA7P7C2g1AUWlZnG/E4WxNYB7gBSZZzOoEqdQkNL4vdxGsxMLDAHn/QnK/wBI9b2cQNLX7ieBfRFQaMNQRcHyJ/04VFH9iRVnuahIUwDUD/JT2+glOV2G25k3/KYW2wKU9CS8pU4gxhlggg+WjNGmwhtqzIA+p/50p5SX9ko1SXsGWOcpmVtEnCJ2s6ixy7aazC+KfjMgsfsVbL9lNR9xTi+o4Nqo4Z/vjXwOof8AgQ6Bixvx3DBFsFAFjdy5WGaYfJTWi+xmLn2aKfZKEA2GjAeJfcabT7M0K+xOB+y1lHyDIWrhcVFb+xO6EzpFlUvoDjmCTAxMaU+QAMIlNPyYNr6lyH1qdWjqA2g58wF0iF1v2liSZ4mj4Q2hLd4+JguLM//aAAwDAQACAAMAAAAQ+ukG+yi+LSiaOocQMkf4WCUUq8QgoISefE8oCOCkUod+rsQwmDwAuIGegUSskyGY88g4E85x4gW8cwkwIok4IwQiUgw4oo8SdUGEG5kAY8R021JqMKgc/kkdt+ALhhikhNak8+ggsCkkGlysUsIcChUHyDMDM0Rg44rI1Ikm9Weig8SYMkcU1A3DgZojub6gWWyix774i04zXUY+QVn0rMOd7+Sa+Q8YddIZqd0ox8nlZbBRgh9s5sx//8QAHxEBAAICAwEBAQEAAAAAAAAAAQARECAhMUEwQFFh/9oACAEDAQE/EMGy1BvRHk/xoAf3BHrHHsSdS5RA+/AahFs58hHOxh1FJc7h+N5H9IXCErBHY94Gpdke9KnBkjgLi+QjkXD4Hr6DDhwBFeS18xK0MOfXC6l3Kudy/INBWgsiU4MOCLjRhKOckAqPuckOONukM9NryBETnB3KQSXCwCXFEolEolIm4AlEolEolJRP/8QAHxEAAgICAwEBAQAAAAAAAAAAAAEQESFRIDFBMGFx/9oACAECAQE/EIfzTeigNgvE0jftGfB/YrZKt0hcSGIayPO/BGR0OfwXJD4IdejcNBQxS5Q/o/q/gy6LsUP4MqxKmKHF0ZOLhS4oG7dil8FLO/NyhiGrI/yWdmDAs54Pgit0UKsqi5VL4Y9KhrcFDO4YxCH0JFwotxDLoyC+mJ8G7Y4YoemXiH0d/lUO6px0GHyqptststsTbLoT0NSi2y2y2y2y2y2z/8QAJRABAAICAwACAwEAAwEAAAAAAQARITFBUWFxgRCRobHB0fDh/9oACAEBAAE/EGBFnZLsl7VMg5itE/FalDjJDFpNCMRIJr+iKiF/krJQ5gLbjSxPKeEWkAWWzXUxEHlLldrRDPUXkfIfqOea+JlaTyLYbGIR0jheYY1wsu63qK1BjlM7g54DxCrDPcrEBzbFnFeyCCRj4bITJeE0uMBL9FwqFix1lkK4xFK89J1B/oDEAnVHLKcIsbbw1QD3HKhp+MBGQL4lcm3VRlLCvMFg2cRiSa2iHE/qofsDSKrjlAWayiBPHW5duuDXG8lJzvI6CVm2WfvNZjcXeBFovsniATYbEP40c0BFPE3ETl2QI0hyuZQlKvEKkzgMQOgcRRCvRnjfq3H4WYGebV8xeVdJktHggXYOZb0N4ARJTMqqW9y3cAC4kUY1vEvrcte2WQYuW3MXQ4YSl+AafmGEPNmY/UvBU5QBqOoYdXHHvsQgHtqqolGEVh0HxNOIrByHMEfjSAYrHZQdsSKnMTfxGjKVZPmO/wACWX+BlcxBVR4qZHEOKuyuviYl5kOYTmjRDcYMZbY2anQc1M52csWRhhBbXQRb2VmnmIw1vI8wpXJY0wOoBF3KTJqfMoiU3D+QRqKCxxPGeINNfis6I+7nEOBpQ4i1bOBYkvLrOYnVjZuAAeRQYVZLyNTc4sWYWG5U1oERU2aGMDGJd/gGtQKairhha38/hR4S4AlCcww5orXMRWagHm/khc0TyM8+Igb+kr01Knb+4yMF9LiLgACrhbeQq416KAqJcnRogUQqq2DAjK2DBLuFuAjBxUpnE7OIQgK4gu9+TcRYkqLhlUjViAaBsqAG5U3u+oqBAuuCWW3gdTXCzEFsf5FsGCs39RRbqocEswcFwi64Vr6iSrBcAt6hV8sC2m4caj9Qpwy7bQcPMMkg63DdNclwKg6XpFRuneZWAWchUILbaFgsY1nNkBLXfUVCnCYV3Hop+xMN3tfHUfzy2wEW4NwEDjqCmQjH6ljhjFpTCu2bIqH0RSqWuGAi6t1cpwylobNwWC715EVBwdT5ZYLrBiPFL8CUwS6WxtgTCCnZD/uQa0Lb0dfMvopMi6ioGtfwPxB0ZI4wefMZaN8dQIi27UOIaTrhhlWYLa2yw08QafI8iOUulFm4WMwIgG4ZE7mDkrsIYbh2sKC3ey5jJnCDtuWQoZ1UXrGJk7EquGIqdduY4HpB77qGEhWRLv6h01RKDH/lxQSkcmrlEtEwHEJYlWZb14zCAApJVEut4CMOKCszAW6taij4cwriOo1R22QxIQc25iVSGUGTRcRqB2VpJ+uaou6ADjiu4wm0srmV8KM3CBQCHQcsVS/ZDBoLubedsKTKjmpYIbdK9k30s0rnEcBpim4qxVzfN9TeCmj47i09nSYYHSyAoZ7XioSoRWUBWCpdHEyYNywtAPWAZEYkO9ZYDncohaXJHlW8UtwuQiiUQ0enwlN2lp10SinYR6PYtI9HJz/YQYpuExYyB95WWztwDArQPPMXN8ZH+1GYZ6BMsUEHtyMXGoOLpqYCQUgxiCUpeJuS3L7BcKYlMVF7lngZth6CXbZfmNwQiOoepuLAycNSUFMO2f3QYVvpw6jtjC2XMRtzbEG8n6gNVmQppKBD1axb/wDZeCw3Gry8mO6TaWBLyldDH6iQ7OGv5BTchbWALepYDm8DLZMpWYZ04qsQFAGVoIlWg0WljKrajHtQfh8Psqu4TvgioUVwy4Aj2Gb6tcQJ5lYzcVglJHEtAi+lwi8YeZlUucoaQJYmGyFVVE+FPSBuaVLK5+IvWXBSH7jqX33GnPEurhqZltQf8lymmN1iP3BLKRoKrSzx0RwnZeh4ffIwBMwPEYsxx2L1eH5mLw8uBKv9CIga6pEC0d3UGFBvXn5jThEwssVLYLbN9pyRwxqqUszWYlAANdn3iHJZYVArZXB8Q8RpWcHbAU911FqUYp4lJmIU3CyKtGrNwARAqqTDFIut/MUGF7wcwtInMjtq0vSwcRxX4ATi0XB1Hc0YOxV5ObixIPIGojVocGo8lKcDNYVLBOSmycpAO5YAgxcFVdmIZXkgEbuu5WkIzQA69NktGeEoWzuD8SpyzSkuLU1dd3d1LddhR4CtX1LNqChHI6jAAV0NVzL+QAQMyAcbzCzo3Ew0pRy/MM3I0vXxOauUU4lZS3ljoBI8rkgIAPjczhs2VMZD9kqZD9RGuP5F4IuBVrd1PM3/ALMg8lVl0kFN1sURWACy8srVdgM/L8RKNVmG3RKDQCbOHUYvjaYL9mxHJRj6iPaygK1UVkGFW1EG2pzLr0QNO4g4fZL2CvsTIPdxHJfSXpq9YiM0phLKlKDnyCPKAmTEbCp8SgMtYCO/ctUNGL39TQzd8xqoI0g6zKSRW1yY8/5EY7BLHSwQs3T7hFwQ9iUxYSt8Ssqpoept2Bhw/MpAQDyLUT/iUbTZyxLri8dTCD6I+Y0CHe42LChLwEDYZZjJi5qu4Vt5lr5EZDC2HqWOyN2OVmBzlasJkYvFYn7jLgLKag1lFMgRuI1ghouo5jmLWiFSHWquLwXlxZHZbPER9CCoHHsA1TZSahlxeiA6sOyWsr7Qs1ZTMOtzmKX7ECnc0uyKg0bWUKVbu9xlU/oRyIe9wUlvKwQmVPUYqgxSxqC1TOrota3DEN4gmKKOtcdOD51KaMXEvx1CbI5U4htXCcVMX0xzFtuFjj4DfkSiJi/xSi5jjlo4gxSDghFG0M9obiBVEZAZOa5lc5LKsPcBaKvUzPMQ3QFjSqCGh16bvyKJQ8bxBkEoz2yocRKRgBlzfEFin8zM0hhYRLADuPMQQVt5MbZo5jUQxUQQamW3uGQVi4IxqvMSIXKL3GcuUzr/ALiSrrBqeTGwGhzCWNSUqz9QAPEqGrLmGZLBK6gGggIXnCSWcIRpCjqJLMeYdXthKvzZSDTA0Y+5wmkbvNTWgeTC0r9sVBEK7gDK2HryFeVWPaFkVNALYoOyGmW+bXPMq/ZCeDGYspt/Ybg6rKTQGscStAbhW/mKAANWW/E9I8KzGx2YgtC8tRinkgqNVBsVRDREc2FQfy7IFyIhpQLU39QfawYd1oMdPQsn0EQt5o4j2Bv3FXVAlruUhbJal4IzvqUFe2m75Y7jTpeU5IemQTKi9yuJhCgcrwx45vIYTrLjmNLZ6aPacwOnCNZ/AVRazrrbyv6jAoF1EhlaO6FkWa9GoqG1xhlIy2pZEnFWLUkaICuax+4KRHuOIpgUaLyyiY1v5EQNtJGsrYypi1Kye2F0jVrcNNgA4t3nuWuK7iv4cxgXdhnlYmRdBWYPVSlwspW6CVLGRFxLLMW1sfh9vxGi1LFyi7Hxi3GMiZpk+IGanNsx8WRjbFEBynELMLRfw+I2PQ7rMbQPQZhRmFXHPQ7rcIuhxcC0ImiDdL6YEULVVCArQmdR1BWQcsuqFIuMLfc7UbtdeQCIqNBuAvtGcQTca5mUeZ0D9EJNFbXsl2nOel/UAn+mBxMKnK4xYVZFKeBHmWinBWQtvMbHsy4PjqURn2LkA3QuZYa7upYHuX/iFE3NPMIaZaix1+oLVEAET0Za3k+Y8I+wqFYN3Cg2B9IWyXoQwuGrFVANuZEZjhbgrSZRGlZ0fJCm9Qti5vbxXMrptEhGoXQGYhpl4xCKQ9NcTfkMdrpl/YOlxjOBMg0xl0XCIwvqEZ+qVGx9mbNwp4/cZVUI4oqUt3WBl1qZEEoOXM3s2BiP8QFCkHu0swssyD2kFcGCuoNR4bQSuQL231BoG1PiWWNyL/IdFXyVbhPYlCthckGApqHe7oqLTV7hVmcS5nACGRRuEuWPfUSFR07Jgsw6SJ7Ny4gClx/SOQDWVIkfui4JIYVUwMWeeEvAsOudR9BnQeMFm9YuhOzkIZgMBtRqJm0toJWBzgXSZ6I6rgKOFUMwSildztI8VMoRfw4pj2ALvlNOYBQeoGYMvGeiWW0qFAli9S/AyGyVEA1DF/8AU2ZO2YRCreTA28pd36RXUNguIdkPhg/ktOHDOYOhCQJR6s4JifOjf8iIL2rG/jENq0tCMLlrbmY9brLL3L6TN3f5wDtl3Byqn/ERt4WSo2pp4yoZqs1cvp2YJAIKQeATeO5qHHupw+JWpkouTP8A0swxPdlpVCiNqVtEt2Gwy/cc4XVKgJlRKH/ZR3LkFSwLXarr+xggxBsYroFgCmPZZmTcYqVtr8LauI6OahoSlin8mFQKTiYkRdLiW5npQEfE5A4iIFi0/wCYsQHSoEjzkekZ3DWblmDrm9n0w3acXslOkWxXPxEYOivA7lhdsFWivAitj2DZgXe/hFAxa24Cujkw+ooBVGx9QMtSsJCwdyzW5Yyxqucrdpea6m4MR+UCJjJV0RPABWJuq5o6+YARdnSJuV4plAQUyDUTDA0by/GBzgf9QcbN2jBOGFWFG6poXDQlqgVM0CAqa6l72BORddQHGPgKzCVNLLEe79QDEUbC0qv1DQ26+8w2Cq6hoIB8Sw5IJquNjHdFWMrgoKLp8QiyImk3CtvEBEVH44oNLCwxGLYM4CmXBOhpQqLxU0YDBRCg4iOx+my1CQ18KjAqeHFzeaq1mHToWwfY3AeCaBXGpMvNM5tvaZgmNgKcQYYpMXKKzqFsCOYQMhFK8bj1uhamb0KbErUp7Q9MXPqArEugatjDHekrOH4S0TF+w026Ll0mI4GDh9y4dBUxiUscWVDHjJDBBPnbskOGsCQFpWvKmM1sItw0B02HMKDHYoYu6HBQnBKxFglTu9pD8MeqlowXBJUdFpYqHoxpbcq8hra3Din4sl/Uvq5mhVFDEKRYwgrq2llKAu6tkYGpVC7ZdJx2pUYjecpjJEekINKBaabIh9VoSjX7jBRdnRcYsQaRbDKuTm+YkVVsoMR31GPJdHjpEtXrY1HvTs5TKDi8kYWoQVsN3SFhLdso5bGBmLGC14xA2ihq1ZUi2WyXnmbylnE0aViVpqsLuXkKOLhUte4nIbJmX08L3P/Z""" + +AUDIO_NAMESPACE = "hf-internal-testing" +AUDIO_REPO_NAME = "dummy-audio-samples" +AUDIO_FILENAME = "bcn_weather.mp3" +AUDIO_URL = f"https://huggingface.co/datasets/{AUDIO_NAMESPACE}/{AUDIO_REPO_NAME}/resolve/main/{AUDIO_FILENAME}" +AUDIO_BASE_64 = """//uUxAAAAAAAAAAAAAAAAAAAAAAAWGluZwAAAA8AAAHNAAFFIAACAwQGBwkLDBAUGBodIiQnKy8yNjo9QEVIS1BTVlteYGNlZ2ltcHR5fH6AgoSGioyPkpOVl5mbnJ6goqWnqaqsra6wsbK0tbe6wMTIzM/S1tnd3+Ll6Ovt7/Dy8/X3+fr8/f4AAAA8TEFNRTMuMTAwBK8AAAAAAAAAABUgJAJAgQABzAABRSDkC9nPAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA//sUxAADwAABpAAAACAAADSAAAAEgAAAwGTTgARagDIRBTA+AObl+QLlBsR59aWhqsBAE6Mw7jVSLXK7bBhnEsbe23jIMFALQZ1Dg8+ZMLH3tjCRFdG1//+GCgIB/QAh//sUxCWDwAABpAAAACAAAD/AAAAEjdVqUyy5u0DsbzE8huZ6FsLobCoxHUzJ/zK4CY+KHHfLgpD1pc8/d7dxM9k2vtC0VXJ///+QyOgt2VUokSMElCvuEP/aZlYVoAAL//sUxEsDwAAB/gAAACAAAD/AAAAErgO+XRMAYOkZkQiOd8gWJcOlXMqJFIzlaIdlKKrkRnh1GCI7//rpRlVEotoTbTIGhxegrkghCYOszseMNncr5276eknssvTba2Sv//t0xHCAQJwHHKEEADBOgiQsZjBEAMOi2ccDxXcH0sH2qh8PWXOkWVZJkqkMJJo5SbiqqEgSFwkTqCwOgoNqvejtEot2iJoCUqkyk3OuYO4FrKpNmaAANC67BRpsdc++ZXJSTDVF+ZJEpndhBijUXbdvW1Wi3BgDLtceLQnLGHMLCxp118VlToYvOcQyWwzBHKE///////9Nl4pZYAAEHsbWKsk+l7GlIqyWVZ9MXZwkx3MQiOnn76uHiXpGsZhZBOUTB9gDpGEqF9enOdRcXLogpF6eDLvcTPRlRrdA5rPfC5ViVeYuqaAAF8Ug+tisAJHH6AyVTNfMB1crPJggcK1cVk8+709c5RAXYTQkZUBnDAdFQt+TRKqb2gSrJt5N//tExOmARrxXGyekywEEF6Nk9gk4dyKAagnaKEbiday4UkXK8UxBEVRpgAABMvdugmweA8pJNSG1teoWkgScppiTq90YEgA/ZTUtkhLRUJl4KMDptsTokmkpbKOqbbMnMY0CuAUPS6du+upMQU1FMy4xMDCqqqqqqotdGYAAIIshsdiGEZpjnwr4Wer65mwdhl0zALBV0HMyPcUACjWRgL1ASAXs/x6e//sUxPeARYhhGyYkZ4CGiuNg9JgUE5SNY+zU4R4X77ifg11MQU1FMy4xMDBVVVVVVVVVVVVV0upcoAAOCIreWoimeg9NW3PtQWBA0vIk8iYu/vOuoFydCZRiW01CpUST//sUxPYAQ/xDHQYZJ6iACGMgkJnFtDoVtgZf4TS8h07uq8WE1VWAAA6FC1PI3NgDBaALKWAocQnsjA+gyFoHATn6P/////66dkZ7CoqPR9tYBi7YbPHvU8NcZFj/mL1g//sUxPuARAxRHySEbCiZCyOkxgwosWZpBRonFi5L/////5FMQU1FMy4xMDBVVVVVVVVVU2puoAApMlokUbDs5UaLhmxoSJGSoZgs1PRw2+ztAMriAweARCAybMQoZ0gC//sUxP2ARHBLHSM8xGifC+NkwwnlAhDAdikmoxIzOx2/98xMQU1FMy4xMDCqqqqqqqqmOrSQADAmIg/ODMawBx9RAo+RxjUuyaY11vsFMUA+2ueJdVWCYrBokjyDsKdd//sUxP0ARSBPHSewweiHCeMgwaUJKTFYS7NBIIZVz3ufK1VMQU1FMy4xMDBVVVVVVVVfFJqwACBRcgQCAGnNn1SeQJkRcNBIQAZQCyCVmw853o6wopoFAZRNxmTAGIlb//sUxPwARCxNGyGwwIiJCiOkkI6FWhv5l+9gR1W9aOTOwIJMQU1FMy4xMDCqqqqXyapAAApGrTN9FIYg8BLQySi32GpHgeBTowsSQsGl6YnYhEqUJLCoBvESkoiMdQIv//sUxPiAQ8Q9HSUwYWh6B2OglBhNAjHUjIBKCgiGEtEt/1VMQU1FMy4xMDBVVVVVVVVVVYZUFYBMZUuFYQgZUOUDQRr61kapLl/0wc9buKvujPVAmCAuQr6RlgNSU3hh//sUxPYAQ2A5ISMEbmByBqQkkI1VoDCa6RAZh5WSsJ7VjfhMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqiqVJ4AtAw4VkpJoERKmAcTWVpG7pKlSFRgKBQYsoHSJ6vxh//sUxP+ARJA3GySMSQCaCWOkwo1QWa0b4OL2Num6q727MapMQU1FMy4xMDCqqqqqqqqqqqqqqqqq22O68AAGKfUEiQurV+oHVziqGGjR/i3hhQv4mGukKqrHDvWCVw0X//sUxPeAQ6xHHyGIbCh2BSNgdIwNMKisdYoKWt/L0My/bmpMQU1FqqqquUZUdAASl4C6lc3FaHey/Tvvo3ONoKn+rz7FKaqZIEgyTTMrWl2bWUUUUlYKDwgKJXUH7M1r//sUxPgARBQ1HSSYCuhrA6QkkAxF/GRO7fwJgbDlInBOYpdMQU1FMy4xMDCqaKYjjTcQAABhazcZGSe75IgrbKucI4fMmJWjs7NsKgOgqxmiEsEKN3ANCKd3R5Y7P1VE//sUxPgARBA3HSEkYIBshOPkkAzFqBrI0bId3Jihpg7l+dpMQU1FMy4xMDCqqqqqql96MkQAIW3vQj0JP2kCxIaEKpjjL8WwNyEwtsRYlNNBxJ0BZgTopBoETgzGRPhE//sUxPmARChFHSYgZyh0iGOkkIzlDB+fNf0lPHRNjIfv/dXrnPqgACT5KugDxO6/j5Sv8WDjQcbWiD/JU+vZmxt1tJJNBKAIAAEBGi7LaHul25OcfksS8aHe+btUpIC2//sUxPcAQ3wXGwSwwmh4COPkkIzlDIGIdK2EQN//ioH/////4HeBAB//rA9QAY24kUCUmWQIAAEEDp44gXIQtkeTgN82s5a1WqqFKUTOKCDtkOdK///URDxv+r////////sUxPKAQqgfHwAYQOBtA+OkYwxN/+IjBUSFw8cVUv//d+wiKhKHhMScInDoy/+zcIzF0tHNyIsgpgmAMFqFQREV7D7dtOhaapEwguxxaZw3Tc0W9SKlKol0eclDMvDA//sUxPSAQ6QxISSYYKhegeOgMwRFEmPcS8JoNhupB1NZ6bGBnf//1a7oIJrRpHlNGEQSCJylYHxiATMK386nGNaVAikgsXHAMnJrl0jtcsoMcbVUh+OcYFDQktoyZLIo//sUxPwARRBtHSYFLuhuDKOkgI5Vl42Z+dnBIPOp96MgVomhJ0sjQNv9pSGSy//9PbT2RmVdFL1yMVmVHMjNvQcGDytSElEJLMaxbrBEm22WWW6A11wEAxSBYjKqttag//sUxPqARHhlI6MEcOBzBWQwkIzVYhfctCW3JJllSkggxxaeXbXQEYO8p7iYJBQkAHRv0c8xtnyf/31EEHkBHWjEmlDeZUKsCTw6JIiWAka3mBtbFda7NLZoRbpQFgZk//sUxPiAQ7BDHyYESqB6hWQwkxiVEzCuSJ+ZJSJB8nhPk0vEo+PEE4+d2LWtWKiW6iYX/rqXmnsf/7olChlza8mrwwHPxZdblotlLXm20zt2sre/cycyykCBUFiiEaFL//sUxP+AA5AnITSRACjlCGSzHjAAkcGAojRrqtBBToqyzDyvlY0xL5GyWce8iplqecRgiSwrSWkTZUr///rQmAFjFoH6f//Stbhk4qAIEQXJYfjcl+hmpm57n+TB/KDr//tUxPoACfVHI5jCgAGNmiPrktAAjh9aNup2ffr3K6bT0EGzlrbuD+eL2zf/tmw42YT4GN5GgUnEpUAA6AAVI7QSzMYn9jcJiIoRTkkJnv4tmV1yqGDuQZ9oeVOQj8CX////tSoOsSqtKqFVmWgAIZhFLcWMMpCr64ZEiqZznpozeJaZxRLvyeGT6UYBR8kqFJJWVwAfb2CjkJrPC42LVtgWZhl1Vms4WhBvkARqTEFNRaqqopl6pAAMCgLqoOIA//tUxPYACdETJ6YYRcFDGWU0wwj4F3ZSmjHi0gt/ZkYxZQyDDpMOI77nFsyI0y1y+6ueLAGVrkZxsfJx1IoTUDxdKdu+jmESii6QtlZMQU1FMy4xMDCqEbjgTVkAASfVFefyTMpSyRX6ReZGIqKHAYq6TszSDy4oH/UZSzzi1AcgCkIsRgrjW3odQv5qXhrEBBxQyQRLbdVMQU1uNCOSfgAEzA/NoTRBas7CkzZs9dGphIePtHMkd3VohAccmG70//s0xPuACUzFK6SYScj8jyOkkJmAu2Gi426ggH8laY1FJqxHGGyQ2BilIKe0rzvaudYsTd2t2qFMQU1FMy4xMDBVVVUNRJtt0AAGeBtbapKAd9OePoPLy5xLUUKGHBtnUmWXLBq2p3nPuwKEJcBYALb2RSnoFBol7A4KkFotIxFX4TVMQU1FMy4xMDBVIkFa//s0xPQABuT5HSWAXIjRDqQwkaZcgAA6ghxeIBE0VXf0aHJmQqpEuDpwPhqUW3//////+mlUU6gTB1J74QS1Z5nKMjfHQWOUH2HT4nGhwJW//oVMQU1FMy4xMDBVVVVVVVVVVVVVpkKsoAAYQOY7MDbi3gJHfuirkFe6WNziaEDaqqCoCQbAtFAVOtIaFoPG//sUxPuARMh1HSUlACB0CmOgYZUcBdnRK//RjVwYhhVdTJRMQU1FMy4xMDBVVVVVVVVVVVVwtBJNtAAFjwFCrqeEBW3VZdRsiT3ZBN4IpuWO2vdQ7TVAKQqRToDxHdqp//sUxPwARDxRHyMUYKiHimNgxAksRyMuorwqaH0oCJ6evgpMQU1FMy4xMLcVW4BYZABNRoQhZPGMzFlU7FgAWEjOiNO+TePWBuIYqDLk1TAWRUAReQ2ftCu6wolCsGAz//sUxPqARJRNIYA8oWBuByPkZgideEYWDYdcMLhQXx3//2VtxNoNtAAGjRqBcoQAbfoSUmWbM4Uh8NMrk2o9nL0n6bkhbbiabU/vCKNGuhLBObxYSnhEmNPu4jO9Vr2G//sUxP4ARLRPI4SZByiIh2Qw8bDVQx0fDdttcqzkmoqQenP5Ak4nQ5lUw+u59uNnK8fsXcaGjGmrDzSSbf///fucq2t3//6Bow3P2btp5rBOBKJP/X/jvPgPATDg6A8D//sUxPmARFhNIYYYbqhvB6Qkkwwl4COTzsvJIIJUO41Nid////5uSz7O2MYffYHh5OD0amp2HXbjb//8H3//9SpuJNIkhIkmv9UGkE9VDh+IIT1Kv2l2YDdLW+r0rbNy//sUxPqAREg7GySMx0B5B6OkkYho/UpG1+b1/n83Zvm3lhbXNab9mlSQYCOdrzw+HBCHF9Ub8WQJHpZpP3vOzb3IHa5kv87B87Pd05vd/0tWHL/RUuiYO4Vjfp1nQlUc//sUxPYAQ1A7HyMkYCB2CKOkkw1Ni0ExVOVqyqVMk/iScEs/IuU6mzWZmZns7bTMznzJsTlpEVNA0BP//2//4qGBX7VOS21UpsNmNIBw1wdBOGzGBjQMgSjTo5fnnnvC//sUxPaAw8Q3IYSxACBpCaPglAxV/X4JjQoRFzgKJCaOMYqiQI11Gi7sQiMZxZPtVUVBRwHD4MYjL+r1mfoZHdU5iJ0VldGPZbdz9j6toqKgiYc6sPFSEQoidonCDxQG//sUxPuAQ6gZHQSlICiViGNkwYmIZK5d4fDDaa4EWWeJl3+9VQYjZa81pBiRCFh76Ncyw5brb1Ip6R5xOPzdqpUlOfdzlXPG5Vq0l2PrkLQNpDcbvsfp6Mx54XGRKCgi//tUxP+AA/gbIZSQACpNr2RzHrAAD9v8jXI6pQplKjX+sjWVPUvWxVrZfp50OpEI4kCvfi5SWlgBJ4ZnZ3y4DQIdEEUEFJN2EQLBw3BbgRCpctW7ipoOtQW2JFhwpaYc4u6xVHBkQ9hFnJcbifQtVzYYNbg5/+g1wQPMLP/sINRG8P1RjvndXkD53T+m06izi6lat63fY8pYuYxzVStSDaYDNQAYeIZ2YjkJEACEOTTJArmViZIYiMsnNvpDGOE3//t0xPsAEvFnIZj2AAHBJyT3tlAAc3xIxJYlUTdZ1OtPZa0zgwRAKATYLyFxUFUPl1AyRW6dNP01mMxJF0mV91KNDy1M3abGBMNDQuGBoXC4SZTKZIucVZkdlpprYxl4vlAmNN00XU9M+ghQQUgipB9996zrpQEFajNzSESQMbKxSqBAGADTYARA5sQYTFAkLiQAkjbATfLxoL1jzXd/h3PO9Uv8o954RakfaOtyU2nF+A2HYPaanrO8q3UJiSbjy+HE04hnjEqtXk9M8fd+5uNy+zPPrD2cNU9Xe/7jZceUXPu28pZn/6ne1se5c/Gt+Hc8P7r5nWudytU2e/x1uqOGhhIdIhCCA2FRWd7znrYcMDr93Ny8I1Y3G4goCW8W//tUxPyADMEnNewcWKmpp6Y9l5V9KAQGho7IjU7uEtk9et/epEkPwMEtBh2oPt26QjglH6J48HNCTz1XdU59S6kHGpsqc4Ztc9j75t+kch76/2yo2GubExbbdHxM1PDmfcuLD4rLR6IuZeQ9Dx0mBlmIuS+8yLO3O2pIzvtwbIBiqEqmRYoFAh5BdN330w/86axhWjtsGRQtn3dt7piULJE9CpUBYQe+q2/v1IKdh7mjotx6JLsMGBcXMc+45caR//uExOmAD8E/M/WGgCpsICe/N4JAFVWiK4s5zuf+uVhQdT/9JySABLMb93VLBGPm1RAq3s7YVCFtuDY8JP58C5blq0i1BQkGstbeyIsN1VupCzTvjLFw4QLkLTkHOIq0W7fXr//cGGihsrwjoxvMVdsPYwu9JihsU9y5ECtU58Vt9TrPEOeKDpbuI+pjUu0Glpz3HaWUg5ZYPQlPFKcAUa/vybQjyW3+cXCXiTgVSzCqn7UeYg3CTtZlN2NyWVnCQaEEGQgUPl9qvu/mbTTcm0TVH/v6UzWs8SySBkEAeB0HK+laj5lQ+Owgi0hFyeO9OzdM+flyrzc5DjfdBxk///y9NO01XH3MqOuubilmMqY/7fz3Fw5U0FSwFYCrPp1qIgeVuHqFKSAzlrEZFQgAADD4xMDOQRTQDc1UeDHIFCEuN+KQqEgZUbopEkBXpTJU//tkxPqADdjzR/2FgCGaJ2k9hAo4BKomAoDG6BliQkQFi5Fp4XMAMsA54UARmJ6AwAsMUmw+RZJFAyEAsFIYHIAHFBUDtJIBgWLMYuiugSEislIyF8TwigNmRRUECuSYIgg450aQDwIvgGAQ/l5yyI6EfHTEiqiPK4y5SLw5CzUY0dRGmJPEOPlwxSmLi2HyLkwT5wgh8voDnF4yl9MiIzhBTpVQMV455BxQYyci5tQw/yIekMmfLyjNutX/WkgYGlCpSFSSzE6amqK6nM/v////7M6kP///+kZLVMQMDzNl1FBmyOiECBXhAypnDccA//tkxP0ADbFDS+wxB2oDqKm+sLAARBVFyLw9UBY0m1qQIyzvQhFfFxp7vBVnjbY+R4+L//+eJqkOODIuJT3nib++G4qbEppSmEpiQowgiZLOqY3jDJS0Dpdd79Vlvv/71DmIVQQ27smXSGE1qjaSSqChaHyUglVh4JGvFRtn1mRv9In2egFgq9dPiqC6GHMJiVuHKz0cLHV//z1dcNCFh8KNz//+7PjBtzU3LOWRvKwhaB1P8vdb9g187LwhlIjvGKQ7e1A96ooEBavHlhI6CRb4HVTmL9Q6nYiqqRfTK15L2wYC5UigmIO5LbBw1Uhr//uUxPMAHvoLRfm6AkGFlem/noABuwhFsRYOZiSA/CoWCAIAXBB8avy11F6CoThQQmVf//8ljCMkbf0vxzi+qGomPczf/w9M4SV+c/tuExewf69KMsPUGo7jwTCR3+wqB0i+/tp4a1G5sDqCrALjBGSQcSUK0uQweccEmY3CgDWNVocrOQVxpjxA5VS/2a7FRUe3/A1j6tIanhwqv1C3Ff6uc5lNRlt7/V0pdN9qpQOOQoJg2AAHLJKEQ+TWOuzbEzDITMCxLV5MuiKBaThmgKoC6AFBnCtF2YwVxoFj0S1BITEjpfcRHObV7Q25L12Yz1Va+iyqb+LgtqQ2ikwyjggWpCdgTka9N1mI/ctxiadn5QTtjYIFIIIQvPKcYJbm+pRypq0gwVlzSEcFAgge1iGv+sA6HTgHD4WNRCyUiFFw2K+2Rmbf28ppAC0ndLCLbX6yMcGiRPirL2dxRIw/42gIBhtA9TIZ8l0qr67biKCzCRX//7M7xdQHLSBRcaEm//tkxPuADID7U+wgb+nIqGm9hA49hAKgYxhXhriHeOaX4VCQIGSJ6+uemVmvHdnvYiayECR7nGVmaQDDGOIJxpUoWcxVj/A49AW/qeHf+/NyNAAQJY4X3Cw16IgpJlBYclKOTZmvX2428IZjAVNJpmmCb3FG3/XvPWyTnTvf/r+b/byZLTDRRsjTETY4TaTwlD00ZR4RnNM283dV9DPPzOm8CHxwofKlEEa16GXlgYGAAKhpMwLQSMnEip6bvd6Kl3fd+8p+yAAAiVBSieBkAKQjArFKUrEtHcZ5uIqiuT6ckf3Liu65WmlGlGZaspVy//tkxP2ADJT9V+egUaH8ouk88yYg/yHdfLPDgy55JcwaP7BIQYQrEIGjipIsebRo7dD80rsWMb0J/1+c2ThQ/9GYI0jzBZPW4jp5SsJB0dqS+nY0kH7noaoorrxKfPKIsAgZKnACLCTyRvWd7TaFfH/+zLitAABR4TGZIxpoyokElCwZCF+1JuBSOe8dPi4YQidRKwdVKuP7melvVybamzktjHE2+/Lgzcb3tKGmwPb2TC+toINufrzNecdJMiCXLc9zd+mW8VyY6CDGdQukCMCc4aHzjDw1Jx16nDur6jln/+3LfOAABSSA6qe7DWej//tkxPkADlkPU+w8xoHPI2q9hI34o1CXUc984cgRpUv2Lh1YHISXUaJfmxH89XNnz+4lrGq5CHTHSpCFdJIqKO2NF3ARkEpH8LGtEf6+fvj7jn8o1KdjXLbXfJpiP4plXu9X9jGyX+d3NOANjNqBp96HUD8AX+JhxsIa//+2WzAAAT4bwMMJUJ8BNgH4pIwWcTwsjwbUcq1hDnbW7rrcf71qNDz8/1xS8Wuta1jNMys1HJdK73jY1LGneuCGFTg/ny2ppY+7YpotNJyD1I9APgVBJUsT24gU0wNNcOiRqpqC3KSswMkcg7tNTXzEONY0//t0xPMAETEVU+eZkSHCIeo9hI34ZCaoOrZWxJCr6l0oav7u24zAAANbQRAO0pifhWgikIJYwwb6l2yqtSSqZ7BZ97YfDMik0PPnwb+fUHJmZJIOtElWUpkNmEKyUXKHovYuVzzKnSTEvyp5SNOUFORTd/tp9yUth628/tTPL+LYOm2ligsuk3QvfoIEXObI7VpEb3/szHhAABckDHlmH2ZmqNnwsCIzTpQudnq+byU7Ay30LCsd8B9t1PXnrtmnjUv6yv4TYmh6rCsiBoiMponCkTrTCpMhyFkCQ6TwECEgbEynWNmuDSbyyCmoUyMkIO0CE73BAiOY5dxWKJ/sv+tFis79iFyIAAKviRGpLhTkHCpxvKtSRNIjMdlktsuP//tkxPuADqkRUewkzcIFo2n89BvIEMG3mJIIz2Uj8CTNVarY9ywpJ8/hdJLwRKOXUMiFQ8THjryRk+GSxOCTzeSc6OfcfUb2UlNFvtxp5WPZJMsX2Klat8PYG+k1OmiSp37v3b1sZGKScYhw/JdBq8f/3FtuwAArKFmGyTUXGwMcpT5LE9LnENH7in44NjujhBf3zqst/qeDaTL/aeR78kDEvTYNBqhUU4ChSKFBq24ULUpPl/J+y5dinKdIyvtVX7TfkZxKOVBkHUa1PEqLw070gssaIkFUazVI/ud5fRkIqaKE4G4ATl6DUD7Atm0X//tkxO2ADjUHUeeNMsG9oWn9hI34wSdBoBiLZKzrwRphVz88x2S3tUhKtB1hkV4fvRYJopGTtTD7MAQ0zhG5sz45qDTOs73/y2a5fT0LiLoZsYYuYYwspgiLmA6o4Ej4VMq0MqN39Jsc12vDt5CAFNKhC9fAGoIIBCQ5C104omnKzRqZdtIp1FAEtANDQoT3MHT99s3aHQbYfxnh++wSIv17+o1JDpopYWsGaSGGFmTA57nKctGp0lcYZArAeHPaPWLLkSsBFyQDPMnlv3Gn01oVAhK7tVU0aUi5siCHAHYD6VIteAax4qUnpREBHCl2//t0xOqADxUlTewkz8GpoKn8941wQGuo5Uufz32T/rpfvHEoItu/7sOFGW1SKZEocHYSOQxRfIQjEZPWO5cl//u3nCv0qCGNKsUzUTN3Lv9yRE78+GZ2c//9JpB3BCPKY2g2YQgE/UTZwNIUxfJNmVJSRS2o/LomodhKQSg4zxw2bPEUeNRZDgbhBF2rWdUlBHSIzY8M0jMgJWp+TjXpuQc1sWs1Lp7ecNIcvdc7eKneZz4fnYOFSIvUHHsX6aUkFdujaDroKLgoRGoYm1xpQcYfM6QGStp11BX/mFfRGbfmrYxRIopON3KOLxmNJHGvNEpebq6iive5W1Hx9lIyzmdLX9re/62RsG/Pj/z6v+z/qVWrI7ri5e2OGoee0AMD//tUxP6ADST5T+egbwGokCn9hg3gRRu/FUAJRWy8suaIJVFAboGxrJ0JAHIWwJcfh2RIujiRqMWUZLIzMeKEpMCNAxdFqsxv/2OuUR1S1Zsk1nW7A3QjO1mRkmtpalUU3o6OuKw7QKjrxZYCIh9wTB6gjoVDJsySp2rRBKgXkcYBhiMWC5bAA51gIQtIJiCpc+j/VJZFGbQ4xJdG2sFBITiASm8n5oCcRiedJZnW0hyEJMNpOuVBqLfRipPBVMda//tkxOoADMFbT+eYcMGHI6o9hg1cka6qnFV8kbZJnJnsQFGmIBI1QZGFEPiqmB1UnCo20W1QwlU7uhVr7oQKYt+BuQE2VlUFt2bHLmwQkMI+7N4G8htAQiwuxf/IbBSDAgi50wL75F0yx1DCxLqh1XLI1wHVGpra1zMSGCWCeJkSSU6ErlekhtIevYh+Nw6Xl3Xa38WNQ0YNqSphBY6BRkJ7KJYbqCCodIu3iAsvlDihMHqlLnhcQgtbgGA2ECCBmRGqTEgpvV6phJJ4eblIk5KhNAwYAVSGNXMGwtUQhoyi9c32frIWDpPvYUUyMIiM//tUxPOADLUHSewYccFnnej88YooZKUFIR6mxkTEux9n/zzy85LnSMZRxB/TA0QA1XSiaEcggoQEiSj/OjQAZYcAz0IO9bUoHdxRxz2vOUyAjEuFYauob0hezHRhV78MYliGbrly2Lb/PMpdX2NovTwYeuJCNNI/ak/kkJmdoXT+Ak1PIkEPeKbErOFzOEZyfHfyUDcToMLng621dSAKrZVEQDptOCUHuGKX6AARhxApRMj0FpOJpRSZdqFFKsQy//tkxOkADHUBReykUMG3JKi9hg4YsjDcNPMDO9Km3LnUTDccvtV5nOI29ZyEho8cNIdxCh/XZG2KhVbakriWpOsqXRV2cxTi5BogUrSLVCCzH+9SBuzZCEXroRCB2UjBKShKAhOZzjEwLrZKXhC4RgKV0mp3huz0PiDQAmLercpExijCjAxaAMQj1s4+cn7EUMnzikbuTAyxqefn1EkXO/yZTzcg1Egmsukqef+dJlBOF49KeoRreHnDImIWZuoKrUMJrJgWIDxxGiAkUxCBIh7iU7IWnIqJoMrc91piJ7opLqOwyAzwwS8UkhOnDXNZ//tkxO2ADc07Tewka6m4I6k9hg3sImao2ehj/ld95s4rtj2LC6ITfn1/2dlmRMxmxya3zl7VX//OJ/bUTNqDUSVf/sJvs1hkVlX7RjJgC1jqBCB2kihH0Jys7aI/mVSuYUzFBGnst4WLlrqglNOEcpJVl6evRXYmpbcJb5USvRL1l92jUUdcRQdlULD44JiglPlzGaUjuxqHa7P60Go6LRFksdpKVK6HJGtzsWc5a6CqVWMF3LYTIDyRKicOBUAqm7bBCRZEHlC24NGaJNuDJBAwpWgi9GVvZLrYzVv8XQNTe3ej6m+rnv5f61FRQLCO//tkxOyADJUHUeeksOmopum9gw3tbKXEa/ex3RzvNt3d9/P8RXx38+3Maxc1DMxNW/3AGorhs1OQ73+oIAStRgQAcgAAVggoQPF5yKopubI4qUUpcBvTyLoHBKjjCmVId5UtKGVliLySVxjWmcjKKKYUkIajW2ymYrzPYumeS2FS4hZ7GBUGqjlOGWnHGsmE1Iy7qet/qenjdJeFe4juIneUqXKIkPBUXFzO+eLgo+hEAQ14uhADh5UAADkEAjpWImEKLAxzkBFWUrmdpkrkFq2k6ekyXGXBPnAr3lprJDJ/H7AyjULeIAmxPBD0Yr1J//tkxPKADN0HUewYcamRoGl9hhV0VUSW+IGYbyQ0UtTHHCVRjBzUz/ChqpDiWvtPJPLkNcsjPNfhkrpDQGg4tDUjkqF55DNfkL5S0gE0TkKpAbaxccJUJyOc9gM5MUyMypRvXagSG1C3s2F2lCXbgvwKHFOZgJBwbCwrnv5/wFICDPrIOCYhJmoim8zdBpoIJP+Oqe7K33cU77dPsiHO7/5XRxYCxQMVyzSX2hAERqQgADtIth6EFACABeBoB+CrFqDsajDflxREkZcP6qRCS1K95eFWBHRS4Z8Sr6oXlYdZvQNuVlqmtem4DMYOoYQG//tkxPoADJ0FUewlDWnjI6g9l6F8jhjUjVI1qlbqLaxFHR/KWz9latD9JCL7tVky2EWyBL3KM4009RsGqYkMd9k3VAFm7dBEDxtKiJAEghQsUrMmuypTouTImAusNRHBFgnnLMRcC0jwyywKtJUZjCwqAICk2eXp7792MikhabSpu7jtv+CRzMxpT1H31FVtT8cKlm9z/6z+7aJskfHxxshhjCMIjGd5tmNqYDv8AAHJACD9lgiY1iCkBScBUwuk8QcPhk20LNpjTrIrU/EgqMCqfimap57rmMTp84Q1cyIcjyfHSaqEvlEtOM8a5LJ+//tkxPiADjUfQew8a+mBpOo88Yp1ZM9jTiWVt9D3P+4hhuWP7ff9jd+NrttdsZ/9779eG/7lJUmFa2/M/bfu0KJCwomDqyQVSHT49P3MAJNSxgQHjaUEoHmAxYjINhLlo9PYPCjImFEZrXCKWjxlcRAdKCL6x/CvPWWNhOWbGpfgptB5n8ah4kqS3KLidkK+3KkPCo4GDAOKPpRpWRKpux0XZ+m7KQ9os3J/odlMPEnaq87cGnA0vdhkNn7e3hYCDhCAhQGUPwQ96DXV4pBey2Ifl7hXUkXBUvZa/eZIYwoWcoqCjCz4hP2KjMzyqZbm//tkxP0ADiklQ+eM2umgJOk9hiFcYpEObs4oVd3COxB1dZHfaWc9wdTvR1T3MSLA2u1/I8fLTgjaJWs3ZHfzcHAZroYyEj6WOB3jINiyMyPagKIBMFFRwFjIDCc4NFrnWoaoQQYGFPvpXZW/TO2jrKHd+3g5zN6IJxY7FqHmFbNNTfUziQ1g6NFStVX19t7IhzoV2S9E1MYxHVm+n3KpRRkUYipBBpu4QBI9ulggC3AySwAm20UJYRaS9juShYzEaWdWL8ixgVBGbq5swgbUXGLCjB+cOQXmf/n7qU45WpMZLHp/87HHh5lp9u9SqfV1//tkxP2AD60lO608yeGcpOi9hhU9O6/xat1dxCp29ISeXDRanElpiMXlw4CB/PbQuwZ4oAhwDkPSMkegfqEPB3t6kPZ+uki/RB+hHFWjwYKj0lLRqsJmFx0PEX/zuRSvfA1S4iLqFr/uB5pQDxCha9EuFfzZ+8Pp4jv/CZbEXZihPlz1+CCAn6qxAAZphQAAPQUUIJGEEEQYSGljhwyS/jU8lPsBMaAnlWlWZ5lgH2st8k8FrsjUK7ddctrMqS6EBXGk86PCN7Z8SS80WNepxsTlLZ3Mqv6ftZBQUR3f9zZryciV9ttFwXqeSh9PKxy2//tUxPiADMEpT+eJNemNJKj9hhV01RItR+oTbxdx/23GPdYMIAjcyYkzM4zKchBCeVuBcAAkvYOcBTYAjaOLQySjRB9zOk88RMKDguOK6RSqTuxrdnkOTWSJ/+yGu5UsPVWf9K/nZjhUhbEfDbnnyEhkVZPI0F18o6Y5xfiXyEfKP/jqeX3VUCjduDE0P7Y6FDjWJaIWC3YFSLTRtly6n1S+c6PMnWgygfhpEZjixCgcbUVTTKi1mrYPFx6foi0R//tkxOkAC7T9SeeZDiGNpCk89A49lBlfJjfiXnxsr1irMejMfusOuSwlux/VKH7fJsUmSFllasMYFJY2i/6/KWA4zJkzSP+1sBDQQRKCTBnANoVgo0KBuGIdplqOI0IXSgUSEtM11pWWklJ950BURNXX4QXkmxGFR4ZiEpuvqh9PK4q3o3YLvs4z8/cyhqcTFfDJWYfIYCaJgwEmbY0gKgKUAjFwUcIETCRzWonWy17nQbHKoFCnpE2JHbPV7cahT1sp7GIFfYw3nvaaw3G+Aglrfuw8AydmF70jB1lNr34Znl/9/+OV4LnkyWSx2e9N//tkxPYAD1EhO+y8y+Fyn6k89A3lu7iiUvLqYGztI2AtkauSlXenihQBmO6qWFtTdXth17ErZk38YkIjGuxDpCmUvMuKICtRjwFBWZ3yZz/trLO2WxWhMJQLcS7CY2BPKWU5GUSI+du6/lJMz08uFx1AB62TIXZv1jYckBctjhWIF+BkLglxmpq7ZJEGwsptQ68EicWm+aidSKQdMTNUulngMUzIonb/MfrRUVvLOnD5b9Vq3FPctCiF5iQwDBYtQ1cYCwkSYqE4Z7BOCYgDTSAoIzvW1AxoFNbMICCBhPEBGUcABEgmFqbytpbY5JK4//tUxPeADIEjR+wgbalXlqh89I2ldqv6/pSBLiwxha5rhBVxtRs2JxWY//4xFkUKB1/yk3yn5DvRTHfv/99tV2SJ/PnohJMEnCOF3cW6s4Og3A0FUkxAd9FCAC3RRhX8bKDtBvyzSUxgAPpKxOotmu+4EE1xqMeNCpESxc4QkKZCelHPnrvYt8Wqb4K4lnsq/U3CIddunup2zo4eAxkT7X8rEY4uc5ae2ZEQeZXYu61Uq4iImG1Zj7Wu7YALSiEJ//tUxPAAC3zrO+wkbaloESf9hBod+kQAKiQKg5LBryMIfhVjD2iyCAy+hQGL3HJwfyiaBg4pyeY3ztzkEvpLe2DdafT/w7LIAgiw6EKVz/pE9SMcBMpc0IVxIByzkfLC3WTOGrQsZKuTAB4Liyf0gIDDR/BoRNIyoaYXCj4XqdlbcoatVthIxBGGpouhHkFIDsJepstssod/Qzlkqun1kprIEKaDam39KnVaoqf////f7mV2elv/RDkHIAFCoXVP//tkxOqAC4TZQ+wUdOGeJef9hA4lowACqGAQEACDDwCBOkYtdOVSAXCq2LGVa/kQCQkRJGEB6gSzyTI5/pOUjwQqW+lV+Nbw/m24MvHf4V7//9/0YSLAoh4ACCfuzfRgAJSDU5a8hpMTMDBLfWeBizCGSkbIgMcCuxPOJDuPQfM1zpKYZ1b6bZ5Q0giAVefu6/4f/H/D2UVh//rn////+mgzCKS8yruqqZgAC4AAAAAAtMSYGsKhggOMAk9wASqZQYCHBXQ6YNWuwZoQOJNMAumJuFVF0Byj4E7AQD6OgEgOYRAwIgBFC+koQwtTi2BO//tUxPYADCUjO6wkrWljFea1gwnsBgzL///6fqLlAAQbxQn5QACToKSF7RGKCwIFzxK+y5Ua725kQFns5I4Ap+l43PnUzE3H5S5fI7OTi4PcZZSJMcxNN9OyDoHGRRdNaEwTJId4TkS9Nv//Uy3b//////9S1HjcHk3wob/e8gAA7sh9CQEQQYSPAITEAWcSIkoQpJnbdC3qKa0HIA8OldkJhlGwuU5OQmkcQ8B2P11TZrdzZrlOits5/1CcRP////tUxO6ACjUrNaykTaElECa1ow2s/Ff9WkGSLTX/agAAJcQJySAAtovaFisQIJhJycqHmJCrY1zrsBGQJoSQ8BSSBp2JVhpl3aPXW+i0qzuU4utDsMSM3M6hxo3RjnT/noMAMIf//0///9P//9Vu5U5DQa/Uy1YAAGAFCAByUAA4ZRjGUhijxl8Jhhhmyybpd1LkONGBIJOKaVW+yzdyaj0xvdLLc9+5ioJu1AquXVIDNv5+l31piM/3LgLcG0Sh//tUxPaACQCBN7WVgCFekih/MtAA7//9dBv//+//V/9BjqDvX///u50zegACA/gFyoUAg2g4nuVgRU2e4Ua4iQgKFZKi04iYsWFN7TYFhg5c4kG5AXUhCsDYBeLIWhMAJhNFgqUGYyarecpn+54DIAMBgl//+YRmEKf//nvX3Tqn3nseSHgwb/+VWAAIAZo8wBIIPtZcQAAAAAZTZh6gJoHomksYvB0jpwBvzKgFcXUCMk1xGwn0AhXmZq+6XylZ//tUxPwATBEPMb2mgCEskGZ1th18cBzJfBbE5StF2smsFEVjvxtmLvUAb0SynLf//978P/2/sf/9lIOXA//6bhMBTn/9wkJDvY5P//9//XUAAAMVGIZAMTL5W4AAAAAAmON+ktgaHoXPOyQikul6GfGsKBhRVGMGkbJi0jYVpubOQ6irWWSsoDH5WeCXsOU1nUjXRZG2R0Vjy5tVBrXOfO1//3v///dqG3y/8Llx7P+5GWvK0//3/q+eW7/FwAHA//tUxPuACv0RM6286eF6qWY9ozbMJQB4e2wtkOGXqWSCkBjiqGrUR+kKhURrVlPrDSC+SSg6ez5Q/ilEhyXNTo83KD5uPDi4rVa++kK/2Kmw7B3gRmw0HZ////NzKzhe0nmkuuv//mG2g0/EN7/r2t+v5tjb6uP96BFPDoIBYvhWXm3ETkYRBotReUj7G1YlIkBaSS6dhMtEJFJw2hKRVNyDWwOT+ejUif1p/Sxk1NJk9zjxFGAclG1X6EVDgMIh//tkxPWAC/UNN7WlACG/Eqc/M4AAAT//SdhjMY9//uE0FxwlvnOa238plRFKLkSs9BVRimgLkMUyuBCkdCfwWWXlOSE3kLlBXZTqS7R9Wg/kvbkDToklDqFp7VbRVhEiLZ1P9z3IER7///93lzzHBWLi7JV///2QZOiS8//8XFTwQRX89tbp//GlS9zM0qyqoH0GsWunHHMX/PUCBKh1qFoYNiophY0jEhNGc5M+TNwZIl65sId+WrJobMUh6lzG9sbzB1rcsWtf/m8B5CiJCNAohjYqIU0OSIwQXOknwrkIdtu/Wzyja+ZHhQh1iuEH//tkxPsADaiTO/mcAAHOpSe3srAFOow2pVoYu2eBJAlXa0oYK6s1EsrGpbcsydBPGICJpZC/A0y8siJceMQdbcOHSWuJ7C0DZISpCydofMQMWUHatvGGFp/NfYAFR5nYjOfNB7TVVFMhsgwNOZXygiXy+oIT6baGLjLYIkdNwCElnEs/c9WGvCv+YTO0kiiza9mkgHbezUIY0HC1AtGrtFrW1ej4qnbmNjK0QZcnWOcnQ/zFPNIYWUNOpZeN+rucU9z+e3fwIp/oWoG6I8u5vZIsbPfw64VzblyY7L6XWWNisi6IUgF6RUXbX09KQbyu//tUxPgACx0nSewYryGcJOj9hKGlcSG1Khrj5Z/p5sIa1UuBFVqK/Zn+nogABTRaCTgdwwtjrRpfghwsSFqCEmzRj1MUGxa8T0NX6ixn1NlkOkVzdKTxAgBBI4uYIRLErhISIOJqYmMN2SLBq3sW+7fZ6zoRGknz7bcvtcr3u2HvWXCGgj5KZq/8MTgJUgJwpLym8H6///n83+omK/Lr+zkAAANuSC6QTAFNq68IbGRV2jVHcduXPVLr05K4pHL///uExO2AE5FHRew9keqMKWl9gz3w5maOBWEW/6LuDO09a+9YqBOySP9bUYYsiQrfE9vRWBCZEyLQF1h/qNPqGu3bXOQb2LEUi1UnayST/9j49ldLZoTey6OLUwUBAQJii2ExqtQDPOlKz42lidzcuf2+iAAAyjAHyEg5iLAQwBeJIHcfg4EIPo5HFSWqVICsZxTlttWKftNqz+Ur8FJtNfuxnwXfffbXJl51CVxrEs7hODNhhDvA6VxVBB6IQctPTmVeG4/gkWgWgEhJ1lnxGl3vX9vdONMhC0A55i6qTdG3J2M9r2E+7PQ1+Hb9YxbtxTe2y8/O3/30AEJ6qiRCh5rNFnoSIq0JAU0lqr2yqRM6gTqCAljYrGWDF/343GN2Lts/+Zj9CC/LSTdAvNxi4aMQ5zgTqQFAIExK8I1+flHyyP53zW6xlSyODabMEVgk//t0xOsADrkbVeegz6nwIip9gaZcIC8ROj20knOE1DSI95XDptVYndzZ3q6AAACXgvwwAH0IA7AaxXkIGkK8VZO3p0nzW2ITdAni//eIn+K2zutKZ1Zwrre9yTM7+HaDGklR6NwWSsLpJJx6S1ZfLWFrTcnFk+PxoJ0JsnyFm0S3Ory9+C17FOAu2aM7UX45aj299lmNPMvXcxDQz5ilVahGwCNWJPzpudQwT+YjYeNU8VZa/Lyt2eAA+JlAsOm61BXAWErE0pfT7L4alRP0sij5POyxINoG/jwvrGHlc619Zc3smGV5mloylUasdNLe9bSHpBSFcd5jIaRR3JB2um85T9lYWMSgeTAiF0B4UEDlBYs6KJC8qNEKp3Q8mWJw//tkxPeAENEpUeewz+m3IGp9gw34sMjh4ieNy7JmactDq4hWHytnhWiDAkPHxZRAsjYusex1Oiuak9VyeJwlF9q0gI7xHPk3EVVq6tvNrkAAAFhB0g/CocisBztorw6oBaoFoOqZoq34ni5rBxmje/1jN71zvMTMOLP6W7awsjZLEer3ywPnFpUcU0kMOYTA6ZjtOBRueGZmojHMVGAZj6RwOnak5cd1YTWrytHJe4TTAerK1yU/OSQ+cM8m2LqSUIrVIK5BBmIIMSIm1Q8kgpEPe7Wqc3MsqtxfX9QLIFEsSrj7Z53d2sngAAAIdMOh//uExOqAUZFFTeewfOKFKSk9h6X9ViIAMMJkJOUkivJpsOatS0wuhUUe9d+Jo/pCBhm/Lu/9ZiJFGt7dICYkfPFhyhHhXMSOwCY7DyBe4rcH8V2TjETGLi09A0yRhFRjhZIw2eNuIuZtKa5oJasqNnokEJTZauIyv2izLcmj8VjzXDIeEBmCI6UULcGZFs27YZdpBFXPbWCROQCb9dzTmP+Ohnrd2qt+AAAAn+RKUNaUyBCEYLNwC9FK80otwdVlDsM8ZQGY1w4eP147XPECZj/jfwaVvbEXbmrpdNrCrom48RqPSdClAspEmReyxXSWJG1WoBxgkwpGxcVCgkDaCZZpaUSXmEGgsVp4hEpOZkSA8L2OIjVeLEo2jDIOESyICCwmLCxHIhCwqZThrcvakIsy19vXxNcFtl6rDrt+/czc//5WL0QAAYxhwC4IENg7//uExPEAE1FFSeew3qJlp2k9hLG1xbo5c3qHDJOI4kqtQnDRoYokej/2OHWzLZq7Hluj/Uzn622YYofBZEsygqoPNmkuUSoBIKDDUFmR82M61oq+UFrWNfNSBDSn7MkoCCz44PPNMQEUDHOV5CSa2up1eNzpi27AAAIghATyBGBmlcFseBxqmQwR8CKF3kdLeXGCSB7Ce5+UChrfTT9+Vsmof+u2nFqYsigUxS3JBQ0Fo1y16ahngUStQanW+qxdhBGowMYjLFMGgOSQxM1EmrA4KYXZzGpiuxSf8pXKmF+oM42neoTtgElhIYSTKEwy96sTEE52QBgIAYBm5ayxYYJOt+Su1QFjZt+xDWabc3xSBgEUHEusP1U161QyN/APVaUIfge8FdMzZ/5/EV5XIuQqf64jM6Zp/1jrf9Qj/pmqIhmKhnp86EkoJKPDSURl//t0xPSAE6U7Sew9L+mwoGn88w38LZjSx+SKpMNgbVKdv2ZM5HRiVkghmDROfHF0/rxMHF/DsImRObLE2Zs3ypMCLjLirq8cMMPEMctvKTBkXZb9rvVQt98/dfbDrhZfPVKqdNKqeHR05vneVERh/xkKkq81qtCCKmUuH6pLKgfUaIkPH2dl8BQIIgydoTTWVRFsUAuwn7Ckc4DYhH/7zt6ItDwmGjtOhdunuc6jjS/UaJvd9xxhMOhJkMJKzfq6obSnUFPJzy80IpxZzIdg5v0+HI2GGzftWGff5k61vGUr1WMFmYKIWTpNuhjAYFRiPUA81KNfywq0DQITATBQtIA/kwkKESF+15aYdSJJN6sEyF0w9mdS69A3Is+EaVao//tkxPUADfETR+eYc2l/E2h9hY4Z66kf8H9QVJ4CKMfn51G5NS7wvIc+nr0njbWk3PK0Kw4Iq9XlcX+/pEBY5xdSQ6et4gJEdCJs6ihMksg4LSGII9L+de26FiExxYIMNEn/MOuOeW/m0xb9v/XtGICeZfC4FCmH/Wcy+qGlQIpPfrchFxJnPOrkpnoff88ZPt4TkgkZxYWbugq/+lMDiYJmMqtRyBjYcpei2U/kgCgtRGZp2DZ3IazD0crRN9Z6OHhyBdtATbWPabBzyGkTf/8+sh5kUVGMMwoMnCLNP0KGeLQ69NSlBKxEsHMzThZk//tkxPqADgknRewxDomroGm9go7dh5W5LntaFNHMI4yg6FGG/XBxyoSxLhCmTlJJQvlLhQNLxVIIIhC5yBFc7PoGhL3PbWvQtr8HUb0illN0uY7PTAvim//9txH0iaSsEFClewrkRfuinXfC6nL2ZmJND8yN9+K3Jlk1xiPgNHQX7KLQ/Yv4tWxv8NGD3HJhABMVmDBmqsIZ6txWJyGeSSGar3zcAUY4iMKs2kkb/ZzqlpHNRZm///57CfsYmNYqCk9GkRDNzwhnzmUSH8+IaE1KFHNV3y8ip0toWPYwn9YRtYDUIuKwBabdQVqgUVSf//tUxPoADLEdUewwaemBoym9gw3hLI8B2APehJBC1oo7L3TwREftYdR9dLiu6oGg+MEWKsuoFiY2a1nRnTjDoVFZ9//30Tf3WPKpxbSF+Z1mh6iX3cxtpsZHLfez8vo7Yj1EAA/v+wlGxdhQd4AGPIS3n/65pYy96I4Do43RPDTkgkOyaBIJXCdCAFTBtV5wTFG0sv7aHYlZ884oFhOWJh16bTjDpUSjJh01bf/+k698VJounnz99xf7v+IumnUX//tkxOyADK0RT+wYcOGBI2o9gw4c1TJdEP/l9253DuTkn9aNUoYXRj6OQXI/j+0Id/8AAYGQlRJS86UaQAAAARVM2UAwA1wsxJA06YO+NuZASYoUEmVaKYwJRuhrppcI06NOKqc4qKYAoCowXCZKXFiLB2+EYEQVKu5I14kg1WMjR6MRdKRiXaztSJf+XbaP5FNap2BFsZG6LtQPaxgOSwJLsLq+UvV/Q5jEvlkbilqdtVd3seyznPpLUxX/e8vw/m/z7lnnv/x/Lf477/eVv/f/z8P5n/8/eOWVZlur/oXsK7CMlduSUEBwoaAUblO0//tUxPcADCknT6wYb2GfGSn9hJmdj2CI+rWZtGF3Ut9htd2KUHaCGzD4cUYdclQ8PhsODhZviu+Z1tkupQX0QO2Jdf/r0qCzQqFt6VvJDhV9SBg64oRMjo2mD0PGqtYqxsG6iMgcqqQIkHgCqAHoEgyiiH6LIXBPDtNxjKFFKV2xLfs1po8LmXJLrWVmBaGT/ruYDp+2d9z6IEiD8rMr/P/35EG8NnpEiFEUrz7Mtcd/nrvuY3/8xeJGkFEgDRNR//uExOgADOjdTbWFgCq1JGb3NZAAxYEVLPznMTTQ0Ar+9KogCWBMEcokIM8HiVVQaYDTByRC5wU6U+ZYz6H2Yt1Gh9Izb09pTssz94sgvYaqNSQ7M0jX3fFKfuzKjdgQBJB4IXzpXUEJHNKXDDMp/6hVAjEoZreMvfIvcOcQcxBT+X9DCiiF0QI5m6v/9pCJq8CxihJJFQh8XXaUQDLrtYUsyVHKXlVleBn7k6hqBaaK47VVhETHc4KIzNNg6xh/9biJA89mjkD4iqOYu10c6iQ8WMz7Kyp5VzKVW7f+UhjUNb/1KJCwkBjgUII9NSMEuoNoe/tIghmRMpaqSii8DqCWBCQcLEVnE4CJmcoDrpkw21bFxNmHNL5N17GaRLxOGCx5g5vk+RW3Uk1UYBTVN/sTvQgZRZecvoTnE9OcK3Qk//K9dBGxXKvufC66AYw8//tUxPsAC3ClS72EACGypOj09BoktVb4/6RSZocnZbcmkEqAaKWtkr/sJYEiOrAldIU5nnfVrU7yQMusS0VxnqcnNQgYBctLsJvubk4TKzU1HVSqryN1OoRYxKPAYCGIomCBDmEQJoieYOwvQv5YU/v2nPyJJpJfytKk4cMAAFCUxlBKCKVkWKgRcuvEEELQEADk3omnqrZFi3aGa7IpgIlYAdJED0TYpxNhCAhpcAjrMTS6Mx3RB6KyfEcLHNJa//tkxOwADWUnQaykbaF9JSh9gxYQqFuvtLIN0K50KLjsDGEveXtrTbq/wJTmTvNEMNY7/c0RumamaU2sJ6vFN/tNPG45ZFbKWZrzID38jNb8QvL6cyFPNsp6umuW1Q+u0PHuhRASiqMSwpIUznCqGzqvXjCWZLSZS5sxBEDRCYykUW+I0roioFQTnYFhYAtJU3wft0dZPY1KJiDg7CrWTHm4sBJmOCIaCSD22mddvJ1j/9y/T+28LrAyMi+Fw4TSmgi5kEQ4aeVPz16VCQkJIGsCguNhxqz2RdbV5omNxohftASAF8jJG2Q4JmIBnWGB//tkxPQADNEjQ+wwa6nyque9hI4wlyrEQezFgsruxGlJWli9UyUz2LOW7YhHNrAcY62sFX9TcBkVdZr+M5Dl+oV0mEuEva64obCsl1WtQ6NaMVx80tO5IoIywPhTDSgXixr0NVFHlFjjDZAlhDScUaTVcPu7/k07+YzxHY/Y/vxYAKcEMihngjAX0EIKFywEMQ4lpWImj9TOS5LxAoYkVY/tEEKf4hTMYeW1I/A+MfcGBFTvfxxj1bGXzeY0xl60w7Qjeza2RH2tXVGzkKZK6kGFBWH2QHIYPipBpRw4bAXrdoyLfxM5X31K8l9Rh1mL//t0xO+ADg1XQ+ewa0n3K2i9hA6YmXqNMyiAowt4dYrEmGEHUOUN06TKP4uKqZW1jJzoGtCWIaYXESYqlTD/lmNjSkiZT4zfPcB5fcKzpK5A4pyjmSnwfm9NQTETeX/e80z+H8P/aZWf2KDRnJpDdd+//5zw44UUgJbiabW3LzORDzFrZSBV8KKAhE61Vw7wCkqsrNSrDI9uJTZSms/1pscKkcgjFekYY+7fY54PlGKiXmh8SfbNt+6yWJ6kZXP/VszY1YtgzE1jeamdQ+HJaV82nWcz7T1xx9rqVzMzzUmJEc+z7q0vqU5KJwqMCqw56HdXibU4F1opBGKiAIOeX0Zmv5GZHZH5wBxDcBoHUI5Ko7wnNDdpet3dW9R7L9Vh//tkxP2ADx0tS+wZDynPpem89BY9iuEoIzJUjrK1HzA2qlK6zkofMo4rGMZn+cptDat602SpWVqIZWMpRF0dSrderFWMZpbsJFHk+old806qx3BspR5FoIIZHBSMggaWzLQIBF3NQzSTZKKymrfC0jjgsatBuLLHdqx39KRuYowQyzuzL8nPJRGMEgwRMinCSup3/tz8iQ8vzp5SGpnzymhFfymZ5Fu6lIbhPFcvbA77kGMFWJNnXXqRlgxr084AeGGHDJ6QISgSQAiK8idafA6JVWQQv+j49o/W+7jHiteEocW9UeocrKIiWZkTJ7ME//tkxPSADW1PR+eYb4HOqmi9hA6Ym4m82vG+9/Wf/55IbW2xbUfP4E9/uF8ajwIXxalq+t631B/t6Zxj0ralN0lzSXfx/i1vu2K7p8ZtnG6X1X78mYVXsefdxUKIgMwhSdziyWh/ydVSyMQYPAqMowElRgRBvDBYLmoHDRMiO5mGAtRBxUxqtrJhArdzBgjWKk+BoS6Sz3GAhYMrtKMXiEoy6YaTPgKfRFZmXJARZbN5u7eU8xGH4VJbyodLFd/77PUEVWOz0khyMVLfWyQLgz6NylTNobgUsXuy+/L+LZbE89yNQ9JJ9+aevnOVMM6///tkxPKADS0xPewwqcmKpOd9hg1ha8/nnJq0tjEVi1MzLVPnf5lUncLt6Vz1/CWRjj70mc5TchqIzd6hiPaCdlMdfb7Xd/zuHP//3+t/rVobCVSXd6okF3hgZkz9kZceJCsZHLFqi2EAUaEjMtay2Glk0Ju15EMRtPvNCANh3A7G51yHooHBAgHAQAhAgXSNxRk3YbOvabWata2aq6a2a4vje2HOVNnsnXuYf16t/MsZD31E1X3H+1Zkf88O/bPdZ52dsSqCiIzYqSllUmqpeEQC6Nqh0xpwgKAGo+gQKBiMyOcPpAOqRgZBJMLgkiB4//uExPoAEKknP/WngAtPqml/NaIIJXFJqSqrvbK14WAQFGZuART2O7URksvuu21S7qZ4+rHnnzv8iqR/GOre1S/yVSThlDpftSVRK0qMkZJ/KlTm6iAVeHFWRuRtBgT0B0JSK8QUKYQ8oAqQ0iuH2XgvsLWEJPqLusWSNldxv9qgEgmBQTz1P/Oc1sMmyCJytuS+j0KCrnSTJx2NDas+ZATmSJa0/K/+yej3ahS6hRjRv/q47eaQAR3l1RWC/cZgbA0QcBLQqQnAbL4Z7wc6qL4aCgRBpnUhc/w8ePHraXisf0ePNZZIFbx//iU7/uJB2VmYz99MpbzEmGQn/P5w9xMfh1KcFbtNLfaTSrrtqTnBUdq1jOOOv6lBOHeAJCBv2swCpD6U0vEaQV9WESM3iFLZm7vDS5sgrV5e8WHLNHHH84yW3qx58oBABEB2CGP5//tkxOqADrEjUf2FgCGPJGl9hI1t937uPq/s+pNymcthIeQH8vktCgYIOfc0eoWdJIZ/z/5n6L8hmmaZtOQ5DkqrnARsDqZZxwALxcICCB/I3AuceUTBECwE9INBHdQcdxv1jvk8couRObFQoG58QID8KDgXGlONQkkCcBAODBE/97Ki/m4OQrVPe5je/pt3/dx2z2TT64/qaqIv5upiNn3zLnTtuPbNXV8XLWp1DoUN0mrHOX2qABIzrAABBliRAAAAAAOiMjdUQ5kjPihDTnY3BbDE9OMoFXPHkR/0vzAwkv8KAngE8AUBikABmQAg//tkxOsADDklP+eMVamIo6h88YslcARWOcKSFJieAFhgEhwgMACLG8TosaQpICokDFCRBwWBAkGEwNDRkCMDpCHlYuEyGWBU0zQmTNmMFmKi6mZFZStRo3TZaSkjJfer7XQV+i6uymRZ2SQpmjLUpE8smTMlTVNCs+7l00SRR36/6Ommx/yg4M7v//u//6AEEN5OAAgAgANY0wAAAAADE+ztxTHsjRujjMzEEia+NBjTiV6HWHCTQ1RQ0sWDRg2aIAWCAGgwX7A1yC50CFwLdA0lDsEYAEAcsmgvcH6EeOgLhRCcPjFbk4XRApFRO47j//tkxPaADWUjP+wsdMG1I+h+sLAEU0MgtmYIsaiZmqmSWo0TPK3Osmuxigtr7d9lfZq3dezLtVdS3fqOk+mYHS6V0yQPrRXMSaMTVrVvZSSE0NM/2LoCNWh0ACA3sIAbsNyL1CHoqdJFNVcrsLghxY7Z4NfWN08tfAkj1skjqcJErtZ2lVp7Q9LJq7a3tVrNGDyu+3ejJbSFg/8rvHlV4cEUnwIyQhm6yK+ZOv0p1zgsEhEdxs7f23G4Fk/vze8CyerM9+Z9oKdOT+Tk7/a31JvtXd6GlTcGYGDYkSgQjBTmIBZQsaXQpCWrlRVUiVMN//uExPeAFllVLbm6AAKHJmZ/NTAAUL06lsVq2JpFGgUFcX8jujAKUi8SGPqBTnxhYkIyTDHteecEJd3sRVboYuqo3l9WdivrnS5mI6AlWymX80xiOIeA2pM3xDURSoqmUUWrSGsiQGRA0QKI7j1ErVhUAzOGTvy/Tc4dnICqIT3Z3A1FVQ8+piEQ40lr+ZuyAxcK7J1bRVRIpu9TF3sW5myTDdVe36bec+RizGt3I31N6BR0UIc4ExBpA8IZdM5WiLd1UMSMtuIISEvWhPMOQmMOrcQ7tESUj70TdukgOLu+wtNSBkxDzR4UIV5MEIkwglkYy0/gqA6MmWmLkbVVZI2mkw4yR1OXjrV0J3qxZF66Na7ma7B3T6tJVke/8roHEIzGGdeG790iVVJcm7UyIlVwhNo4K9PDBQ4rfCAKNifCRLfTl6B60lgxYM/wtIm6//tkxOqAD70lPf2GACGKJOh9goocSPj7Bukd7mWzyz5ygVA5AuyEUgvKZSqYZh5UBBDa2lXSwndls/7/5lbp5P0jLfy/aaf/vEeFqOQMGQUFjNM2064ecqbSyNdTZkgLfVAhKdirGCikIYKL3onLCoVL3jtM8EE69+ZyZmqvyWHM6CT81nUT2+bjNS/X8MTCUkkXYjO091NGLbZAzMNmSlarej+z00lmWrlmat3LdTMuHCFkib3pJZDgoNUi6/oAWHiXMhTbTaoesoFDQjCKpL1pfRNe7ns2okIVESzQrRhohhsQHtdPxgMBnV5IFGae//tkxOeADH0tOcwgUYGlpee9hAoxzJoul3AQIWKAqRM04MLjOhyGWfSipD5/cuWd/nC8zckzM9v8rJfVYa/4QHSgIcTIxOBl23dAjZIlEZ05VE2IqEEQnqUpdqCJ7uG9y66yqi/XnVOXDV5I6j14JwKH5gYJ1st237j2ZIi2vg5XTPXwfT1V8W+gmF7////qNuKbpIhl+5+bvqrpOKiYk74ntGmOEdXt5nnEokEMFAdhkQB4tYxz1f3VAgRmhHQytZWkEqEAqcAyZuTLUUBAgcEiUlHF2mq0KkdJ8UgAvASg9FOPo/FJNHWlomRiSRJq//tkxO4ADV0rP+wYbcGUIGd5gwppMDZFppekkXUt36SBcGs1E6TT+t1qfX0kaSkXd3RUyqqlIorTWrUgeV31LUenr//5LEwwQS1iLaADIDLT+k4/+tbZBAAANq2MnGNsQQPNeZNo3JTAcfFgJdsO5F4nBAgNW4KhkAxEYQsjyoJSDAVVA8qGlgWmP+ooXjljO3eV6raqgOBoSZ15Y82k/D9Bx9ePTflEF7pK+U0rILAPdhOXKZ7pP+W3YEAXN2su75vVBz8OfnrXP5Wx5j+WX6rd///////fcu3jv09Sn2f//JIkh6CHlfvuMJKpfIAV//tkxPOADMkjN+wka4m7pOf9hiGtM0wCZY8rBGeMqALRmHtac2CkgcMxYSXNJ46h9EEdanquldQgCZJyuuIdcOUJ7VZqWN3Hkh1Gm2v///5+pr54ibc++f/fEzdbbZVs3sfxzUPdR8V+vsd5cAAxgBB+LNIIFgLQs8LECsgKHKy6VWyEM6TFmGXwI6zXGLuHaXPJhBhEv530ebDTQgDU0t8KZ1ldUm5nf817iCzx+v///37ee7uDx8xdYXBUc8icFW1sDCBws+RBYWOCFP9dAAVCIcppbkhRAAAAAAGLs70NNLRjSTs6YxMYADWQMRAY//t0xPYADbDnQ/WGgCpYnec3NZAAYbo9mCiZoZCLARjAEnwZItwGYuDAMHxEgCiYfGASiC6kBgIIuJyDmlkuhaWbjGieA6cXOGNwuaICKaHNGcJ9A6VEx6UdNWJknzFI0RQIm3JQhCEorL6J5vdSk+7O36ndk0mRbVa/T1v0G6ZqtlP6Ouv3/dRoc9bPgg/W/////+gE2xknp/n2MMyKPsCLwo+qXBEiUA4dJJymvPtA0Wjr6yAMlTZwPjxJIkhuXRjVQSiJQbVGrO7P0IIrbqqsWGwuJEl//mKqamVZM8/2Wm63dyhJ5gJNKILG8o4S+tqFAiNmgnJG7p3GG0C8PSBJE8AIRSk4A7GIHUkSUui+P3JpTKuZNBkiS8Kbv/6j//tUxPmADJEHRb2FgCGIlue2srAEyux/7W+/+ykD9+thdw7jkDRl56aWh7CFAmD9+pUp8LvC3zMj/IrTxbQkuABgYvosAL4ETNQcHDsollIjWSCKw4KQRGORUQQGlDOiVV2J2oHPOySDUxYqEiICi4iDoZIy/S2Y5dc3ZjSRAxMgP9s8N88Qh6fmKstqJCbummnghzIlPD5t4ffkWh/ylNntiEK55RnMyhNSVXjNqIQgvmAkIS3/Dhk0zlIJhwya//t0xOuAFCE7Lbm6AAF2HOg3sHAEwKgc273P8y2A1hRBinNCJp1UJF9hYSsxZYKDQTselyWslT4f3OdgCCJdRyOVY5Mw1OFKpxehE3OZXjmbIyWWixZYT2nHBWWlolkkrltIdAYQiZYqDu4eQQHCwwiX2d9y5+ofGsgHYlyxS1kcL7VP/2/3///+My7eWo1JB9ioKB12XdGM30MvcR33rQvAaBhghfumTbIrXVO0GwU4i4OcvBYQNUtCvCfUI1IhdU/WEcJzK6O9gLRyT0bOPmzXzW9HXMGo/WLkGS+YFPOfG0knGz6vGSFJVXrRjaqTZz1KN/5T1/NZ58uqtZHRjCrS+DxlDGzVdsEbE1/+qWEFK40y/CoQFneFRzhvnDZB//tkxPGADTUfP+eYcaHhKWb9hJlQ+KMIEF4b4MYGCAjH+Mo6wmjAtQfKDBCxFslQZBzjw1ae82lHDXkboKmmdvGy8oy5BkUSP7ZqxzV/qHS/5t5FqpLfNS3IyiNqV1L8VRMaRX+fTLr3yQj33vlqjsaFIIxwQgySgcZWKPCQIOfWM19zkXj0gFQiEdqCZaPOerkWY+EFx4qeNID5FmbHqVRg8y0OkZcS39w1TM2WOview6Vvm3qUWIu/f5qW5LfUv1o9QEwukQ6beP1m/vv8A0V5J4FlJmNWmwtAIAAAAFTIVlkRKAC0ukBzYlLn/BTk//t0xO4AEUUzO+ww0cmxqih88w4xmsJNcgGXQEem5spA7JijBIwKBWUzEvpLUgamggYwhKCXh3NDckDBRLLHmHGVp0FUS1zxxAyKRmQy+dJNq2W6X/X69Oii3/r6looOkjRTbuq3pObG7LGuHf/UCdfp5bLZLLm2AAAAAAWhRLRLJiBlCsRhHQAo9pK9ISWwPebKWAoCCakieGqXlHjZM0HyRQwG8gWEWL5XIkXiLEaZSNLZmMacFaFAdgfAA6AEKFnESZNjE0TKxsMMnzFAgozwY2EelIeW96q/SY8hZVVK3vaymWcRRTWpjtFFa1rXszrqW5fHMIuTYzBbKSi+6P/9Blf8zN541MmM0EzZkP//////////1Jpm6tVAdpmX//tUxPgAC9kdMcekasmVHGX2sIABmGvALAACXAL7YJ8EoBA2yEiL+qkkW5ROatjmWrleyxHum2WNqHdiGOl30SEwR1Q9XavY0a5ah+2qTwYUNzlw/gxoDBM4O1ewMy7Y4SvZG85IUc7UK6kVzW3xs+j2Xe7w/939PaNqLre9N0XGYr+TdY8d/GTzpXP1bGvCguDZBjxWWeaFWNV4wzyVs1uLfaeTfx8b38ZzjExgEBK1qO/9bK8W9vVNmCokxFB1//uExOuAD10jN/mGkAKxQOX3MSABCyghycjUCyRCtOPGC3TKjbHAo9gYruaB8128HfqRV+OVIMQbifzZq21Xgc/UYCFKpltsDJgaTYVCYp1KiVRVynm2OULsnbDE8FAMLA4eSdVWMoeYp5dYIrK4IeL8M+MigW1ZieUyoPKWKgRHTimZ44cLBwBoaUpLFKUdNI3rROBJkDfI3iHSUlWEEMUoQAZszMO444AACBreGXCt9PTIubnPovo/qFG2y5MXfGHwQDGgQicu5qJkydkolKScAEAR1FuyhG2zKFPV5qv2pdgedmM3nScRsQgh8jUCQbNytiQ7arIx4hAfX3dr53qbSbMf/+jHIO+f/6ccHHMeEYglQolUN+094ze+tzoTDmdDEyyDbhUM2OVizU6Ued72Ionhm3LTa9ptr52/7/FPADiZl1NkOGwEE3QABfZn//t0xPUAFG1VN/z3gCFyFee8940wGHFh1HJuy5pNDMQn70WfyVY1ZVGYshgmDHGuw81+Ub6NdDwlLDTiA97Q11cFT018+NDyiWufzZpmcY7ySQNxU37GO0r+eXyehVsdBU73zI1zVuVugmYwhvFpoKqdigZE2y7qmCLftrQEiIAQERQC+3Fwen6vxGWBSADwny1E8aRTGns5/UbtluBlOVb8/zJSaS3X/+4spmiPh+1wo0DMtvUZuyn5/S5S8/KcdByfrnjZd2nBZAA5homCmxy1ABOBuFOB6Frbi2n9AgW8e+W55esPGHAtKAKQHwom1y8WHO1x//x1F7f/nCw+UhJZdzQ62Q2a5mLSFKnuzpFlwYRCPCRKu6NB/yQAAAAA//tkxPqAC/jlOewwaYHsqWh9lhpUAHhiGpDGCCwaHCwwVIKaAdTUPcs0vaj8HxO5Ph7gbAA3mqCA8HkhkS0aLesuplM5UkcMU1ugapnzYmyULneurp11f/+9Btf//upkkk0G///3Y6kzMpRn////nD9CEEh3h0Nq3VCCIyNERLLyoXQtHtAbEak9G4GgOxqBYmYDwPpiiZSNqho+nNt1TCfPNJqARkPwSSPclSDa/5Z//8/LXQdeXmy0Hq5jX3cfXfHz3VTO+p+655ZMsirq5vu6c2POq4wTIay2t4pRAqmJVlfx2RoAQAHiZpnCUIw9//tUxPqADckdN+wgdWFXHSg89I29qqbiMTYm4bZ4VCX8m3yQuFhslPviYtntSXZTgqUyFXBgFAUJspLf8g+6//ut//z/a378ZYKm39CT7CIkCgzAosktUeC4+pxaAAd1OHVHZmJX9oAAAAAAANaHB4wzCgwA8wJESxmSBPiKEFlkQ9IUqAi2ZnQAHVGjintIugWlpEOSBivy/Vaws6EbhiBYDrtvYjCjUReYiqnw1db77YVqC1jjjHvt7rf///vh//tUxO4ACOS3N/T0ACGuLOd/NQAI/6bFq/4RN/b/w8ABCsjCrmzM7LtWAAgCAAAY0wHojUIWRGtFncNGpGiECAkcDBCVGYEMAdGMSkDh5hTMAB+wGVQc0IxD8Q6ggoUx9ilS8sPhUUwxoZh6AfENohowBWx4dAwDQ2RJ0mSktAxKx+mipaKv///9Wt2OFvV0ls/6aSS7E+Vqv+6H9kGoNfNv3/1LAAiVBEaFP8ikCQFKRWkA5lUNkoGFYgrIga19//tkxOoADXEjM/2FgClpFKb+sJAEQRqrJ4lDT/xUjiZSDlAQUgY7R/I5R9LlQ1c6yCKSK6KR9qDI/Uztu/RSXV0Vd6/VpmCaaDJsky0EU9XqRWeKpcKJuerSNCbMXay6C1mRxRM5lA+MpAHyDIpfwIACHUDQGLGKxERGSLhDgZeNwYZXU0lONLis3t8oPRgJIAokMHpxTqK4hCOQEZR52hK7HH3bOrbYz////U5TpZKmpS/0s6qXOJCdr7kRvPMPY0oQnVOLPysAB1OAqhiWmVfygBgEAAAAQAhEgmbwxyaioIGMRjwkx8SEjDwcWB4M//tkxPSADax1M/msAAIWpeZ/NTAAMULSIgBhKtVNBDmnsZx7JDKhFMzIT0rJ95C+EWJAhZPrrJiOBLAMtf+8PD4G0FBpYGjD//4AsE39INBRCv0Yu9X//qAAdSYiMmqGmF+gAQCAAAAAKcQhBQWNaQFYOkPAhFaBQJeQwAZHgEEzYiXTToU8FQIvAMIAMg5wGJJAap+BY+LKBqlAkoK4hUEVwNrBIoA8YAoeDmAbQSGNRFgwEAEADbHX0vLh9P////f/7qUv7/9pm+5H+XPg+CBR3//ECgAJSgYwIHNRZN+AAAgiCADFqB/ZiCBFRkgm//tkxOiADfkVOf2YgCF4pCZ2tKAE4QIxB0oOLjZbAvlTKpJhiASXCFGG0PVhIBR7LuFk5ZKFGZfcDNv9Llt0GbVF8NSKpQV1Z13n/9S9/fc2Tf//+Kw18Mve08or+ykMsU1mphoMjdlU224ABAIAAAGDicQRZiJwmkSKZbThxdbGWhgLDI12PUJ5jEUhgsCwHMoC8ZExiQfAwEmMSsAuSAw8oAwIBoFACXoGqMhc0ITiOwPQ0AsuEegdoKLlHUF4hYsCgAEwoASALJA2UCTYWQN4iKqwDghCoJwWikuqn////+xN/r6/NxMcAgcRK8ke//tkxO8ADXBVPfm9AgHznOf/NUAIQqUJVQAHo2RRAIUzE9a2wAAAAADXJjQADUtjjEV2CSM3AMHADTnC4gQK4YIIMi5UABZVBNwLwkQpKIZAai0AimZsDKoBSRgquWbMeoWZqaKlhkvKgiRnUOKHyIHmv6TIztbuyKCrl+958//+kz//+mtf/2dH+XD/EIiXqSABFE7wBmKIAE9o2gAAAAADe4m2HFZpgBrjQPWBjtrICcjoMOAcLJGCErDLYMQcARxqoKmreW+oS1LClFmCslQKgRKNL81la2ZRtSgNIERhkRkErAgZR3L3gqNnCc84//t0xOgADLhtPfmcAAJJmma/OUAAhe2n3zcd5//9R6C7EZV///7qAibZ28YqAAYzWTVQUQAwutgAAAIAAMbTDFREwgEKG83nfMMcDAAKXhwnmDh+QMaVQaHL3KIAMLXQAvIYECzYBoACQwP6fAxqIvlMQRBukISgWVDLCIhaSOWOQJ3AcDAICgEEAt+Ni7hZkgpRwDAYsIpM2M5RPVm04nqmRbrT//9uv//0t1qT1aKRktFL9fRU6ZoOSNQvl09//Q6z/////6xAVmoYwEg76BAcFWEQtMSNg7ao+vIqZeryRyOtMisuil+SApn88G+I8H1P2NR73CPZxVq+4MDG5P6a9d/cA64TIrJlOK+ZSUL2m9sETUM/FaeBRnG/jsDy//t0xPEADwyRN/msgAHXEGb/NYAAVujPK31ljj7h3q6fwIt3lcTfFd2pSaPia+/9e/9Pams//4+PjcLd53lw2Eb46jI8zKpRNCy7ShZImVqIXggTkzTnfdqAXzjlK5s7deGOP5cNW4HiyYgKZQaiUki1xbF7R0JA2BB0OOhjVJgIQCkYh/q8W8l7O6MMk5lF7L+JuMdqWFOl3BVsKLJeSsf4loS0ARygkRHAULEj72l8RzNeIaO6aVD9HUfPOrIK0qvX0hvCqoaPldR30ox2znY7Sl3+v94b+jQBJf2tIq93XbQtD3+21izEgBGiJaQfwQcxDcSfnUcVzputn7hD9NeBeGW9O6eae/X38VZDtWGKCcGn5oAa4IIOAVwi+uZo//t0xP8AE1krO/m6AEIXJCe/svAECr28ZkCnISEuQwiSTQl05s+ttIcNAQdnFnBoDJ19I+ooQlRR4H8Yw7rHalHKIhAM1HUfTpeboUEQ/hObGDSLPu5XikT0J8hiQDMkutGaQwD6I6MTi/HZcJhxfWoHFiJo8ejb/qVivdt+c+9ep2q5u2lNVXKs7v6HdgAIpXg+lSBrgGomQXZsJFjSsZ61oFzNFPYwpDCn9byK0bMfKv/0oN8+0tJJEqcDMECF5QMrwnElL0ot4wW6wHKHmjCEBSdZgtAltz78F3juDN1od0Qe67/wScFsAoBMgXgwmj6ZJkRmf5JLz++X/08XnqCX9zdV7/P6XnAAAFt/zJFa41hFrFzqKPv3hjK2s08X//uExPQAE2UrQ+w9j8rRK6l8/DNQvR/HF/WVY+WHScEg0j8YJ//LyRMz8e/U2S1MJ7p1aET9umvK1JtOihZPKsLKwiYpHCbO/1+vP1RDPkf6GZ4ugeIBkI99yiiHUUVgQ4ECA9ImUktt0POe/v2ZrEAAGMQgB2XULhFvJWgKljIHSoxHMlHtWJTe6peQJ/6bSZRHzGnxSauve+qKs1TVFJBRyVEgFYiaT6LOoTVd83YtieIbgtNbFveV3z/r9Pf+zv7/9o3NxmfGzZfV///5+tFrON3K2mzFLa+ro5QJF4+07v7+qlpAAITaKClQOMNDEj0Ew0/JmSzEQdGGWYRK7CigU7pP/rWySLPLd/3fkXd9+vgMcCHgzESls+OeqWPLclJKk5Ch4hGn5Et6Xw8qkJ0e0YypfD1EPN6MTXtHkRGo1YZ/LuNVpX/+/7lbAAUp//t0xOmAD3ldTeekccHEpSn9hIo4YUEBhoQCRahKuleNSeGPQ21Ojryy7AGovLDzo58bmxP6taydASnx88FHDmg5TvDkds5zImWZmpKywcjh5EZ/f41KHlOwuZZs2zTNIfmX92qiFXBoMeCQIqK+EnmF4jZ29zwuSCKcCDSa8pEJFWxVKx/01X4r1G41InKX+lEhBoZ+5uF0ju7y5bxR0HbHnM5haaMFbCKVU2UMXpLrnAKMzMKZvKbdy/5lD+/CzaETWSyEjVcYf+pMQSgNhX3+urNN28yXfoAAAgASBuSBLwiajHCVBfkEUDxlTikZob5gpju/k8kCulnOk/5k9lrv/28nXOXS8N+/OG12TbUmplS6MWJjOKQ+3nCNV7Q7//tkxPiADsE7T+w8ycmZoCn9gw34BosQzsM9xDMeCAD6fnKXjxo5kCJ2DZGl3U1DP6AAAA+6YbOh5BMFzXegMOA+rjIvXuIB7C2jz7gPAxSUZd3Rbwqw1hy1/1klnCQQGcRKaO+LGSXDmwSeNajRtyao/cUaaZaKWDir4E1lRjbCZrab3JLIScYIdDFPswJggKFlrJKMoFvVEEh4d3ZuwAAAFtjgi9oYMTJVIczgMaHsTo5DRjCSdxdBhuMgUDJLpyAoZk+/KVXnG4N/wpC0J6MICijkKiplxEPVFkke2AYxNBNAVKpuOyadJaS6xPsY//tUxPeADMUnT+wgcUGDIWk9gw3xqQWWUHURMlFs542Cr6TMPgmjDBBTUwWOWjiJkaNZOc7dU2tvYqHwRA1vtul7c2ANLzEwp/MClHoofFZlF2mMuQQtiZQpEsCgZE0n3Qr5P5bWQ3+kwrKa9tZpS1kwCH1Ok5ImyYufbqBhFho3aFlWD1CB4hosjtHM9G7CKhtSSsfsVe1eGma2tVQx9tu63PY7WVTBNtom9VpmWRYv9NJuUU/Pe7/pjYqbSqoj//tkxOmADGUnQ+eYb+G3IOe9hiEculpqp18AAAIUeFislJ7g3LFXjbRT1eCYy8H0sWnr9i5TucphEXEpoQotunQFye6RsmYIskMx8hu7etZbF5GZrfGD7fi3a4ns7lbmreaiee3BNKgG6yjX87qamOC2p///RAzPCxCL+AAAAKmLhwIbgG4jnyFRQuLA0LcB75yqS+o2T52pExDuUNiyGn1P1CNslL3+rmzSJgKL6ja8140uD2urQHqoquY2HNN6dMvezmNyUNKaTovDGmfnp3UjCWpkoZF+UHmGtvWs8by3YNV1ACaIV4ZvQAAAJ4aq//t0xO6AUK0lNew9JOnrJWb9hiU9V2bMYKDurvYwXSeZojQGO4XdY5plne4s97nfgSBjVexaZt/Zq/LdMzE/AiaUraHTvXme19LvrZxEVmGcSU9tRHNbn3WLg6YJ8qE9corKd0jPXuCQ0mnccrRoqSGmBRYhhnoAH83unAAWBU2FjzIoJjn0YUsc2PFwOBjplGgLPr1eq+qjrNB3GzKR/f8//Oqz9yrCURo1wcEJZXkry66NAQYRROqJCojUDVlSyLJxtSo/xi5nMqlrj3QWSx8YsT7DMYNT2RQ3uq5CzMIaNiDdUe9L//syJHZpmXsBTcobuDRy4wcekehLVHKEUWrMrJEjmWBxlinYZYGMQEAqI4eAsLMQUM7RQbgsM/8b//tkxPOADCzPPewc0Sm4JCa9hJm8N/+y2Msblc1n+TaUVb8+s0y1VpUxE03SJ8dV8XfN3xT1w8LC3EJQ26r+0h8sXsPVP8Mnt/QAAKw7bU4pamwQAAAAFchxkOCBAIoXBVkHM05A6WBBh3RRgQB0YaI57JwOOGtVvju00NlD6vjA1A6DEH7nqa2p592Gy5P8HQdwqjSvfCcl9dry+YCe6hYay5oNJVrLIpLcAX78uispcyCXij79NlTXlF2Q2L/7/P7G8dY5VMsv/PfO/zDLmfL2Xc6T/ua/tT+031ud/m+//2LHO7r57w5v/q0uVruq//tkxPkATcj/M+ywz+HHIKX1liT9Zn6lAAAAQAeXMzETn8lbRRBAAARkwbgwIUzjwQAjEXg6sqoMlzBCSOcuQzy4aNAQ8UBQsnexcj9ma5GBR7dmPN7TKHKEx9hTbxF4uv+87htjZgna0DPt97miPNSs8QEAJ7QLErL+O3KH07ZlrnQUuiBX/nHIgFSuEQ7S0eeH6y3fwz1VrQzn/67r+//c/3uta7KJZnUvb7+WfcPy/v7///6fLVfoOIY8fs/6mQgVSXaST663B6CYsSSvgtF5pK9rrJ31YhNQS6zu2p8QQGxAoGx1+28oD+TjY5Cd//t0xPaADXkhN/WUAAqjJaW3NYAAduUSfZs2f+YujqB9lNk2UHfe357+L5n/44n+Y6jbX9/VGqBuddNObbWQ09/3TpufunTD4epadYqqZAAkAYkQu32oCUxiOt0vhOA0qpA4SsCcTE2DwStCHwFtodJDmFVf9zWgPQJMZmEBOhcjmoOBLasH2mGUyIHAoW6/yGXLermQqs/7W8rh0OxIytRJVd/c6zZ+9hjiRRa8Qo0ACOLTIE+/x0A4gDoEqcMYJSBJJgShXk2LkrixHKkV+O0J1lZjyPsoljE3rdEkVJlq0VIe1mRTMDIwN1LOifDoEnGW6ZopSqatWnfPcpjqv9mWqnOzgkerVqULM+rUN/M5nBgQUTEVRgBHFJogMn0o//t0xPGAFQkPNfmsAAGfpCn/sLAFHwSCYkhdmDpAEa/SYrSWpLCvyuxozPoavuTllRVruXRckSVM1UakzpuigSo5Ccv6Wpd9ZgP4fyiU0PR0+qGWwi4u6Ijf/sYzG85CEUOdX9Zdn3RGccYQQMFw/1MwEbq+29da8mEdFrEw0O8CoQKAtJYjFWGtjhLlJqqwWpGAgNx8842jj8oeCyBYYp6yCNWcuLRpn93WhikY/iuVHX//m9Xqe6GX+/s7mr6Jo5cmQw97qplvtOIpOYPycncozxyjPNoDQEIYcagXYmiTi0WhgIAAxIVjK5cSJMDhsBAcwQAQeADFQvAwxjo8C6QABl0jBoiTGBQAU3vT634fmMurxZnyuzP8VlrVWQCq//tkxO6ADC0lRewkrWmdJOk89oo0quTAXyqofnWsTSNJa6hS78tzxkpapmz1uayuH2AuQruzL45JW5xy2+mWLtvg1p3bPPrZ2NxT+Z8/2m18O1s/zzzuz2eFT9YYa/9f////+WVjHDeFUDGKX/gIVIt//6jyEpnzJDFzDeXk0K29DoCgUICCzNLBaYjBCwgCOZMJMpPiz0aLQEQZyMA4YAAL/atM/8zS9mHp0k5CL8aVmndOJZ90p/QgI4kQijsI/l53NhauWuyy7nJoPLjwQv+rL4lDjlpDyaMz0tjEPRefzfFv3wVxLL8oicjdSc3X//tUxPeADJUnQ+w0U2GYJek+sKAFtMFvxB+LlexSfKLFy93CSxSjik9ZpIvUvQz3l63M1899w7/5/q9GZFUn7OExP5cjUs1OcqcoFO9X72S1yLa9id6ugAADGSkp0knRR/WDT1VqWGT5UzXTB0B341hPPfduj7jf5zNTckeBD/9tQrVrb0rZcyMLVmA5xnGR/PZWC8RZfjSbV28XlxRXoxB0jRIkj7G4FHKbN/7Xzueu8as8Y1ZV/nF4lcU1SHI8//uUxOeAFPkBQfnMoALfpam/M4IAwp5/52WNWMp3LWNZ1qsfVKfEPM8C2s2tjOsZ/+t4xXfr7Sw4ka9YnR3Ce798yM77BUtQlGnMQmLCjkkRCZsRDXbFWy0ro0c7JtXR4weUDVGsYDPlD5n+IuTPi7o3WHkjFmWTSsJC6Eweawaim6qNQQO7P///f4+GV6Rd+h0Y2qCCKqZAg4IiqoZqDnm1Mh2tJ/I/z/ZSfNgeQJrZhvvs3o6AAAUjZiKhTArJmhF5phC4u+kDgwJd8shyHsyxQyaaZUTNvjrz1bUvtN5yz00ybLs8xogxNzBsl0Oy0OyQSuWu0yGiyM/fEKwIOGMYRCRcyL5J1ZG/dW5bBa4Xdox85llfPMukoi6NnlDP//7NzEGEmHfr/Lj9ze6cwACpR2giQVo0wg6BCFnSJm+K8yYxdGZguuHyfc00zd7eZ753P7fu1l5ut5bpZp0ZXwUMZgw5aheSZlCyeDA2O3z//h5tKfzL9V3zGInlnTP3//t0xO0AkzFpT/2HgCHAq+o9hA35/pa2OCV4YSsOs0Zoywqu6tz+y924QAAXWUgoTrAhCgSMI5FLdSShqxpVFGpQ/dgCdwQkrJlpS4dae9KUs/+/JFIV6mq3KXZSfGsKB1Zc4nDY0iV091CuFUxxjlVkNln9zbLulv5HRjJXGeQ7W9yS1FkWBdT2WZuIT2xOeq+cvbm9qOAAAE2oHQzEDaswgB0mXgaiDAiHDbL3jbyWXbz33JqljF06j5r4gAZCYRf/PTEcUQe81S37b/2JTRpH1s8RT6ZkxycmZtGdi6o3VRjX9eVzIMkbxbPy8Ozd+U4Rvc9stYkr2tPT86Zf/9/kB8m4zp3qqthot2gKim1RYYmjehm6iLjyN60OTOtf//tkxO2ADyFbTewwb8GXJOp88w4oXJwYQkpSCOmCcpi4gZ5aUs+102XqnlYVtZcz8p4Iw4o2VxDm+cAgkZg8ZlEmZsX///bD/y+/wVBIKZheGq2ZKJM6CJVSwWG/WdqyMjcq9pNWAi4FgxLya5hKJjQULktSZFNz6mcWlj8W0HDCehQrrkYFqVrWP8kOBYdF2nQ+xmd4FBujdGkW/3pkjN9lBp7kU38zyPy/mZkXBLGXYL+bwcvvcgcKNg8Vp5TLrNyPWCk8G5GxQJByE6xRwBhXEtxYNu8of2PqMqkfSMRCb2aMlYrkgvCmS1aoWJts//tkxOuADbElT+wkT8HFqyj9hI444mdm0fEFIJILu2jd1TOMXVjIurr2l3V91VnO93Mr0ndkd7PXOKwMcoZZaCpapqGR6loq68QAAQCyhrahAoNGTZaarcsxXTV25PhdbG/q4t3k2JrNwYwjYxdUuCaPc775elzG9nui87T7Zjjook8mblubUZmu/6ex96P6q/d5Lzg1ypDNZ2akpMOU8lb2a3vQ7iSmDV0TZJlF710wdqpYqq6QBAIKIE9k2ihIIW0mtHyIRdjZakLYdwHs7p+2Qz+JwXQowmi+E/EOcH82/hIcZP6OLJw0TMhKINjx//tkxOmADOkRS+wkbYF0IGi9hA2pSjscdJ/Fi7MvZJRiCBDKUq0qxEKS2NJHdSvVkdjRc24e5q5eoJWWttYhPxpuyq2f1YfpEupxrqm1YSaoiZRJV4tsFOT7Zwx3HTWl3cVUao0p78EHsuM1i3NUMqJv448aIZ+RUwcy6p2kgfwHaVW8yOoxmthFnDsN3yGh4CYNBBVoNG1rWOf7/rgw7uE85D7Zr9JRaahpiW9IJMoKh0IoAFuFwGmlw2jQdAPORtK7Fbjz2X224dU8taVi8qQOtamfudo+F/foRil7dAYdExayGhfacMoxxm7+X3hf//tkxPSADCkhReygUImyHug9lJndfyhe34oKYpBJioM4OKpCWjK+UOJU3a24LeW13le4FEsDg2uS1QoOQ3qnLgP2199XHjCRqc6ZzuRZGiX0L7hdltSvovEwxO1Dcixi+gPGb0c02T/EVw9IJhMdb1y11VdtxI6aJq4j+a7+3qdpiulv6Ue4DTGuVY5QLnB55kl11WFHeSWofWBSShYEOJkDqz6CRdKw1ErG4jVK6jzyBEaRnWu7X+kvonr0CU0ZozRk0mn5b/mmHn233pgxCL3LmS4aHWDo7HRzzIyjpKlpl0odT6k2LX81y1yPO/uQ//tUxPsADlkjPeeVFil7mWf9hA3hthdViKigKSopkvYyEVA8A9C0qJQ1+2CtaXGLGd9mbsNz4HWaCqAVfFnsKNb4k0a1MP9n7Xr/D9JHQxlMn0rcyj2BsYsm07PrWz1McYwidnSiHudnpTZWud1cwIQgoZRTI54Sv20qUQUyFriNYiiWEOBcGHCZCZD0tHWkv5oCgHgNxNi43uwuXs124/AqttyWj/wuJVcc1v+//2gv+B2dnMQJIi5JlrTvFuq8//tkxOeADAUBO+wsbwmcHeh9hiHc+edO+3phnAQ6llO0xs785/JrCKNKFg8PNKaVAWEGe6eONIJhNobNwiGXfaYDlqigdzeM5TMUHk757o4BoX9D/ZqSR2AOtaETKIgiEGuf3///O42iqbEr2rRsWLJzNz3FwT3klSmSq2W3/0mMhudSMIDIzGWQnVVssKcKFMJAKIClYCZha7mPM3U2IfK5zyoFaEdi9DJ0A6502M4kSGHkc7crJGaDK/0yK0W2T30qZsw1Nda/l39F/w0PPnT6JCMvoZXLOPkRkI2sjBy1u9tf7QKK30GCXUZbs+j9//tkxPEADB0jP+wwbUmBJOg9hImtv051bgKIJXVPplM2wOlB1qirk5qYWA1ufULhDFQBqaLjo6wv5HyQuPAGTh1G9lEbJxeHX/5f/aFzzk0jGyBYtP/MSwOhMPSNnMMD7fLPn+czKa3L3M+xfhHK8y8rAUeyNWIFQFqodz2WQAlGgSlKECL6y0YVftwXZfX0ixD14L5PSlRrqH4EUQ2/3+qN49EayYddM3/6JVz3mGLjOUg5u14L8jqgzQ0fLznCvnsQMIRjQXpNtirJKskvPShgiGM0qu7SSAZkSIsDlrsX2qdUTUFcuyzJVs9wND5r//tUxP2AC/EjP+wwaeGYpGe9hYo1JFS6tUlMZ/MTCpqWorJxuT9QVWsUXMgdcSfstuog+hsx0TJ6fdUcVFiivB3IbK3SvplVUANDJ5JrftawEnhKM4oAlVCU+1rOiuKfbC11q+ntsaLwK/5jjSGRAQFmhSdJ6VuZ/8W/ZFhDlFWSR06hdAQt3KiKzSG0ZqOzIKKI3mL4pVmiJCBkYRBDL7qwAQIEG1BhgLohg4wLQtSonMBAEu2TdnviEpkeLCjd//tUxPAAC6y5Qew8ael1o+f9hI10CQ0QzUOYQh/0tj5+y6/3HVjSnpHvlX/oq4KFijZ6PetXsDzhMiNCRUeSCb60AC2LKZeIhIVQCoKxdB5SKtKgkijZDGrGgqp8zNq0v/WZXrC3PnPjiF/t5zN+lvh7klnkJjYDJEKPjzpYUo1JlxZGxLEqCIFNKMLYy2MQ2puFDDeIUl4jGlskBs8262x5yIYQWNKWIHDARcil+soqKuD00YqNVWjHRspXbAAA//tkxOgAC0zZPewsbalHmye9hZWtKlezos4uQvtnTUHzTjkKpnscOjonn5QrcnDCck25ZMuDZAqRNwI9dLxmzX/+f//I0wipoxeetTzaDZ8Z/+/gckLYAAAAAACNL+NCNAUUgCqj+g6MIKXGFLgTGIDnYMuQoVlaBJOhMmBxEVlqYbj21UVkSVYRS16CVT3M3eWfdaEOxSOLXs/z69vX/b1///5//15Zc//xv2VJRITbb6jK2JgAAAAAB+TLTGhjPaAQoGbU+aRxuqKUApBGBHBcAhsHhRDoVkMva41VhrOFrDRIfc5C2dIRyHsJonXo//tExP8ACizVP+wYTyEtFKc88SIM10CnB/0ihp1rW//7Gv739///3P//G7a//+/2f/YCmZIYvMVEQ9Nt7KAEAAAAzMBAFhJyUDBKkKFmIGPHOaHUOyCFnJW1aCkxbABwQIYG8NYD2UHWGfLQxgmpkITBvaRDRDwCbhzgxgBwyOkigcgVb808zakqste6PWxJ//y5IXUgESMHJ4mHmImeVoAAAAAADKPJ//s0xPoASFyDN+w8yODpECX09BXkl+JHoCxqRwXDQZNS5LYTkKgmzLAOkZEL08vs9CApBguKLLSqAYthQDTdV/25mCqL2XxREecaYYqZ5p9//+BOb3/P//3DUW05n////Jnujo/8YkCIxIzWXeYh4m/SUAAAAACAxAKGAg6BDYwGzyXBQbXg4M5QC6SHJiib//tUxPiACBSPMbWEgCF8kiY3M4AAqWBqnEXIe0DYKC9Aj4EDCx0FsYjkhobkoFyjcmhnAbwhkiInYLak+CVDT28kUebd1LQ6mR6iHlf/////+tV4eHRmZmdGZkZxEIAAAAAAx1ADHw9MrGE8ubhabmnYkZWGppQNmtmMIQgbROQ4IDBpREloNPUIThhI0mTAeDdIUiALQJsHkLJRhKLIaWxuO5EcgqCOAxGskhtj6FUAFj/m9l2+dS+/k0ef/+z7//tUxP4ADASFM7mcAAGJkid/MzAA/x+ag/4lAhMVI3iHVmaF1kiBAAAAAStXcIRpjCDPi5gkDDCprghhgpsUjERgK5gCTssMHJGioaiGIQF0GARSw12Ql4yLJw+YmJHDRNggAIagKwGKjU3Qy26t9qjQ25w1Kux/yH/0Ttn9LVI0IkF3h4l3eIm7NsIAgAAAOIAAKHMgSrQ0UpMWFBRw3i4xA0aETQCSlqzpJQg8ZlAqKhdduMAP+0zPOp9mYnMJ//tkxPIADKh5OfmMgAGYEmc/MxAAm/AUSmkPgAWahgz0s/3/3Tc/+XnQBgru+r/6Hav/Oo8ASktPdX/9cAUABpVIBs/AHg+hNQuUNHAPUhZeXI63tglNGRWaPFRHPGw0WzrHlJEREAeLLFhub/8w482pYbf/zWIlm+QZ1A6JDVEUyJ4kHeFDpuFQyEh1R2ACIpmAN2wACXBbdMAGBXmXnTbAQWO11u1XKa18XtZAoSbKpIgJssz/4HCxziokPUYFxj3/8olQ9FMKO/KoOZA4Voh67wtoiUVsFoACT6qdsRWY4yoWhwKwGs21/EhO++t0//tkxPmADmCTL/nIgAGSkOa/NRAAabxmfltNaJqlnP/66Bm1OgVeG1dAAAEaIpNLDHq1qKpovGs2AmTxmFutAUy/dajhBYWhqrBUiBYKhM9wNggRTlDShFHG3AFgwkw0ZMFLWOxISGpbTMmbnI6B6pffyomo4OEjeuppzaUzUFJpE9mFNREMbnYAAgRakLDFjKzQ2vhTZPmTixlWQPa0Ua/HsB+J1nbipDhY8G/J7B2OyNwAlO1QNO0VOcvYIMfwTJxIlinsVVEUQKEB0o8w9LMAWVCYxShQKRJtsAABKkHRROX42GeLdN44SjAmQTUF//tUxPsAC9xtOfmsAAFjFSf/nnAE03DiUDIYMUGob97bTyyjJK8goRHQHQcIE0J2OcfguCEvMQ6wrMhkDAWMnffG148MTCGByNJN1AAEdGoipQ4eaoIyFQIcT9ghAYgw2zr7u1dmXqi11uIZc3zJi1YVxhXDgqVgwrLnjoFlsXPKh3ZNCUdqZ7jDAooAwja2lWVEBACEK4EIEGB6EpFNMcsYjQjYCC6XRysjY3K14MbpUcrvvmbO7X9C3JFaIyO0//s0xPSAR+B/NewZDqDKD2b9gwnlQ8cAnQY4PCMfLEyZt7paQxEMKY7K9A7+5WRpVRSQACRCgbYI0DlD8CoMEqJniTCJpMnklfJT29P27tO3sZksxAMGguo5//////y/7lV/AqhNAJYmYKIOvEFDDxiidrNR2WaqkFghkkvn3a375AxGWjv7FSQGRIZlXa1A//skxPkARjhjK6wAbii3DGS1gZnkAB0QgHHQhSl7wsEHoVRogqYiArCuUXcJD04eNDoJKySwPD8xIKfKkzpqSUXlVxY6EhqzzxByEZAcBiF2AG9a/THWf1kItSFqAA4BwcwBSOHVjl2YIAHAHMEAYaSshKcRhocM//sUxPqARThNJYwkaKilBWT1h4ydHsYwBuFQGTibqOAIYjjeZGGAakEKZFhSYDAlGcJa/cQxlEppM5XcWWSIIop1x1MeCBAZD0v2+7cXcQmQ4OAYM+2iyLOgns5oZgnY//sUxPaAROw5IYwsaGiNiCOg9gzVfAoRb1////6mf9aSKReIBDLD5qbGj9Wf/FacFXACgNAB4UkAyESEKnVVZEDkJwQ6vGJMmWBUWcuMCw4DUlZNJZUwIuv9/OipcGGA//sUxPaARQhDIYw9ASiEBSNhhg0N9eNSXVkjUvWQwQoH0dW9TFSqKggBiRE3////Pc8/rc05TBYJywcEI56tQmMguz6DRqUGVi9hePSwOATEQOW3Nkzg5DJkyb8hWAf9//sUxPcARNQ/FwekyCiJg+Og97BNksANxnrI6SEQxJXP5ynDHacKrShQeFQYMJj/+/oIISxAP///6rdnU41vzjUQmhUx73bduNUtb//pTEqMpQAAUnPtq7fY2wAAAAAI//skxPgARhRVGSekyACeiuPk9BkowYEFmEiBiEUGCJhacZSElmDCSJqZf1gCYw8KBAsGJamSUwXDDAikoKvl3oEl6wMqUpKCV5Ktp11hAAJzlbg2S3oyIGlpBo8jvT0RWd3tdLFf/6xwqN9j+F69Nd/XJS+hzgPn//tUxP0ACoiHK+3grWH0HWW93DXle8o0E2Yvqt5TvK/Mo+4yEDhCmHZMWjQIAAysQHYnYBCKQhwOZtcRuKt0T5LsswePB4kjtUZHYiPDOcajqajx4gd/7TnUqSGx5b+31Qt/TRzUdv5yjYntqH7Pyy0wNiYymZ1kkRAWCLBZIn2q9lSSCoihgpEWZ8qCsNJbdIZdsVUCl6bcmw5x6k8xWz0VaUWGFCxg/v/j06uENFzQfD+UOA+8yR4XkAQZ4CqJ//tkxOmADAjfNa09TWFaG+g2sKAFfKi7UU/SJa3IyABBYjiukGGlBaQAAZWmghocwt21490S51unqtUkdISgRHajOr6+DoFh7X8XwzNZRQtchyIsX/tdEmwzNrNf/8MUeAINa+tAqwu562sAAL4PkECc6gDwEaHgFcQpdHta5xEuxUV9KX7qDEsAACCSEuZMaCDvdvyrdJQ3A0nxYdUFKnbbYzMLqCGwDACdYyGCkeZt4mYWKYMQ9X81ZnWC9YsCECNopuDYSLsQrbPBYWV0Su1y20AAAWRUS1UJ9CgCEgNcRIrUak2wlSCAtX20HQWS//tUxPuAD+CRMbm8AAE3G+f/nnAEznIU3RFGEveZYfB7+/wa26SyACQgzBENlDooWIElnp3vokEZo7MgNiq8RiiIggGLIUREW4cBgSqJhhmAAB0BAJTNn6MCmCYy32GP7hW5uSvJLXvBAWDALlTJ4UCJ9p3/////+q6KBgEAx/Q8w8SzyrIqwAOJQKAgAAAAkshyBLQwAiaghTAc8OzRAgK7abGOSZItk6lmiTKUgzKjHDhBX/y0YgmH79ZAJceg//tUxOqACkiFNew9B+EzF+V1h6EU3f/heDMgJlwj/wi7///6jCVXf/l6lWiHllZc5N9aFGy8hMbJuKWwEEiWl/ELFmJ14HgOfos4fv34vy5h+O/jFujqQJSZc5lhqAKK/SZza522aYnO86w72Og+qy1JuAqR+JQ/8POyaWl+2USiUwWCgQlORtUi5990e1N4FlcTcepnSR+ftzECZds61LKepYp5iWRilfurjXtzEmgiHLG4xE26SVyGAMQvR1zi//s0xPCARwyFLaeMz6DAimU1hg1U4lqcffsijNFMV43cij6N7B8KfiYeNTpXDiZVYOi/MrNPfx1hlea+BxTdiavKjH+AFZMUfIanMDIK6aib7aVbOn4lsomYQ/UsnXMuLlZ9LKaWzXTUdpap1mHUYjA2KHVVOpOKlS5FCsye+vOfzffy34SBUnTtgo6cjKbG//skxPmARehPJ6w9CECniCT1hg0VqpVxBlzVtWEMRpiEO2sbkwcQggcyye/zkKuq4IgfU740gBh5S3113KnN2omOwQkVXIGDudC4LLXMVqO1Ts3ZJKXgjkPv8wME8LJEGdW4YxYKBGR0yaPzvpMDhuhdtY1Sj4Q3//s0xP4ABmQjGzWAAAFRkua/MNAASx029N9osd7XT1oKOOtrieZuYaOar+t2qIuI5e4mkYgJ4qhtC/8XPLXMzU5PJoq3M///7I+QLqPPTmzfbsNyPbzs3ZalwIcbdF2fjwHcmQDACqEGLNoRIsT9OJBsZ0SjVu01vr2xV6oFVS8Sn/8rdPq0koWBqK9b55aH//uExPeAF+FLM/2MAAnhpWg9hI5wTINxS1W1TopFzhzlJSnlmv0ud1Xa7FCOfBVQ8o/7be8rMub/1agoxDiJdol1VzpBKSYXTeOc60ME/HU+SF51zBzAarscVPWfxcZz5FD2SelYtv8PkSaTNjhgjOhhQAAkCCEZS3yts8myMgTN5/SU1y4XJ5ocN46lIeZPk3Ms0bL1vvG/7dm25ZOekcVDds0K7wrIVBSaKBcQBOeQAoDQBkBo3AI3I2qYNg4KSEBYOfn/05JkWBbc+3A0zvQJdaIOCVeFJPLoU2Rj30A1QxyuqX/6fP6Utpn65l5LwguTMw8byZgg1r2Ih3/qdLFIQJABEHQTI8BcOI0RgSpigBIAQtep8XgiUmZZClypBtD1VPto1MkhH1r6kvXcbYPhsM0ROot4wSFdcTnKTlFfV38aWiPP3uyFIwJrucv2//tkxPkAD3FdQ+wtDwmRqqi88Yso9e5GZOk9AgMAFECUCuKGF2Gi4lLjyZuzsIJ+wfHBBIAAjEb4rBmJ4gcGqVBTByXSnmwP86CwbVWYsGWPB1apauXNclz9/N0kseiVWOdr5TTMohJgjvpXRIlEc56SU4B6gNRM1sUyGfGltFvenfzHzMbxHl8eEPYGaBREIYZsdyYc96e0tYqOWiolFPnWMCgApLlutAHp+aBK+9oABllARi5JSAApyP49I34Ctm3CGsoSacxMJHaAqzjzbEmbQt+dyCtZ38caPc0MLh9lUzvqJk7ETAjf2k8CNPyJ//tUxPaADJ0nN+eM2QlkoKZ89IzwrGgaW4bD4CcJMMty19EtQ6iJmKuvj/550+yiz5Mmu9JmGGFP0bEUbV1+k+WIIsJzxYKGkBoXIeoC3fi8cotQ0mOqcUSyRhKFb6LjgYbpRGHIll0Uk01Uc7BX5w5dkPQSojSijgIClWMsILeqrOMVwwEAqUYxjCi2uZXeYfdV/9vllK7Nurvur9DsVm/ooCGPAp01BWu61esUrYCHMQDh9DozpFpYVdbe2YKt//t0xO0ADZj/L60wUUIHJWX1gyctvrL2q07SYaBaNmXj8aEOru/cXB44WFBUdxKxbFP4xDnj+UjUyYmGf47amQ64Wrjmv77++vjnt2bmfHoOvDdt3YAlMO7w7qqqCrtWmAgUAQAFD1eBZAIkErweiH1wOsI/CmkrdNTCcbBTF9Qq5OBzG6CRgt01sitLpMnozdAkCtE4O4qHay1GKNVSHu08zOtX//skZuj/07ILdMyQJYfSKXCmYf/s/5eLoxSSL4RCJ7//rRBodlNmbeXVIBsYByBAkgC4YOaXIa1KIxhTX93uV40CbrS7rs8Zn3xvajSRnxxyfjDpDg4ct7d2TF6PKpL//t1+p7LH/8ffz3HNVPSTVcwt/ayYayILDM6M//tkxPsATwEpMewlFGFppGY1hgks771xogMzFAjSBENQdCtp6r8a+dvur/L0lDmsbdG70pg7/ay4jzcI/P87G9/zy3f/JAf2lf//U+L1279VTdUSlTNcffBLFqDUpKzSSOmtkcbkcjgSAAAAAAFYYc2DioVBDAoOIiyKPN7gw+Abz7Usd1YYtfO56noaI6XVcIKVHDhLd8yggE4PX/5nDSo17Dinf0/F/16m4uytbTxer/o1rpCH//8kBvtJJKlE4W+0AAAADG8sOID81IXjWA4NNtw5YnRoTQEUAprDALkibnDjLHCBoFIaaHycBeQ9//tUxP8ACwz1LbWEAAHFpGZ/MtAALIYZHQ29MUwAwxeTdE6XyHlYfx3EwQE2GVGshMDchhAh3rLqJWOHCSHYQFF1HT6BcMzpVZa1KUtlqUhazV2Vekiqy7sgtN22RopqQQPou7ooGCRsmldSkUHWtnprSY4KmAg+s6at+3qoMgl1mhhglzaS8lxCAIBAACBCERiVINAF/TQZ0jnQB3iUmZCypgayQEGOZgiAVIB2ybA1x4NUgZIGQYMRgKBgtIAW//tUxO+ACo0JL/2EAAk9DqY+sGAFAAYsQDjoN1gBHoX1TNB0gFBwMONCxIuCeQUEC4iLHisYh2C/RWBECXyfKRsXSumTZusdIc4LrhyhEkh1kNEFRop/9SH79X/1oqTW2kmtav/r0zpeWa0lTjopGVn/9qQAHc4HDCEOlFoZJk8DAAADYQPBw7UjR3bMKAnqWchApUhLIm6xoODjeQ6yg+eVJUSR8DG3FNK6jjBtGK4ERomOUAlljWpEgHMR8HQo//t0xPMAC2CVLbmkAAJ4JeSzOTAAq8K1IDeEKBgIpf2rvsZq/rImDrfn8sfgv3F6PCYfptFX0eXXpgeAOc/OV97/6ljPqbL6HVaTc/9/+/w/+9/GU5Wq2P/+993/////5W/1nrv61QXrX9TteIYQTIAs5SSmMIggAAlCJksFGDQYYeApmonmLKACiW+Q8VomZXDCA5sRgQIVBUCOUYDBIsm/g1K5pwzDwDBFgmmIJgI6twS4N4kOfjCGC3C6QhEFAxCEyEKqM6yx10HEu7doeGE4pLcUn/cAyAHZuY6lQJMX9TX9QUoxXu7992NwPe3W+UvtL+fv8v7//zHKpSZ4f//Wx1zDe8MP1rf67YwuXe0lj+fruWXe83ZqXLuHM65r//uExPwAFBkrN/mqAEKUIyg/M5JAU/7fFxMH4m/////6HAEgdcBMNB2a2tMBEAAGJAG2QDBohzIsmvGA0HAAGOU4CwMnLxmYDP8SBQguBpYt6xcFDS4DiBzBCSAHxJJ1UO0vfRB9MAs+WnAilpRctAYQJlplDZsFtdv01ZEyLWrPgaBi89a318SQVyL/2pYqBtd/aiYKDT7tf8zKq3/j/3cP/v54Ul7u//+Y////6///9VKSL5WJf3P6/MqXKm9JccGBAhWW2/++QgNXoQIAFTykHiEjp9l/nCMLQAtMkeSvYSU5SdDZlhbtPHzATsLyHcdp0xQNCmMEPMpqMDhkssIA5BHEsIIShKFiv/odlG5oYKS/9aBRLRLhKB4nq9WyH/6TMtfbPGCClrdXpHFMtTumtFmZI4krCcbagygP/aUP+hG14ITCEDVTrnY6qdY6//uUxPaAF90rNVnMgEKboGa3NZAAxXTV+0qYmYLTLRfCyGGNBwk8fAu4TcSxBqRkgxcQMUR7nZ7//XUVIGpmbm3/6lmpimr/vX/Up1qdBlq1maakNm+pTvsdM5pN0R4ADwATAKWmBmBQAXblkGggCAFKASwMoKC0ImFmJFhApTxylAYDBymwCRJqjhmxZiwiTJnIIGkLgKUwM02D5gDv4BekPfAzDMMfFzgYAIDeQDAJQNCaCxVQpIshb4Bjw4WaNw/gFgQdkh7YBwwLCp4jgBkIzr5qcK5LvRNg3wcGiP4ZGHa3v7ofWZP/ro9RXQZD2ud/9dDnDQny/1PSSTPfzeXVSWKlwAAL37ME7UhBoLM0hQhI8ZM1PtlaNDVWuOOzC/Dz8EorheAdKspij0jFghJmPYZniCJRFkELZMDSh1/5p7SQjIgoBiIIQi//Y8XuSEyf7f/PZVKGv1V09uiopzc8whrNV2PGBKXd9apnGPq2IAI6m2waSHAZuWgg8u8D//tkxPkADcUnQ/2GgCGTJGm+sNAFEoeJWo9vysZhrkS9YH2VUhKG6nlRjRl7G3qaqSOSFa5hREv//MBhgFP/6AwJv//9wRzCRQkypKAjjGPW/djKTlRfVHEjkWVQeLdRAAPtpKIoPETqS7aAIArRSqTxiS5YPaldpNB2CqxcDmYbcIokKJeFTihWbJEbiaIMKq3+94iIOJBwh//qziwiFFb//2daOzO7M6lEwEe4z/4lKqf19WQIWmaqqCukAAG7ZTAwMTW6Q8FlyGRWS4TAyR4UpwQrrl6zVqqgNVVXbW1uZaF7PpSRmt6+RtyLNE9i//t0xP0AFAkvPfmqAgGrpek/sKAE/K1dDDi7t1UhQKGTB4agdBSn/+VhgWEhdvf/7lZKsVkNVkGEFish1Wqu7W9GLslFFBI8+3QEbaQgAB/5pAseT3ZogFFoCq1hWErVghC1DgwlhL82aCmlOMRTGkt3HdNSy2syeNzN27lDsM1FnPu8dygGhz/2QaFjHOJSUZhPDgNTv/u8EBiw5upVR2b7sY3YgmtHoY9VqrsxARiW9+l3ewghZijdtjACN99qF8JnNfTCW+sQKjUXLdw4/aw7nuVJKlBUlA5CEqISJUVIIIIIhZFTBaDrEVoSv/8Ym7vwYM///+LcXDwOBl/////2/XKfTNu9svK11S2zXfz//28wkDIkUEWU2q7MiNCM//tUxPyACzEtTewkTWl3Hik9hJWtwef/dxDAQAROBBZoAFLmVnk4QzgjY0kvHCGoOy0QpF6FgUJETFhEGDkNRoukm8RJdoZKGZXW0liELSqGqN2IRgcrlJmtOh9zkhB6sR/9MBa539JQRHv3JTONyvd+I5zN7/gF9GMSb/12////52s9f/xBzZFmCvb8eJCX/gmDjYhVAWQWZ8BVIzBQFUnK4EAYAVQBt0HCDLNDNgjPHx7lBQl7cA14SJtTX4pB//tkxPYADUEtPay8qem3pag9hQsVPZW0xxERkBamAwIA6zgB44DArwufDLQIioKAQM4WC58hpBwUGl0WsERAETMEB8DbmCaDiRdCcik9QCjkO6V1Czw1WXNZ4cJbG9kDIsRUkdMtEo3SMn5mTak+US4Oanr6a6l//UvW6zrYiYSyDGOiOKi6lpc0RDISGaWwNAAAgAwIG4ybmoBJAYgAuLJsa+loYxHgYcgecAAIsU0oCArBf2qNuFwAnlskWA0qwDBEgDxgCRQHnPiqFJASUgZQAKMHTiCQJCwJFRC4d0BQAILgJChcEHIjkgDIgADQ//tkxPeADBkrT/WEACoiF6f/NYAAg/RCRcgZLmaIA0oVs9ZuVCeLWRxaL5rqTMf/WX6HWo7//////q1N63SOotpLLqoBN3drsjQjYgGZL4WiMIAAFBTBWVloB1AjRETCGy3wYic8WpuM/LjrRLKNZgUWsDAKA1ALfRAYDahAxOF+wChIX3EZhe8TeBgA4YgFsGXC9A5gngQQMBrDJBk4g1GsBQGMibLhgovdBIw5maG7bHTrdSvUTZMv6jZL+l/UibnEyodW7QBzMEgbslQMUDIKJ+LQGAwAE1QqLJ5GNBRhiUdvGCwXdMlBmvGgCDLn//uExPAAEzD5Q/mqEgJmpac/O0AA7gdRFJS4uYWeBmAInoDMlQajwM3yAzycDGxwMQxEqAIHgNIhOgXsAyIAmRSoj4XpBgwoN0R2A8iGWyjrGKrgZcwDckYhDjIwQONl0lizyyYoPqMkPU5Mp9SZAjev//s1V2myX/porV62K4HeHjzP/7a6IyWVvKZVZ2QjqlskYYQAAb0yA8mBG1Ir8MwHKNMNnATqdgp/KknUa0QTDJYNhgN8Ak9DEwHVIhrQM0cAKWAZkKFmwbkgYxMBxwBCgLpAMCAE2CFwbriOgb1D4D4ogIAIFgZNuyYXcXuIcg1ZfdDps7dvuXEOpzqvof/+ccvGX+ggbm/eSAVDlwKIKuYphP1ooAAABBo8ctY4lkmTjSTz82VnvKGLCqQoBFl0JzqxjOC2hqQOlDsA1ggxEFCICCQDxBOAY0eAFPAt//t0xPOAEJDfQfmqEAJkI2h/N0AQVGXFgGZTH4TkILheYKDwufHNeZjSVwWGCuoqUcPK550er6BfLqvq9azPyCP2nxMilJmiBjRCEYXLYmiCAAFbwxAQADayRYCZ5WNIYyTOUAAQ7hCtrDGQQOkQLACRADCr6IpxIQGzI9AI4mcc4LLjxpcNAi7LUkxjMImoHVpiThwEZoMCX9TSYVr/9msU59yzh//qf///6Tn/+N2OS7f//65//+drntBrk/QG9f6EADBtTRCFBUFJLwMMxWKABoDAIWYoJGtaE4OgRMHZkV1RGCAjfsFMWD1Bi45CGAYsJQFgoJlgRwQFDwGlXh5AMMDBsaE8gJTBQ+HPAwwIGxAhELQCIeFvgAQIDOqh//t0xOoAEHz3P/mqAAHMlyi/M0AIWghOAkGCwQs1pAiqgYEMSZMFoMhkR6Ldn/+YmDem9XWXz2/1VpUaFjHQQoM5FK0vqrTdRtR3NJcNAACAf/6tNTACAtmnAnIDQJpwOJi6AAF7EJZSJgT6+R1uiRfHmNOED2vOgaUZdVABppwUoIW4ChYLamANhQChYIA4EmRBRzgKAyBigwxGJkOoUKaBjxXAwhEZQPiDVgWVE9UwBpEfZadQm4cTMeb//6zF1P/2OlxE+/3UUiC+1SFSzc6gT5ieMjp6zpGLW/lzLKApEMAgBfq0w2MX0LDZG1kHcLySlfdhVVo7yyB/ZuVxgkxlgjQnQ9kDEnnTMZRDLTJTJn0TcfxAyKMAPEbTpLK9//t0xPQAD/C5O/msgAJzpCi/N0CASkjVel+prqMEFetyowNy4gbGyXatf2pvQNDEzQT6aaKLq/qUmn/0FpugUz4Ud0KKoxAGNvZKFDwi4+eJITDXFAHB7ImBsuWHdeSRDeMYB+NRoLTaGGigUKNzzFFaFzhYBQiFRuTHld/d//9XMM/QxhYLDyb//t7MTLnHuy5mjf6HE5mz2P5pqGlSwhBUCJ6MhNzORPO3+WhsJgAEBGAkkYQJA98xSyYbIOIsCZMhvCERmq/8kOggqVQ9cewsIDbhRhZQjonxBMi4akA0AlwbCgR8C00iVFvF8BAoDgAHaL7JLEnN3eC8yMWgj6PmBcdJSjI7mVXsgj5gtSPh+yEq/wBhhb5gNSQF+AAA//t0xOsAES0FSfmqAkG6JKg/sNAFOkAAh1ERYOUTfJSB9kcXUFRFZYXbTq63zqRaOSsCgAKkpBJEiQMx5D0D8DKRRxLPlQl5kMoUAexbgFASgHmMEPY1RR61Gp6ZGiK1IGa0jRkkDNL+kiSZPMroN//7Ldt6ra01nsXCbFoH4cCwOFxIhaXIBAheVsBsIwsmoy0YAB5Fvr5CZWFhqxVwp62F8ej9hh517zpCIzMD2xF04PWF4cj6AEvIoaRzel+3tVnY8eb+5hUiRPRf1/+prnHHmK6Ot2d3ozshU3zyDCpEJHm0EwQo/tAmC0IshezIUxC4bXVbpC0R7vYDJtTEpci8IPjGu2zKd52paycRkgueAZk9//yuVpW/qMFxYRFH//tkxPSAC8knSfWDgCnqlyg/MzAA///qxXmUs5Veyk34qg+VURKkxCARkUBoARBBONNkJlKDgCMD4h1VhoSLAY1njVWuRnDkyp4qjdTX/5maoPtyRCsS//+8Pf9YJgkh1TRFd4MBXYAAZmDkg7qQzRjM8eMpsQojywdZX2AiIaK3Rv7yCiyujN8ut4XrejXaeSk8QSPDsIJXwG+BqgM9FWuXqVoUxJ2Ygm1iFiZDhKwXz/xMtDKge6YVLnBdBSyeE6Ca6c12CTGAAADilgSUUPNxEugoTvA2qQLI0CPqgmkwTIReHZklHBFb2/j+DS11//tkxPWADljxM72WgCFxoKc9hh11Z43JeOTy4A08AIALoPoEUxmmAzBJXAwjB7S5aBh5gugSvu0ChGo32a7bxaaZfPsQN6GA4ef///+gKvV/rlVmh2cDOpANECMlnxo7/OMt8vFi3OQKwjntGgumCJmv6NmKyTp1Ww8xxkkHQdbf////oo8LCzv8CDTYIjl1HEIKhpleIh4Ex4glgAh4BsHrvrVU1L2tNZVAyMCGmMbbBEuw2SOq/SFqJqTE9U7CUSDoMf//+z//RVVo3r/S0ZTVN2aZmgMaGBEAJcDQjRi9C800067AIA8DAJmOK7Eg//tExPsACfUDQewkrWDvC+a9hhksG8IxOBNN+ihSj4ryP5coUoTt//9co//iBC0dod3ZnVjgTAcBuAag+wVYhgYyLSrSwuETDarX6FCKAriCiZoKTL4YJWtwZqQX9aN2cLLsIG4kFZNv9x3xgA0A8AgOLIWYQgTQRLXyUxWH88dRLRlwqJX5cwlRNo8TzgD4Cz+xH22/MyvOyvRYHkXv6JX////7CFzv//skxP6ARjRbMcwl5yDAC2Z9hJj0ipuVPXUK48AIAOkhOIANalBcUSLZVzFNE5MWWkQU1miTIOZ85QnYSYCCHUOpiPKdmhQqxYKE2LsXI1wXiqVUcHj57///+sAqaFhpmQNcOBWwHdEjEZET2xJaIluM3mpXacNx//skxP8ABhBfK6wkx0jlC6V08z0wJZGCi+zwHU9Jcj/P6L26s+oed0hrbBM/aWl/un/z////chWfp//7HIo7sdFtbrqhAgb6UeIl4gRPDAWsA/wWgBoqwLgQACe5zPJyllFRC3S6rmf9QiEOfZjeX/WwaUkNtHP///s0xPuACEijM+wkqeDzlWY9hJUw+ox/9Vn+MjZXh6cSTDgfUChC5EDVYmmlrxEzRPJVzQlKqnseIp9ph0r2T4U7UVRDI+zS/T/psYcbQAzos0r//HCFIZ/1rOApZ6hQqpIOIh1FCoYAjAQkBJF3ArKEX6PJmSWAohtdNREuu0NA4hu2ZNM5Cdhy+9o2CKMg//s0xPkARvhbN+wlByDfC+Y88SaFgc////8uk3/E9VWJl4dIDIAAABSgFxXQQMYtgZLIDyOxetTRFrMowMgFAwZbv9NDaCc7/lX1wVXLJK6z/6KLhASkt4PCZawwSONMk4b2XnVavbx1YafAtiV56QvEpSSkBr/0uNTwjZr////4//xirccrNMCAAAAuA0CD//s0xP6ACGBjL6w9h0EVjCV1hL0QIMXQF8ICfd0WHaD+9lHBdkffYnevTdo/9brHgirU5bY2GUaBoCuL8IeHEJqPmGSxgfVRplWLCBt7CgbrWnzla75OAsfLXvdYqgkWgEgAWhxCcDSCaXSj1dzbqFmRBWpREqwskSJl51AIxxpavupG3wdgs+NQgFTNs+EC//tExPeACcj/Oew8S+DaDCb89Jko0QNqmjPy5cCoyjHRIncudVZhMQBBQY7////o/uVVnxRrgEoQiMpQSUXpd2h2qyJc4tciooG9hmYfSsDnjxoqMAop1BtRcOg7wt4fqMfIRfFDzLBGjoBsD/lkQlAVsCmw/ipuUkeAqDkLqFkGOPI5E4CPVf0cTJWlM6tFFuIpw0znibb3yqhVUNoBEEhGOZJPCwp5//s0xP6ACKhdN+w9JcDgi6Z89JkgmWafd8RifOoYZQGvvqwpmkxBTUWqqmRJgF8mJGHYJAGEuqR1a/c64GymywhQj9fmA7vA/rDXUgqn6OoLI4RwWgOHd99ELgg01DTyopTcXOUChV9n+1W5BpYAawNJTlStep/ol38u/z+5Y1QgwvWrafWAKM8OzMzsqqCg//skxP0ARhRbNefFJijQC+X1hiTkCgUAAAAgAALXm1yPqFSrQa7KK2cHcsa5m/+xTBziqN51N/Iv/3b/////////86oICf+VD0alktbjkkgAABFQ+S7IIlccdMtHs+n17/GDHElEO6sp2c7mJTM9U//////////y//sUxPwARTxfJ6W8wICojKS08rFtle/M4JWMZHFOn0vnQxjtUxXeo4ADu97tSWyOyS2sNBBsJi0fiWEhiaikNNV+aaWQQuz6h20xDYFpx1TIQgcDe8tG2T///+vMHLS5//sUxPeARJBdHQegZ6iuiyOlgwjw22o1Z887MhWMiLQjMSzdXN3Y7jAQlKhppo+xafydn/QqjbLLTkTRQABugPksI7DBKQlVaOvPbkxYzZO4PDz2mMaMPhaclnjY695o//sUxPSARABFHQY8YKCMh2Pxh4xN0PnBBIpWQ1K0yrRf6s52/IjrRjMoFYxttW7ZTGVarSYWIyioqxx0ssNsLRdLRvV+9X/12yy2KyQWQEgMEP0SIMqy/iegQCpT0w4g//sUxPgARFA3GweYZyh6ByNg8I0FQDCB7wHAIBhQcMQWcgIQmVI9qt9Z3shgTEf/ogiBQaOePjdhhuinGmL2qQGhxpMCDf04IUmCyTCkWic4TD/cogbqQQiGhkZO9JES//sUxPqAxBQ7GwewQSh/BWNg9gxVAuTPOpL3GCGIIHUBAOCEkZbydmXm6MrnRpkbdHTXECtladKvS7utfTU5jij8q6chAsjCagADizeVTmnRsoCCp+iU//ZZSkWJgcaO//sUxP+AA5wrHRWBACj3nmZ/MCAArVlRCFseeqktMJOjmEHYUKJtR9/xSoAJodzGE87sIQR1ASFHQFMeMuhi7f07xxu1hy1q7KNvlZgaxM8t7gqni7bTt/Dtm6mlMY/T//tExPeACKUvJbzxAAlMI6T0wwj49KlfiQ+DxybEURQDp/eSWRbihmd2T/T/+oI0gGwzW9qL0WrK8ihhlKUY4yJmHC/TACaXmDY7uVSUIyTRbmj4DBwU5z3rOY0ceYmi6x5o8glExOHPjStoOa++nPbtTSGsTrNzCIw4o5CD2/shw4rONDoaVNE2T/+zMiiAmIHamjKRLs7P2ZyDUWpbSHHMJig4WN0h//tUxPSAC6T7H6ewp8FklOT1hJ04PtuM3oUwQFoEbXjH5CXUBykkqpbTCW19eJSMFeR3jeL+/aQ01/mNLxdG4pptBGX6scIcWKM/3ysMKdmZW/lnX/+YUYwMuyPVELBFubdUbFfC/yOWujCIeYh3f/6tIC2DQOGREUAVMhTAkLBQVp2zcUJQ0iPIywMxrnLIMGoRLPss/ejuHArCW/bUIDdyf/64Z9bkREuPge10ttucBACeqKDlBGggEsZK/teS//tkxO6ADUkrMe08p+mSpGZ9hArcHF6tLzJI4W7uPbIe0Sh20bXc1VVl/OFZxf/znG//+KXC/23bbZMAAFkDgx3zEFBDUkbAKaR0uOs9d/IwAg2WuL6BpxREDyvXwDEXE7XtnYPjfu0Wfim3PP/bP8xH///q5nDwE1u3uteukttzcAAAAAAM+ODwwOOgocYFCVnmOS506B7JRvcO1bFwgVehoiqYRWz7/lzn2S7u5k0POYs/ePBCgSMZ/0i3rYQwHN////+gCdNyU1hmVVZUNVZmzkjSZJAIAGrAWgiUXBMqYSGBVKKL8W0RMfkv43I4//tUxPSADEU3NewsqelXH+W1hIk9Sk5DjMW7LiuJI0B9dVjAKp4XwsDA0n6aKvL8WQNUkcN8iGEnrWkU+Qo+SIYmfS3Q/zxbV+FovVYS5xHzTP/tNW/1rEVVRt4eQs6vm8PGtbxJmNCj5vieMqvjOMWzX+/3XEa+d/6gUmgQK33eJHf/h9lRneIVmjBUJYBnAJZog+hM3olUrBjq5gjWls9fCpohhWxjOVQ85xUCEZSXb/IdLqmyjcpCJa/HafOw//tExO4ACCCdNewkRyDSk6V1gwkouPmb48VDosTqRrj7ogfBKTe33zaItrKs1cTQ+mlu37aHzfuaHI31pv8gY+jddWhWhnZmSUgoDKBlBqB4gPk/zqRNtdByEQ/SUaEq9PPKyE4nmIr/8a8SrY+i0iSjokk2dva6H8GlArIjZklOq98RIcBA44OixYNDQwoCqxUqEUMYhpVUaGZkV1raUIQGWDSRwGYl//tExPyACHifLbWDACE/keY3NLAAQxxbQnlFDe0zT/6bmiB5mhLIrd8JmJDbywa1+Z143MGhkSVNBQ9Cc1M9iwZWGrcMMtxUDTyzG94V1PBktEpUVSdYSy4cCiLnr0qVDS+lknJQ4sEcFABqEbNy7hCVEtmromO+pvFvA+WCKm/BWnc1ofkY6WlKHSnnzaIxBjNiYlbOvTsIFMHCkKeDHeDmVcKbH1ZL//tkxPwAEuktL/mXgAGdo2Z/noABn/5n/z5wy+fnWWuPtksnPBGKCsJdP6li0gOpxcyiRXI4Aw2QGnKTDqEhlpmYTwI8Nycl3VSxgkLGLQiGgo/qAk2hYm9cn7qi6U1iDE80QsuwFdDNO0bYx1RuOvfPmYbhS+1H9k2BwxJjjgrUsNWiA4hYwGiLQqTPEHJVA2Oq6nm6/9nKILBwldMgUSLvLPmxIkPsTbc6DULnFfqNkSIjoTaFOEQeAFtUNbnu3q4GKDAAgqomfPP03UUOwIWZuxMzFa864XMuVpCXz//9a5CJmKZH1LSEZnECZo0w//tkxOoACsCRM+eZB0FpFWX89g3gl/k6u5O39tirBeXCw+P+ylCiqrEoUjxgiLo0Njwe1JxrqPbfvO7NyWDIV6NCYEpSseBHDdZ/KSxb5lfkIRB7Ur8GT9jd69CqP9zKnMttiD5FkKFamDYkj////2TNF2NYIu/21Xjwh2spjPDEAYDydXelA0BphlRYbv26LJEB2y1jQgwhMOLKBuE01fr/y5jT2r/ToqydyZVdmonhO85kQMuCCTBXbf/0oz5SAzM9NTQIrM9nK9Qx1VVZtE2q1qFsVR1YrX7oa87cvFTTBVV39M5RrvEAB5YzAkv///tUxP8ADCUjLYw8acmElyd9hg10WkEpk9XSSTVVRCkLUBhTLXYTxobznymcd+FT1LQowTFNZ2zCJA2Yvvud18sJnYoGhszeDNA6hCyi3zqlpw7/nvxuxuM5i5QxFyipQWWNEplKCnjVAAB5ZTFNPtkkCZAgwagoXY5AvUqArnCONBbQ44EIlJRVHqpI2U231VRbzYuEqPV8//vN1SfzPV5d1EhFj7FyniCDObaryo7WV9a/Z6xyiZbJu5e0itcY//tkxPMADPUDRew8aymnpGh9gw6N10NXmd/QACeWJBSX+1Ih6iRSUIyaQogCS4AZ0VhTVsNLdn7VEIi+1rkDjW7U1H+qmctuauWQU2pzKp3U7LYZBU6n+QQ8dutmM8hCl+q6tvQUSLmyO5+pwfoRB+Yc4d/9QKv2zdn+DQFOkmgYYh1kelJS9Lpvmy1YBibs24u+k7OyUCBAzDPS0ZpwxDMpeHlmT/550l+u7RjbygFBf///7ZZHeGIGmIdryqQk/9+7b9ACBPiNzF0HmnoYJJUgkZLlYTocNwnJ4TmC46B4agA7NASq2gYDgQGZY1zJ//tUxPeADDEzQ+wI1eFsHae9go4k6c/n3ws+ln///7WyK3Q7rds3tACBSAgDmlIKyWwXAy1MWKLGfhr/0gMiIdfY1aYsmsYh7aLzTJHM2Y/Y+Iwu0AOFgiLQy6dxoH///kG0Q+6Kj0At7N11uN3BVB9G8z/gRwUq5ZiAMNZifyC4lvPG7N2Gli8cOgZFB2KCQiqiNhLEWZCdG2CrDZ6oTiAml2Z1Xf0AAB8TOEOc/boDPAYQWc7hcBUlKhjYTkpi//tUxO6AC5DjOeekTelqHKa9hImtDqtnT8ZbduFn1P+wtpS8IFA/eXnbP7PxeKhF2brKC2TpkegA2gSYOYIUKaO8E5GZXigteiYQtPNxN4yoISrFgmPsR/Nq7cQ2JRAj6sS5pd0pECOYVDJreAAAFHQE0mQzlYzoJ01H6ct1G23AngL5DR463FFggrDMwIJb//keBGAQTTfEfVxXkSBmiHQzNrgPCSBHoMvEISwABNa85LjFVlZEAiIRYEGCoNco//tUxOiACTjhN6wMUaD5ECa1hg1UkrvT/fzpGJTOfrxG1UxAZ5WXQ2n4AAAglGBC1uQ8lPQCwYAZRh5VhUAo9LQ8IqutOzPxe481l5xqofPOYZ5qGpZgZYaHmX+4D0AwA0WHRIqtzQWOJtVzDyED+cBFI6E4YJSveKOCF+LutEyV/dykjhbtIabklT2kZADdCXhiDDqlac6Vjp0lrLK1TSSlmZyIf7ZpZYh7DKxhMYcuZ1rKHUxhLrMJTPAwG4y5//s0xPoASLRpMawkzGDhDWV1hgzs1GJqAS2alksls/HOBEXRGyAoYnNsoCZusX3/pRq7XRitt5o/LvL//yaQ8RHG5HJLrWiMEniYU5SSEPJ47l2FFz8N418JfzC/jnVqRGlmG4OyxOV5JUIKFwyohOaCOQ/NOFVyYwAv0wrHwjlD8pQSUmMqlzoUsYgTsofV//s0xPiAR6hhM+w9iWDOjSX09J4U02tSB/8msKge5coBKgPg9fSX6tUqnbimcHw5SLnaffiDEH8LgLxX0gPjSSi9XWowYigclg8HKOvTf70ibs/NvY35vf73+cpaj9qHEMgICZDn1bWqoKuoVBfSRgsxnF6K1oE3A8JRvVP8S67OyMqo88GtIs/3p5CT6Px9//skxP2ARuBTNexhgSjDi+Z9hhkVNSdIKexC2J86bdj47GekNndSubUYsduTpcoydc1wcjKBdASAF9RPwJAEYKpWoYGKnxeBVgoYpc6CIpJhEmFRWaSYD5OAqELIyiInPkKbTbD6JyLN6kUdINPOSgwTiSy5NAuT//skxPsARmBTM+w9hGjCiea9hLDlMhQWNvQmHHq0Xe/293UpBqSlE4IyMYFuS8BJDpENQpjW45pkMLEsDhlXKglUasFyO//2emZffVUXZhs2d2EyAwsaEgTIisYWRMr3jNdtimW+pbqRLIi29CxPnp87QruOgWdS//t0xPqADHS1JawNOgKGoqT1rDMY73D9qovLu7q4NAtKXjJNzvAiAjQt4Z44lE+V19Np8HsOEpPCrYUt/iFKIPvuLBpqvKWFUiIzPaFke+xlfJQtMj1ilDH9j2meZdSHKxLr7//539yRDQtzLUjFXHBkj3ppVEzdTM0wAHJzcNjHXiT4dYMn6rAsaOy6t3WOdjDgYYuc17DodTVGMEzKgympjD6TjwGoNp1tqLfIyGNMoKxK1D0I6xaW5HltfN0CaGczNEihLinIwrIQcdR9mkVYqrmlABRElh6C4jSFbVrGAQYh3a8chFBF6GVPEtRlYHCY/v1Y8XHL2EHABOYPKYYWIdaMKIDOUDa5n5lWqDO2dS3lYzS7JVfVzkXOTlpV//tkxP0AEqUXPee9L+F0Hil89Il9d02t2kOou1HQSkcw7QYQ4rEMAV4oMwFl4NIHseRERFe9LrNRkCjkRW41/OOz2ZPd5yATIIFMujD12L8qTEZAREcF7wggB8+Zmifs/r8xfPWscrXbpJVFQeG+lQu0hiyLPnqeyRAAQmEVfBQkAYlCYgAHSCYX2cxEakAwgQWGCYGzA7bKYeUOypHwd2Uz50+/NKFhjOxCXrZyddtc6d3ppO5lpnPWJnFy4gA4OP03/3ad8XfZL5nZEZ3EDqLHcZRU3yrlZ2VF1KhHnVnoRzRJK3UB6zQH8m+IgFVU//tUxPEAC5UdQeekbUFpoue9go351sjd1stAJEuZQDREPM0DwgA9nqXIny5V56nhCUkF036iSnH4rkyZz3B/GQtqd9PxyUnx8+b2lhX/ON1QPzBARUj38+gTSlfOU2Blcr3ep2qZ6Zlc1Zz+IKYIBgwEdNUkBbtnxEavtjYSYLwTEZQmIuoLQxAlRpD8OQvJxQOrJVNExBno1AP8AARimDHHgM/6pwOMIUjJxZZPS9rutZszDhSlf9oBA7ZnSzv5//tkxOsACx0bPewwTmGIo6c5hI4d4Mg6CFos/X5ViYiQigkIjyqAOtuAQAPEFhrvWc3YtjLJtgADD4plUZFEtxKX65vH1vnj4F6jiDO/QxSsbeY5t1J+j/jCdX8OArN1ZHLoqGQcUry/KClmJuf8tcWBCvX6sFqJAATQQEWoOQSQC6EoVQEMOMTxRplbJ2fjujqXySEKOyhyock2dYuUwgt/WLNM/UbeXzT6lZ4IFlbc4kASpSqXR1WrIoC1HUTyb8h2TXTckEDRWWIdqe1MAToJkTIG+LwFsA0oYSYU8lRelYSJRIRvJKoswD1SZYOj//tUxPsADY0XOewwr+mHIyh88w5kl0tBeSnr5mRhEzMdZZvSEHX+9bupV3mB3+rwVnFk+Rv3YjQYadJigjKBRRAVVXaZdv/SMA+BOah6FvC4CIDrFxIyBrqpHp03QrmttNzT26qrxR/liSbpFY/yzqDMNpn19HH82piIeWAwfev4oVO9o8MDWsNtRvrWxzmKQgQhaHd7d7UAE2kf0AqaydaHUSIzZsEscC8AUPwBpCxDx+56lmJLCuLGnB1lAY7e//tUxOkACvzZQ+ewauFAmyd9hgkt3lPWSktl2k0Bm/MW5spRT/XLAhz/36VAAzJneYt3sYAVuWeNAKyGQiGSWDAVlqpA/xABmXAYuMc761mNj75MPtVg+ASeVJ1mdSOJrCjP0Qi5jccsOWU0DCvqhgFElwA0Z/u3+ImX+YaW3BozJFMlpsRVWVo0NTj7OPp6uxH5jlvNccQUI4b78p2ZXF7fvP1ANdUAA2WIh3t1AAAaqj8mGwqAEBQNJCxGV52o//tUxOqACqjjM6egTylRFub89BX8JwgmEBJJJz/vnla79s3nOW7nYecpD3f+blpOIeoRFUB4Z2j1CL6wREJyUGTGVliELSS6JtTElWYCgZW7Ses7TCnleP6miYC/rz81yyxyUbE3BHZ4dm82AAASlJ2FxgFFuhWou+vgCgbEhFpOOloYc3PVE/eAAgYwFrVyKFDT+awiWHmO4IN19dbPBpWhKsSnKD/LiFUF4JKQWiBUSh5Fmp0uOkCVkf6zx4wI//tUxOsACgCxOeekraEbFqb9hIl8Ja7MvbY2kED2xH///oVgz77XX4AAAMoJoMnQwvqApHUawCaLbp8hwsTFJbVvvhYQevvrt29DgnA8ougvfqg6u8NDvvwGQGQLWi6K0ULldLuTna2s2UhwFV+ySsrU046L3QtYYH4MyU25cI5B/OyXawAAAZkgRZTpFykM3UYGnLUZMzcVlPl5wlVpRQShxQDQIKADgkoo5bUECSFeHZ334HNkAbPI0RwANaJp//s0xPUASOB9NewwaeDNDqZ1hiFVQ9RND8jPoLKbtEVTRGXKFCRFp4NV1mIhxppJ9gAGAjyUJQpYcAlFwr8blEtU1BWgrkcXqBmyJgLy9Zi6e1wcw+RNLbZXIBUTlUEc5K9eo2pVmolUWcJChAXFZGqbcnRgEACZrlD5GPeh3D+WTQU47FJ+gAJQEkNELQCA//s0xPUARsBrM+wwS6DLDOY9h5kMH2FrPAXspzVsyCSh9t0Xghh3CUjSVcG1ODrfnR0zCXd2Zp/2DSi7N1AOZQy4RqYHGXRj7yUsudZimrdzLt3lNBAZFeygHz5xCXgAhmpoxZZe05RekaQVNAWXiISNvgAAGfDIgwCaoEhGwudT672ur8fJ5H4TCSRhndne//skxP4ARpRjM+wMrujPjSX1h5hkGH3Ky9gVUM43mW8wQrA8lBP6+BSOxaBMFiVWQDzeQ0qZClLoBfMAR/7LnbaSoMXZi8Nqhcyp08QIP/Z0QsMeLNVRCbACXTfu/7p/Q00Thkq3rpUkHVXo8/xAAUIhKDD1ZyhU//skxPsAReRZL6wwyii3DSZ9hA1kR8FurRfx4aFXj1RnmGmjoENshY+byMhM4PQkWVi4QhIOjDddqno9+UHo6cEoA1IyyCAmpHAl39EPTFhBZmm8piAJpaGdnlthzj9T5/qc+3CKxMLD/5X7gdaW3Aljx10fsxNI//sUxP4ARbhLK6wwaiikC2Z88YGtDY56/Okqs/7XqEQMGn1/0FRSQA/C3nFzAADCRkOJCkuAEHNvEDTRhKkSSArtvQ3V6skkHTw+YPWbLS+egXZLCJq0VrkNe84bq+hK//skxPgARSxPIYwMyuCyC2T1hI1VwXM9NQADpGr0+kEqdpoLlQUOUVFkL7w+oszJi6cegXFlZ2D7UyC68hlc1hnL3LCAaG1ILfNz2rddf3C5lNUQAGIxhA4/wAAbuhiPIJxIyHSGEFNYUFVRbFUjth+FwT/kzyCO//skxP6ARWBPJYewZujlCyY9gyaE3VcqkOBMVLvBcTA7EBYr+7Oej68x1xqOhIN39xwnSogauaU50cdVEKGKCuEhmDQBQL/swdFqbWeZQAzWt5Yw9u1s5ZAFKncuQoEIfz///3AT3qUjAkcxhgQ4AAAaSIJBYpIs//skxP2AR1hVN+wdlCDvECa9hJ3khIPw80QHNlSAgQlt5TsOfoTkJm6JItnXcnR+Rq/VTDYyL+VDESIQgBVIIYCOBeIEB6d+EcBM9SMntqrMhhdRyBMZV5EqRskrlDQkDbc1gmFru+FErTAARBCXADgIAB9BGSUT//tExPOASAyBM6y86yERE+Z9p5U9IIiR8AYARz6TAM8IwHbTIt5Yr8Shkd1VOXtolFATz+8HhSiA91wAPjD3/6cWSAtStEECEuEBk6gMSO4bHiz3rpZopk71mDWXOLLOxCa16HDgSbwVCxdlryOKt////pUkCZPUAcAAAPgVYiwF4gkoclOlUs9fDRH/aDUZC0QkCNzzNlD/5ETGc33ktAgNbwwogwRI//s0xPqAR6RRM61hhSDkEGa1ph11GUAmAeokGTkp00wYAOQlmsPI5tgnMhIP95fhX3XWv7zEghx/wYicSUf5erpAMHcglQA/gAAaUMolCrkI+G0aA0WJDSEsUhKtQBFoV3RydpGppXshWtHvdO0HkEiq79Qfa4ncIJYREgNABThlp2p2WKOBQEAAAAASTGHy//s0xPyASHSVNeyk7ujPkKf9gwncYIBDGRnGLqgrY7w0FqnMRGKJFl1XIo0BiAgOmE0eMzEDUmwMeFE9DuDmk0NEkQ2MMjhxYjgcQwykMjBtuBiGQN1GdD+RALnAtADpAbv//IO4ssVuO8Zj//ZZOFw0P/5cPwJ/5xQDPl//4EcCADg+//////wg6gUSgWdY//skxP4ARshTNexlYyC6Cic9lh1VmHeIVPdgKAgEAAGrmGYYCJgBqGBRg0FVZg2sGijz9Md7sDFqYZJCdhf4AVBySKlwogAoGRQuBKopxFSHhl4oCEIDxAPEhoccNEjBgHQsJFJC4h/FJN6tUVsKCJkqkOHT/+Oa//skxP0Ax2BRM+y9JSDGCqaRoqXcQUycmSaIt//pVGQKu/xKDSgaBX/4l9n/9tpqAOpG8nlwAAA9BVEEg1Mm5ExwSfIQcUhNfGFNIYfGIp37jahVJjMhJTiS0lm0hI5rcslFlRB4B3h7OAAAAoAaMRQ8uZn5Z4xQ//skxPgAxkhRNaxpIyC2iib5hi1dJalewZyE52glPS6PiZ/MebpTGGS6HyBbJeyMMVwegvqjcXUDiEh4e3gO2OQD7qMu+PFL6tYV80lgTQonKmoAKhV7uSoS9qB0aDD/lgiBYIR/LDdpWhViBIlHiFS4AAAnB2Y9//tUxPmAB2BTN/WWACImF6h/NUII+rRiFgO82rgMhEAF6IFAMAMt6TRxQyZwEvQKJCAQMZNKTcYgMKjuyuQCIiJI+OXyUBADPy5qKpljwWyOzEUQoxVHN9JoqpaYT35Uw+MiEhElN7VEBIdHZoUwAAArjLw7zNZUn01MoWXsfqKPbPuPCQskRvMuPnLqFRN//1TamIj04H63A5FLJaGJskHgw2FzI4LPexki/bimiBHdHU9xogpk5U3zDViRyqq0//tkxOyAEDzJO/mZAADPCmb/spAEK626ygAAARjdB7DoXYMAD4nlD54FoOxFkNr84PRArfQqCXMkwOoOBddociijbgElWOkArFBYUQIVlBR9VD/CSwFB6zCPkcGCOPuopkxQGRhI3xlHT0wo1JI5AAABkGYL0mZ3AzgUZfTgotwlUOFwXIYYdZFrZzXTjCu7gXGG0h/xyl07pCljbcYEhnENEbXAD0IxPq0epP0KfCr5NX7MvN5mzhi0VMr4umV4bRqQADMlQYywSjaSiDq3520/Ewn6s2nYX2JOKIcXQCtEHIGIluLKKURRoT4Kqbxd//skxP8ARuBRNeyx62jNCub9hDGkNK1CSYEBuxjMUUWIdpWqQdXLTwgsEHASWILMIFXpHReqHm1pgKi2lEVGERQCxAx8oM796Z4frVCJmIG1PGHJI7Z9yoFzfFG0wYiWsCKUABUYiyABQ6T/ziFHOUWJGVkMK2ZY//skxPsARexRNewsSqDAimX9gyWN1UWGAduDnZegr8MqTLpMloAAIRnAHQaJzACMF7ieBrpnao2g4BIUOzzm8gKMUZKEyKIIolq4NlmDYFiKsJoUEAmn2YQj6lkCQSC+Ewz53FMlDC3sEZtMQU1FMy4xMHG0EylQ//sUxPyAxhBRMewZLKCZiaURh5jVAAN42AYgaot5yi9bQMjiMrgI3T4ag08pEnvZhmfklpYMWlCxIk/azxekJVCcSOXIeRIEScpb4tvNTeT7Dk1MQU1FMy4xMDBVVVVV//skxPaARTxVLaewZuiwCiS1hgzVVVVVVVV5QFgAuRUWKyjwOkuMVKbG4vsEC3C0IsV1SAYS3VKqWCgEMPBOFuFNHoaRDJyvisxvuxAfOf2pbSpMQU1FMy4xMDCqqqqqO2JZAGwaBbTKaxmnTHjvInTgSKUhF4jl//sUxP0ARdRXJaexBqiXiiS08ZmlUMu0t2tRRqAXwdx/HMrQzBkwF2zgUXE4RGBlrK4cxOEQtFg6/6ZMQU1FMy4xMDCqqqqpAWqAAAqi8wLYHwASiciRRPZNo2EIwQUO//sUxPgARQRNHSwEbGilCWQxh4idwOAgkIGjwIo+lxwFkNwDoF8OND4RBqtKwprpPyhPQhmwlKnONkpMQU1FMy4xMDCqqqqqqqqqqqqqqqqtJVeAE4UjB4tpG4MS4EwI//skxPSARLg7HQw8ZqieB6Ow94ydqK+27u5JfvqbY/dXAokA1GmhsPRpj9jubaxqc4Gr0TxatFUOPlq+j2kAhmyNRGk8CoAgPCkl3eYEQsFcczdCN3fQtxWweh8PtU0NSm2urFW2wgQCMQHJf5PdlcabmQGE2QiB//sUxP6ARHxNHSeMzOiUiuPw8wzUXbUdBbMKEkOihxZBZjm0HYkty3nIMfHH1bf1J9n/8wrSUTR6KqvyaugAMmW4F1FgOxmL0fioFzVhwC4JlR5Ma2CGBDk65E3lj10E//sUxPuARDBVIYeMR+CFiOOlhYyFkEpHQGKuEyXf3aT3///krd/hrfbaEgCsCUF3FrFkFIRyHhUDIsYXRuWkBTb5HwmwlkfuxXOMi/f3aOuFBV3zVdfxevwADJhTcwzD//sUxPaAQ5QdGwwwwmhuAyOhB6QVTCrZhgneaY6bEWtyhl9+Ps1ep89fTxjghqYWIIY3/8HJua/3GZtfUItNg9DgBZ/6VCbhJZHGAqme4AGAJsKlzGEOvCpa+kUYnSNp//sUxPkAQ4g5HQC8YSiGCCNk9IyIEwnuU6dZVWWBeE98veJvbUDmVCjSfaCblTEAZShobX5AAAcmD6J8JNgBkMDQ6Iv3OyShgykh9pUB005dAuoMDZABQkw5rqnFVFq8//sUxPmAxFA9GyYEZwBxCCQQ8IzEIf5XXYuXnbbXNwk8gGB1CHMN79QwBUKCILhkQcYGCWPIRGBp7MYZoINhTZu+KqbyjLIRAg9FVQ6RpzKk/qu1tPqeEYcT///LAmMR//sUxPUAQ1wdHQY8YmhqiiOk8I01pQEDaSN4Kz2tABR5KlYYtcYCqqI42mGRBRxgUEIsH177djCqHJ1OsljSiisOxrZ2dVvb9VBigoCCbo/nvrETl1iAtEqbsf/sBACs//sUxP+AREQ/HQewZSD8jyMlgYngwkdXoydPplqqUFIYrpUmzAyCYeRg1sMNVm1uah6qptHcIvlsNB+3tORTjSYM8qz//DRQJ5hTZ3+9AAAT0SjUxRCKxp5LGVw0Niat//s0xPQARqhZHSewakC/ieW09hkNk8uwJAnHduKscvNEBSPM905fbHwFQYPVBzxKgHEOzO8bcAOoBVAHoywmA/Aww6BLnQn49IhzohpW0OQ0qpkLBgKxcHwrkncrJdKQiDxrqjA4iWZ4a7AAABR4VElC4A6FyWpKj8VJSMzdDIKUq25kiDDI0UIEsMeHVQF9//skxP6AR2hvHy1kwYDMCiU1nCQsCXz0Y+2c1isCOxt8G4KSPjMLJjQgHBl2N+QtKMaDUotpCIHe0DInojhJt7u6zpvGMY2TdSXlGsWqMAaJQ3Zff6GgIJCEQsfZAYowQDj0Ii8DlPPByXGE09ChkNXlnL/gzp9x//s0xPiAB8yBMewlr2j9kOb9hB3kxJrbdmV5gAQHEBWdkqIweSeY643d6uaEYvIBGE7k0p8w////9mNMHzDlPMMRvRY+PCwuErFpwy//QQgaqxTD5f0JANjAIY0UoeZIjpj/qaCEiglTRIQ09NZdWN4DBMMIC80EWxgAYbIkCq8wuoGwmTwQX4niuNrrv5Vx//s0xPcAB/SFNewwSyDxCyZ9hiVM7EAJgFh0EmwcTFRn/6RKlUUcNFUiAs05cL1DADhBeEY7gaAR3AAUsgBiAMCgCCQE13J4VEV3Wn4YUBeGxxDzFmg2PQ9LOIaBag7FxJjd2cxG1/pLDokoSM6//1Dou56nZkRkbGRhCAIphDmh5YgBNhLU1BYbWzUATING//skxPaARnxbM+wkyyDPjOY9B6A0EmN0ZmzMkAcLRC+kZaUvDb6zMC9ZtIf11Iho8/Ly9x57mLt2rOcbBCJRGt6TOl56G6f/vNdkLuclIwCFIocCPXEQJhMFm6GsMmKKO1O6rCtZ9F0RB92rujX6Fj7GCPz+79C///s0xPQARdRXM+w8Y2DWjOV1l5kUJQdGBvY2EGO5Ep1/LFTiABj/9ILI/5IhJ6qetoBwz9gf1pAMaQpcZOOPBlABjWKCmLcZhKHhjlIqEdDOhE0l1Y+1vkk82JBnyUU8Ia3/++e7tEP0ZhhY1/97HfriqCS+MuRZQhEAIwN4MD7AgBTpoq1VJSI5zQdop9my//tUxP8ADHT7M+0w7ylsESZ9lK3kGTOFQIiOUQq2qBG7UTa+RiarVTPkmkKxAIGfDP2r8NyPtXGqjCVxGTQARATnXv//9blpEgAhF3hiPoAAGjJZBBqPhUDCVTFcLuI9jIgIAQLIZj6FESRbeyjVoVW66n8avs8+lPlyKt+Mylz4cOEXzDBw8ARLv//1VREAAUh1cD6gADAWE2VXqbw28kup5mLGmkPpBrlO6QGASaCLISNRGn7v3HBZILjRFRdp//tUxPUACXSJNe0Y7uE4m2Z9hh10VuoS/+J3f0MBUXAQ///WRAJEsMzsfxmKES32ryg0NTtTTUNTQZ5Ln2ZpBDQfQt7kF5kTCDbSranCrkJj7dy7lbtX5HVquMOgZ///UjADQWh0dj2AgAHyL5dFYmwDIHMErA0wCxJB6L4JGX0CSUhaQ63DBsVr+9nKVUdQcDCwh1Iev+n2dwQe///6jLQBuixDxXxREUuwpwIwyZUqxmNApSXiRApEnECc9t8x//s0xP2ACLCLNeygryEgkSa1l5jcbEUyAsmyeQbW8t2gaRLcr/w0bkg9L9Mj8gAA4I1xh5ROXl+i0xAQwkQ6EhVHBNJjBfdQ+5ulmB7Cx1yvdpHVBQWKEqQpggxI+fF1u1///1Il0T5MjBzBQhgZciNoWKTSMnWNR1vXxnbzBPBuTWa4VK1/ZUiotioNAAOf//tExPQACUCLM+yxKmEUkWZ9lg086zEgQkRoYiQ9YAAUOQph5FVLkteWGqfLQ7jnEdajUmeqQ5tj9jyICy43/GXnncOmWNFOF1qddkzpNRYYV3cBS2YVkMku+LFBlwwUIiKdJ9KR12vr8i9QgKQC2FZRAYqF9lZgqAUZHYjwVhpLIoUsCp2mxLWqAAC0ho6CoDAcAoOi14QKWGYixelpjYEe8TXxsBUH//s0xPWASByLM+wZDODzEWa9hJWsR//8kojSlTPB40KJVraeWIQTqztCebCRF+kJBSQBENiAQGtXUadtfbaxjJZycqm028ZG8xaasKNAFYOCFDRPbpQva799RwBBdoZmbXVgAC4fwDoQcvIRRAHNXsB/ggzbRqoVlKZStaTHV20moVZ7anPFgm5CIr9+1dTo//s0xPQAR+SLM+ekrODKiqc9h5kMIA53EErtNM5IF4BWIIDfRhapEH4FtR1gLiBKxePkg+HZo0iHMyPKFO3lXeXdOt80/WFRxEF7KmIbNptpKAAAsgE0GhyJWxZ4wF16u6ViLm0lIcjevhvQrKKTPcoTeTcVUxys385qscELZPTRbK229EAQHiTOPqlY4JDh//skxPiAR5RfMawwayC1CqY1hAmcCkHWbNAy7JERk8maQJkwsmbb6fGEI+nxF1er36vjXU4hYaENgTiseQf9a38wreGDFy3////1HBdn6YYrI1HFFWkBDZZFerLphwBq7TVg4xF11W8bOt/Tc5T3dUuVNncfCBL///s0xPUARvBfMew8xuDWDGY9kwmMLNPGPotSyHVL4W7hMsQdJqszUHp4flbr+xuXlY8yT2RIHlUpbJYLlYntMGC9g0pQcM/n5p4SEe5Th3uvqOUGEu5J574oIhFvScjR8ZEf1Y1h5z7/pipaZd2h8C/3KKEVWaohAVhEBoAW3dg7LVg1YKXCz3LkEQLS9xrd//skxPwARnRVLaw8xqDZkCY9hI2cuVqB/E9whj5qGk9qEydUiYstPjAqvXzdfg34LoZ44kIAomyHQTwPxGj16PrUMvpRf6PyOVHVL7l7T6fzel7U51JbGh7ohzmmRtXyadI9cTeOPUKh3/NW+5dHC9mU9YqJqIl5//skxPiARwiBMeekrSjLkGV1kx10PBNRuio0UjKtay3YKGVe09tZa0G9WzjdLH7ECbfycpu+2DoRJ2i/jWbpSrWGEZzWorM95sfn5K1X9nyKaKTqaQ9L/FLIuW3SLnFt6OxtSL35fbWhgIQ8CMon5CYaId4WEYCd//tExPQABmx9LawYTSkqj+S1gz1obgbs5gm2Gb4AOHgoIrBwqa1se0FldE/jjtriAMWRc/MQzol84KE5NR0nS9kI5Dh9LPqmCHB5hnDV1acb9qjf803BjF8NtUQmQiMrvG/NjolbraRZdIdlZXUaglEmGoGMFyhggBwyoUWUeBFdxN7HfHYFLAhCa/8nhDj77d3ORdo2kN2UmzTT7n5m5/vdq747x/hs//tkxP6AD7kjJawxGkIOp+Z9hiKpnMHl3+Zdt2/kz3cntybpX7cyvGb5p8yvXIUVs8/bK5FI2sN4MAYpElSAtJ5hEA/eSTxYIIhkJo9jIrVeQhNzfe/yCimEkTtlio4uglePL7WLDpSr9y6s9j39Dbzk875m098yKaM0Hn3Ir+fnnRlE214Y12akbjBTjYB6muKYeZLCCH4TPF8f+2lFIweMgjQsFtsEBaXLf+zWOLJzxiRu4mpJ4IvygqqSkHBmftylx+04SF/9pbmMioGPIz8wE2hFMS9R12L62pbIwW40BALylvAgkTWCW+X8vpxK//tkxOsADAkjN+wgcsFuJGZ9hgx4mRBAlGcIpL1wGl7/3F8dZkMORlI0kJZ+SkSGyAz/n91Surhj2tPpZZE5CZUeXIHL4FS1SinFE0pCCkSAdgDCXIB3AFgh4N0rtNkImkrSKEBhAs66iQI3MCEAzHLLXOggtYxzi2i0t6q/4oYbzK+XBv/rltKAnoTfo7ibsLY+MhQ6bx/jDT/+gkItuN+4gAfAk5kglw5zUEwS96qW2ffohOBmwdmln7cuZwuEpmCrplUJJWWcmF5/j1/mX2PG/62bGfSnv9av+mph663POqAAAB8BdggXACWIeSEb//tUxPqAC2EjL+eYcclYI+Uw9Iz4ShfFWuJGeH2OIiUA6bNIhNcufsiNESCpZPMBL8w/L6ts20gFMPDw8b7gzAB0MQDwHiI5iZFYJxqkaXB7mYBf68T31u/vVv2FoR7YSDVaTv7+EYrVIW+lt0igAAB6ACYV4DXChnuEBG+c4VhIlA7WVtM50V7Dt9XJ0jU5A6oUjjKCafLjmgIzw7s8fWioNmHrlBwXJ1iqBVTQwRir2Qw2tqGq5fhzp3qZsAkj//tUxPeAClkBKaegb4kmm6T1hIyoPUL12QHTDVdSMCZHiGd96AAAKIxzIptiFiPKOHZDbUzXrbi9AoHw3rxQ4Jg2b67ofoVeaFmFBysAGVhYiI/4F0sJU2HsI421XIPQlKlRmvcIAs4AA0wNBZwiEqbpysQBR0DIYcXtAAdWd2aPsAAALpBE1GeUWnPF/GmwMrdErI6nMTBacVrBVWZJYLJ0R8K77uBTNAANMQzu/3Am0bQGIhmNHSZcELVCyZat//tExP6ACnB9IaelB4j/D2Qw9hkoIDHIWg1deDh6UdAmxkn+3zNR2NoVIEh4d3d/+AAAGflkAWQYpKezEVloVD+HamKipKyO25onq6ubSgy0JfIycQVXQAmiIl4hsYiMRcAzxpL6IbwY3WDAPMqo00xwE7djnLMtNbWUUvCPQ3zahKFHXgAXhod2j/gAABsJBRwRaaWD2oE68hf+kSag9iE9vc7lnCVJ//skxP4ARqxzKaec0KjDDqa89hjE1RWK1mH852iyS4ATTDuzxAIwxQcHLDqUSt69Iql6DN1mCyOnTTcgQ1NFGNwdSk/p4poyugAXl3d3ffgAADEsCIhiS0sKQuerAi/HRSC+zJ7RlGZnpp2NGzls5oOISxNAW77b//skxPwARhR3K6eYayC8DOZ9gw1s62gXVUhI6Z4kFPQzzANkgQYAVuPM6flxhaGHAOCqU5PPooNdpLffAAAAiQaoKc+RjhUCHFYfYEwIBo78lCuR10OV6QHPAnjvfSzE/iK2dEJOPQeDddJJIqxpTFBkWq4CERKS//sUxP2AReBnM+wkami2i2Z9gI1FSHWIQIW8s2Wl1I+0SCxYosflXzdfwcUBMLg2ERR/XTB3h3d2begAABsiDrZkISsiwSzY5wLQAPcxSSsP5+Y/aBV203reefPc+Uk8//skxPSARbxTMewMyuitjGZ9kw1FY3/su+2AEWANQ5AuQRJvHMmzLcit4wBqksIXRbDKRVKCOUjIJA+M1KqDa2y3WUAAABVBAQMhYTkIMzpI9EJYVSNrVPZZReBsKQlQbXbwlFZoicEsskdkYENDRy7ia6AyPBFA//skxPkAxahjM+y8Zmi2jCZ5hI0sJrRDQkoYmOkQs4Hg4sEwluEpnCCGZtHL6K6AABtLyCoA5isPY1VUtt4cle5ZmxtrDgWXMwuWh/uUXVyo3KkVY6TGLQsQ8EQ5rDKxEinpY1WoCShhMyThZd9yTEFNRTMuMTAw//sUxP0AxaRdM+wYaaini+Z5hg0NqqqqqqYhGIAAIAk6lNMSrMaK9SipiFYCB02F3YYNdcQhW6iWWQCB1cNQVMEZMKs3ijmagskd175SLJX871ZMQU1FMy4xMDCqqqor//sUxPcARWxbM+wYSWiVhuX1h5iMaTuAg6HUeB9MxCFWBmQQnLi6fcYtI+iL1K8zf6ffWfSQKwQcYhRTjiHcblCATtLIbCHxKs21WkxyhnDOjdVMQU1FMy4xMDBVFkiS//skxPQARiRbK6eN6ui6C6U1h6CUZdQABFNE5A9ADjMeRYbLEFVmVd3S/jVGDKqMtd/Kj/43AQiUmQKAEE1Q0ge5L3BPlWdUm+bUGB/HxMTN//VMQU1FMy4xMLlRhkAAIkIylzU81xv2U0El31yVzDIjKDCfxwwe//skxPWARYBfMew8xGCgi+X08I1Ut7HH4qaZCVfKE/RLGi9Wc0LIanuFionSKW641OZrDOKUIxItU9RMQU1FMy4xMDCqqqqqqqpZVEMA0oTPRhXJQUtiBdEbxLTUDEx6xvcHTEUabvvRmXkidLVMgWBDexYHEC1B//sUxPyARSRbK6eYZmifCuT1hIyUR0FiB5FaE0q0qW00r2pMQU1FqlECUm00AANTsf4t7torY2Ig1c0cVQIFJY1270ic3tt/vWhyiITbbvC1xrodR2bHPxiRylDmC0TE//sUxPmARFRXHyeMySCAByOhh4xUYqLFFQvb/ZRIszMSrYtMQU1FMaCabVQAB6hpixgyyy3e7FDJW6pJChykmaPkEvD+njYg27LaBATc7BvTA60y22p7eUUFCqLhm4px//sUxPcAQ7A9GyeESsBxAuPkJ6QNgYQcAFBC9Oh0IzlYc5ZMQU1FqmVWQmAAKqkrzQIix6JE7YyHNP9GS6fxwTdjIhmWOGpAhp4Y6Qo0mg1UmYrqEBbBx0dPCRhGEaLs//sUxPmAxAQ1HQU8wKh6BSNg9gxNIWuWdRHhnK2rBDq36dHiMqqgABgRjQk9oHKZ5Zc1skURSRNg2jtKxdZNUi6UOBmWvf7P/////1uOANKRuDtYXwBKLiYYa9CxqETK//sUxPqARGQ3IYiwYqh2gePxB4QNw6bz4wJ3yhX+5n3J15JvrVKdv6aGtGVUm8BUDmjTBQP49s8w1exoQ54Rw4ZkuCVUldyHFWR7/raseomhCmm6ovTaG0V6AqHWyG10//sUxPuAQ/AnGywkZIiNiuOk8wzsjhNFn0icqtUHVcfPoGRrVu193IPS41WBZKQAGwfDwwEZxE9AJGFW66NJonFDYeRm2DKe7yb3vvzSkRB4EaYJiELJjUC66fvukZri//sUxPgAQ7AtGQewxAB3BeOg9IxN4SgpNjKCgUnWdpOMLOdBBnLZRkPEqs31KoEQ84qATbXstpW/T364ABONDZVGViEL3ssMtrFBkZbXk5dPWVFVs1+ObkCBWyEWRH5e//sUxP0ARFQzH4eZBWiNjCQw8wxtFjlysNpNpqGE2BNQbC+y5RlGoKoqXMuoDposlBn1dKkMs/CMBBSVfuN7Wy5XimuKLZQAFFDpbEwOEhca8muqgMWpRvmJScWYvOnK//sUxP2ARFxDIYekQ+iPjOQw8A0NKvpvit72doXdDdUJgahwoEBxX1KT4zFADTkDSuwm2knKXo10ABQoa+tpHXV4k6igACG7oDHUPIT1L/9aTQRmzgI2WrlnLul+fYSj//sUxP0ARIBXGyeYo4CHiuQwwwykAIPkukk/5dy1C40BgywDgEE/VVuqjdQfplRM5/68k1r8YrPat6BVSiFA3Lr+RppkABKXhaGpwIp9WVeZBbkg8LHVB621TLCEQVx1//sUxP+ARTRbHSYYasClC2QwwKTNpCHsMoWx00kmXqmgqjACW1IWGciUziFAopIA0krxpOup1VZoLgoZW0UoHf/j1a0GmGAAHiqTDoaQhfXl+nu4LCsxKWTR1ZqllIyJ//sUxPuARIx9HQSYRyiaCyQwkyElMFlIAUROJ8akCmYknQs2gB2Xhy9riTwxGCpOFhFapaKz/zTRyFDZMkv0Kn/miYQAM7FkOQaEIsLCMwtkqpDSWOabogiaQbddTBQg//sUxPuARihdGSekw8CZCyOgwyBMPdvqcaoUFiYGAaFsEortiSSDEGfNkI7kUkjKTdOGjufn3ikgpAuIhXkaTEFNRTMuMTClUWjgABCWnIPs41pUcn8MSMhQq0FFYcZe//skxPUARUx5ISYkY+CsCyQw9Iyt4EEQFRAgM2OdG1xZ9dQQNwasOcxHtNamRWPVPPyOV2iZ56rW8tVMQU1FMy4xMDBqRqmAABzyAUEBIW6bvuy2FFhwaQA3ey9CACmXwexAPk/9UUQTKZodjN0gNXAu6GDY7bLo//sUxPuAxKRPHySYZ6iNCyPg9Ih8hyFp3urMHX88QUEFLWpMQU1FMy4xMDCqqkWClQDqgamATR4PDlN+3uQ0yk2sdSJ1gIUEGyBoEP/+kqKyymdEHUR6SvE7dQ2WO2O2//sUxPyARIhVHSYgbqiZiyPkkKUMFp5UH74hAxRIpt45YQpMQU1FMy4xMDA/au2gACmIz4hJwiCU6xRVeb2olhJd6nKmRC+TlsjQp2Pqt6VPGtYMxaWFzA14bhDgCCvd//sUxPyAROBZHyYNBuCUiyOkkw0lxUUG2R/IpJhxIN9VUlVMQU1FFmBqoAA6JMiiDYlUKbITyhmHaQaM6pKcTFI4BEFpWF8WfTMsiCqwKhxo7WAgQKQQKrQ0bgQSIoWG//sUxPuARKRXHSYYpyCICyPwkaHcAqHA2K7RZYIEAguhf6lMQU1FVRlpWaAAMdF7qMQxWaoGhE9bVJrp2uq5TMQ0flM9iTDCw7UsM3/6VCsToTR8Qlo6A6cQeRMT6sDq//sUxP0ARJBbHyekQ6CUDCMkwwzoHfdqT05n8IyehmLf9apMQU1Fqq+pqjAAIafVZ/rgkIDhzYfgCypXISGENQbrqHLkH6mF1rWH1hWJqCFGjOLgZ1I4eeXRggJIE9lt//sUxPmARGxfHSYYYuhtBSQkIww1LTNbR3gowWAxq4M373VMQU1FVlJZoAAjZsRYDIKo4PUa84IyAiDEtuo1nWx+dq9B3BRj/afxnSqrAtUNDbLgKMFbtYiKcaWDo8pA//sUxPsAREBPHSMkbGh9iuQw8wjd2SXiUN16p2UDQUAH+tVMQU0QqAuOXAAFRAcHY4XPE6JERIURgHMJFpVbFpSF7Hj6QUYbEqUpFMhabYTpBjJsT49vadHHSAyMqOJ0//sUxPoARAQ/GwMkZyh9iuOkwYj0qkQv8ERNFxnifSBSDXJMQU1FqqqqmlsmkAAVAIqukKhPCWWzqiyYIt2q4ohXY1zDOkAucGcBddVqli5kH0iIIHwIw0BXqA57LBjA//sUxPsAxEQ3HyC9IGh8CuPgFgwVi6LESkpGRZ34ww23cqrrYSZgAB6YsEwlMhYgKbGLSSt3iqvIZCwKz9zUU0eqJzaBk4ochcX/2////V9Y+1MB6hORkDKzAjhD/dmJ//sUxP2ARGRBGySBKgiOhmMklgwYyBqS/MAWkrpYDBExcgtUtb8Wmb37VoQRoAAO2ki9okAiF4POjFaSOV4sm/D1jhbk5QzbZ7AoEJ3h579aiwK0Ax1IqMmBsAySI6pU//sUxP0ARLxTGyYkZwh9CuOkxA0Y30FFpFnkApUUa7JRyFEfpUxBTUUzLjEwMFVmkVsATICo+XYBYZJD4BPcCJkdUGusw5GR7ftH9++RpoHR5OApIZYWiSF7zT0k7Nah//sUxP0ARGg7HSewZECIhqNkwxiZClXOQEuTjFKA+NFFzcVMQU1FMy4xMDBVVVVVVVVVVVVVWpQUgAAa4zSLTsCbRZxi1IeNNXr5dQ6XsRJNgJfnOKXOA2H2knNJRKmr//sUxP2ARHhVGySgToiKCaOklhiAftPwNaAjFU797iFyAOpMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqoaURYABxEwUA2BoQMsCUOuYRPZJCOmCGOa+DK3AikWoAiIDRIV//sUxP4ARMRZIYSEyGCGCyQw8wzcCdiPOO8OXPMUzDffpppMQU1FMy4xMDCqqqqqqqqqqqr/im6wACBOoIywZBdVW08DRhpvaBDC7iCo/m69cRirSypPIcSUJUGhG0f7//sUxPwARGBZHSSkYaiBDCPkEwwUCQz6HZwQ6iEndwv/P1xMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqlghWAIgb1EXVEj0JR+tMxwmQRQeNNJMaq0yClhEeo+wZ//sUxP+ARYxjGyeYZ8CWCyPkkI4NoHWnb/DBR3p4qnOcm3VMQU1FMy4xMDBVVVVVVVVVVVVVVVVVpYFWAGwQLyGy+bOICzrTOwigetwLyTTApcoZIBEXBUPCcOMGbVId//sUxPwARNRZGSYkZwB7hWNgZJgV1NtE8pbtrMeE2DlpWqtMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVV3VSgAkofo47RgkAQNZaqs0o4gWsDHGWYWhAWQ4+oT+SIwU5QY//sUxPmAQ5g3HQSEaOiHB+OkwI1NBTrqCaCpMFke4oo+2lVMQU1llQagADLIfQ0BpgWRkjJ2Cmxmknwp/rPVI1WGESH1oGoV/eXUhzIF+ADAQUAXg90qKLctZhKNw/wq//sUxPYAQ7RXGyYEaqhnBmPkwI1NAgCTVcY9OCxSJyjBnxUgxNFs3AAAhCTf4E3+s0ocODMwaE023FWBrPdAI32Dg8lECCn+wzsQi2msxG0ykAuhH/////ShdZo5KowC//sUxPOAQ2QlGwGkYOhdhiQwl4xFAByiedocBMAoBsxmNKh6yWwncHAQ6tZSEmH2l2NpDMsx7teJ0FFAri0YfeZGQTZFfAMIe///6X71FyAAGHVXdo0+YQAGAhlBQ5aI//sUxPaAQ9w7ISSEaOhoheOgcwwduqusWBSUgNOFUSQ6ikhIBstGTELGBY2mekHz7lVrlBn+4DYaRXeL7Dq8kB4q//9VutFxnFgAoQkZmXL2rQCVS4RjMoYKV0ToUiVC//sUxPGAQtQdGwSFJmhfAmPkgKRF87DPmm3mhSvBP0ysLine/BQPLjTpPf0CbC4eVxQjW/yUJWIF6gAJQziGSrigoALQHCgMoXkm85rRBk7T00WOSd6qK8mY7nNLB3VS//sUxPSAQsQpHQYASiB7iONgkRkkV0qvT6NCRR2H/9WwaLvGuM/mAZMs///vaWWBw+FwAjFaWISISXObPAwAAAAADVKBUI/wC0BCycorAyg4s0vUmjNEk0Xy7IZE0Ioj//sUxPOAwwgbHQekwmhqBKMg8IzFFgIhRMCXSQ4B6kmQY6k1KQ8CUHXlpPhsgKZHAvBZ76/5TRPnmtAdWR+HP//rCBI/+t2ejtpDAAAAAAMW0DxZPlBBo2Io3nkDEh0A//sUxP4ARGxPGyekY0CRiiOk9gyVNHzPjTJrDENiJQgagIBTw1I4DMXEHRQQ3BwkG4MbEXiSwdhoLqy1AXaXyqjLWpV2MMipW4dx78pkPP8/KaHjrn/+PP/////e6x3///skxP+ABsRbHY3owQEHC+T1rKRk9XtP4LPf/k3GnW//qExwpIEIyqquzMklIAAAAAABko6GxgiBqSZJpxwkrHNWUHbgwWViQAmvyubVJRQDjWaVIjUCqeEGc1gbCYZCsAkHCwwiQgkGRiGkyBggANg8JkAM1AEF//tExPUASJhlM+w9KKDqEWZ9lJXdw0YBj+AE2AwCMLdANEBDwMEWAxwsDMnAFxgGUCkJxSxcrg2+LYZt1W6/pK/+/7f+d+XDxmTldZkWSAof+XGoFwib6ZFkmJoySW1av/0y4YAnUGZ19qAVASAQlIiqhmQ1t81DCaCAAKAI8OBJcwwoqjAYAAxVB0GCTMCzNqCIMdZumMccOEABhKYwSITBgYLKALzD//tExP6ACHBbNfWEgCFqDac/MvBACgQNEeCgQ1EYggKF1RESPAyXGqOSOQHqBhISUSkBAI5IqaHDbzDgikOw961dkiML7VInDb/q//+kpW1ZMHS99dH/yyfUXTctmct/7wAAACREliIwBO7K0gCAAAAckDoJoSxnzhEVBWM3QcxQQwn0zwIy8YeJmIANwNa5OIFFQZcEG1AxIBjTQGRVCAIWIniBijFA//t0xPkADtyTL7msAAKwqaW/OUAAZ0BQATpoF/jAOnHsgQd4nxbxoCgRNwX0G9hQCOlsWwai+gkXyJoSOHCQEWU+6jzZot+tJTrR/26DI/KJFTb7rWvy4aNumo/RMTXf4IOQq8nQPBVNAABTcqJQLY9sZJBIAAIDJjQxgRAkZElA1ZBQQzIE0U1Jk1KAyYkEgDLCDMFzcBwoAEjADegLQAcUPgDEBESbI0G5ZXKYbaVyZFLCAZgRorcO8QIV4BggWkhYuKjxQR/gKpE5poZuXybIO0xJ4zNsyMS4XE5gp0GVUzfez9VF0x4+p0q+kibE+T7Tc0M3SRpUnpd0U7fy+R1Cyv3suwq8EMBMUNJMCcAN9zcjFwKAABTxAvMUcMmL//uExO0AEQERPfmpgAJqoua/NUAACwsMzmypBDolIwIJLwxYZ1UaQmh0EhxghACQAaBOAMZAwYgGxgA4mWCLD5AwQJahCYMYDJBY6BECA0LDQExZpPiji4BXAMOHIAlg28bNi2J/KApIc001oUakjchhypklpI/2WiktF2Z6yYIOQL6mVdCtIvk2WC+yCaSKtDr+Rg7CJk2blQ4TjoVJtmM7/3fLKgAAAAyHnANTJU4QiCADGgEbQMhBRgxIsmUkEIumi+goZNmBlKqwsfZ0sULCDFlwCgQX9DmkVAOOiXEQIqAQjJ8WYGBBHYjoDFFgHDwBgwWmiuCORWgYPD8xB4GOJjwW6hKQ0zZofAPXqRQS5ufZVRRFeHYUa1oo11FxCgmxfHybERNSNZdSzUmRrf1HqLzQc8SkGXh7NDJakl6jJ2u7vHNTemmaHzJ1GJda//uExPkAE9kzN7mpgAKhp2h/NUIA60lGTMqgg3/RWfNb0//////0mAQODELBsWy93FwFgADgJlBnBRhRBuyhoVxKCkREgBxMxdEsCKQQg04l1gEAZF0ApBE/Bb+JTAzgIPWPGQgsBIGAEEBsYEFiUAqPPBjQfQoIUsFzYxgBh0c0LDTXha2ffAzJ4L3HvosqpMZQaF3KJfNEmRQQVWtyDlAnDA8pRiamtm+YqZBqjI0JNSLUlHTdT2/QTJs3Vy4aFU2Jo2NmTQYvf/2//OukXkWpEy0gNQMwhAOiUwLxZ6rANBgAwQVUQrFCx4GkAMQCoIEjTcNgy0Z47NxUGgFmGjLmDDmQZgYIKGJgMinA1IEEzQEh4noCQcBKADFDgJBgMEIJIUkAKMFgKYmQjMLCAMMAFiNxwAAA1muAQBD1S2yg24rP6Bmg9lqHYXalooqq//uUxPKAF4VrN7mqAAKzLqg3NUAIdA0sXlE6JkI0NjRFI6QEgtv+aJqrSN/WiyzN/8fZeLib1mSR9lJKt//9lG5cLhTSNzBc5///6jIAADTAAFAcPFgTBAIAB8KB1gBWfFVZegCkx+ep8xKhUwZsfkz6UzJBmRiwheUMDgc8qqBZo0RUThqZPgFSEgpdVcqMpgSgIp0hbMWHFxUXiWAUBDCQukvExhS8DectAoh///xCiDmu55f3etW/tYt2n+7y/f67uX0+tc5rLXf33Ck73+d5nnOVsolh/55atYf//+v3firj28bVznKe448GS7uV+h7j9zW/5//yfa5DlJMSi9KH8nKTn8xpccu1cqtL/ggXR//VtQEwAymQBANQENLI0kQQAAAQZGmRpRRKAG6JpFZgCbBRvEg4ZOkYIClqFQodDOSAM5LOMMMQ4zChGEcYZMYbz4sQpu18ZWOKNHkDZKUsyjTNlsFwTJmA00ZQIKjUoAT9NY8FZrmzy6tCQQjl//uUxPOAFn1bQfmqAgMfq2b3NZIAfeFRpE7Y3jci1bLv8nccfl8Vn7+7feZV7O+aw5+G/13DVJjjhv/y3l9z+59sc+o6b/yzG/hzPDlth3Mt/lr9Xpbhhz9/+/t1Pq0//hzv/luzz6vzsH8PE0J68ICAQDDSxwgkkAAJeaIoKFDAqjtI06AdpTlNmtCABz0xCMFQ4tCKwo0FAoURAkJRgDL4NFhyCAFHMSHSIBzBiFg8F1SzDQVMwu6URv6CBzKAiSNC6Q4yH//zUJGhovQZL3lnP+/qPNBheXeaj2s/+bZXL7laP01LOX9flhVx/+V7sjsZWf/eHPu3P////3zDfd5517TTIxV33D/s1oez1/P/8qmUYsfhrncJ+mq+KgFnyXggACAyEIlyAAIAIEhrY4i0UADRhDGgCYK8JhWIsLD1Cm5jBbbkQJ3i8JhyUUJWJjBZYMjAAARmgW4IUMXDLk+AwFDC4pIT+FwAX4C0QXCKOAUhFmCiC4xyxRA+MEAQ//uUxOsAGEVVNfmsgALfpqc3NZAAg7LiiF68LqxsULsYjsNkXrKR5WgYGaTI5qjpuvorPmic01o06f9djItE6ZGhMl0UC61pPkykqp1ePgmXWmYpIyCGtT9Z5/8uEnYwFEmKp42NZMDKdbe2yRqABeRUBgLKZoWRCyUSJEHLMMDVqHhVkxhMwCUBF1DDVrzh3iKAkREagYYOQUBxIOUFnBREBlQIKBgmuImCEEBgQpsH7BbIlAuiHlGRC24CBAGDCEsp4CgwTFFR4PbIStt07dBdpwzUjUtTqU6nMndfUmtlVJW9boGCDry8iiYLKRsrWzXTSXp7ydIcRZNzIrZsExRZYyIABPmUBBSQBwEnMQegrgmhvDxCtHoKFvO/zIolkiDxcA9TZcrljx1E59NTsSE0imQ+EOTpb/+7///JCpsSL6u4mPmNjLq0nHq7qf//+J4+vbP8RMPThtLjcwprqXAUQPcscLAALxAAAe0AhMkJAOBUoiaCIuZC1aYuqjBo//uUxOOAFNk/PfmqAAJ8pah/NUAA/FsFSoWR5KlppGI508wyE46G51Edwob5IVj+ZDqm8DdvzGWqPxxQZ6Bmu7dUMtQwGcxU7f/tuaaqLRFzhrhRgkrv3usx9u+ifXpmAQerIAA+pADPA8pfJPdQVZ4gZZXDKog6yIU5dU4o08xqXWFsp9MtmxPoFziXeb7xxNbaLm+Aav4dfZchw8HQ6as+i97XRTMQ1Wlf/+vW/uqlccLqUwmJLrECSKc1QCV/5ABpLkpDYLcD5ArBkBWi9HxChHrM4wnr1shNxvmVLtnAaI+WptYmvkbkoe//9CCRQwxL9//0ZvUt9vr1ltT0ZVGcjOqAQlV4VSk/7MAAr6IAsorGzNCam+7idS/F2snYNIgdBU+JQLBoRlBxRc9JKkzunzU0/+T/BrfQr//1UECgZbLX/+v9///9qZ1KAsKQqigM4vWQAaUpmQAX0NgNbB4zLkXkUGHJ1v9FEWktmV4wXA12xHQICMCGubAyWqp7//tkxPYADPUBQfz1gCGQoGb1hgl1Eh4GhnPCp0vJ5uO9I411SUJmBJPWcP1KDC8dZNTeoWHJ/////////65//6mK++afd1vlV6YlCcBf/+5CBAKcYBABIsoJAAAAAAMYwCrg2QM2RU5J49PYSEJZhDwmDj3BqqnwYXKEYKZjw0WkAKAhGYBo8XCAZAAy4gxFOCykZgSoXQpYO8AxNJ8RUAYQViuAAEHkL0AZcMANJD0SkITGwssLMFsowNYMC+pmXj1N0dZ0uGjaBoTaPq/ofLJ79lN1pmC6etBWuZUfsmfQUxfL5ugXEbm9Zq6ieV8y//tUxP2ACxEJOaw8q6FAoSh88wpVV80s5ogaEHN36WpFI2CrcBQNwiXEyY0VS8tqaAACAAQhTrMPZRPCqYzFcMIQs4RwAhgU5eQOCIHCTyDRYEcFEIgUwMiDD9gM9dDGpoGDBSxFRzQbBYUEA1GAceQaCbgICw+wX/AEDFQMGgYBqFphWKTOBYAS68DgLQcAIAnqWk/WXmetZEUT3W33b62///1o//6loqsX1K3mKg63/mvhNVUAQLyMuqWO2poE//tUxP6ACYUJP6wkS6GaICd+srAEAAAAADYArE3xQTyYgxEmY4rMwO87RGVOGGeDUwKEBIIZFlwDm4ChYDGRgsrBFaACGB7oGIAAYI+FhoDwQDDEioQgAW1B9xjQMEVBtIIEoGFVHgxIBhEoFgQqLKgaQsI/HJSgYQiKIXFa3Nj6E6bF8wXXZktm7Zdat/9d3uqicMHpel7OZ1vrMlzzoqe9pk9zfyxIKnbTOBz///8GTAGAKRTNHQmItd0KAgGA//uExPqAFdlvK7mqAApBpGe/NUAIACYEMWOcIxuDajQUFoWMiX8eDunAJIDSKXUaNgYAVQQIgRQYHCthAFAx8QDAABvAJLgYUKFroGCKgZg4RYZ4AIaFvYNAgAgYg4N0gAo6ghDg2JDVCK2gDRRmSZXABAmDvoFwuTaqXn/vUs3+kl9Tft9T9f+ydBlIMgzKU6CSSkkrbf//qrLsJ+0wUgRygwFFYUh35aBoBAgAGl1MhmMZUubA8XBM8EiZzArgmZJs0ZCYpFAxixACLhUKCAgDBgBCEmhikXGEGfA2QM6BgQAGbaiLABAwEgiyRofGXAFhAKVCKB+gGBFBz0FYDCIR2zOCJGLen1LL5FDlFZMnmrm5PmiaqD1qbfXp/Wg7etFtf+pay+q9aV5dB0MNsC0wVBj1Qo8XqRd///2JNh96JzXLz7pUGAQAAGKCIDSj//uExPgAFMkhMbmaAAJeKeg/M0BJkHaiahmoAKKVIWVTidQNWYIGnyL9uqYAYGQBBe4BIEXQBgwCRQvERAsHDJRzAQvAGBAYiAl0EoiUgCiKxSIBpIBpiAMjACdhQGZcDBEBC5aSTB10LmyXbyNLxj0F1VupNFS0Wr/pqSZDas5el7/U3N0zxwZ0vJGNaKKDmSf0HlxDoN2//V/5cRcuGjACAwBgRhAQCBJzns7IQABAANuQR5AIUHFAG0IjEqpIJDOgCuIfVcY5j0jgsnLaABIRZotxeDBgyJkSgIgpdDRgUFjqDBwxCYEJQGgB4RQAUYQcLXwWXgiTi64KACC8BqQPTtUtRASdXukivdRUPLRpOpX9zRkTdBBVXr/+gp1o01kea3qV2/tK5om7KRSUkTSaJksNf4NCAMA+EQsIibxIgQA7/RMNVSvXsmpJgcER//uExPaAE+0NPfmqAgJ9Leh3M0BJDi4Ykuk1J22hQVP360ABWRiEWiP+DBIyn+jiJJBBH1Y1BBcedz/z/s3vp8rU5sttzrm31EMuKjOMpvEvhl11Mtb93DL5/jf032S9bHbM1///w99sVfFsWlImliQXsAQBfUiQKhpppeSxV4+MnNF1HYPbeGXDjGFDm1gTM0JU3T0mVJMTM2QXTHYxWfEoGBGKJ2CvCNm71ThoMOWOgmxJyUJo5DxucYvmL9l1/retN/oL+kghTd0V/1ugefekyjNFVvd9dN7bLRdCp1GkSOCEcLNyiG0ujNrLJtpIGwAiauVFQAPFkigEeLkYmkGNGAPZVtKq5gChZRMlvEVsV2QlYWdrLxgC0tcrtf0NMjLfLabzb9RhoEMp18qyOMS7tZOhe899dL6CH0dyB68vsOMrGRCYjSW467MFxWW3//t0xPSAE2U9Q/maEEG2p2g/sLAF5RIM6/e7jVDT0VrDC9u5hQT+X/+PMPr/U3e7u33v913C7h//////9yN2csd85y/luppSahdoypzIrJbVlw4E5GqzIEizpmBBaZBKHFmKCAl17Ga4EFCQtKk2DrV1g1SHm4GaC26arVCR4iEX29hiZ4Q4v9/BgA2FFzqUCo652rzUHTzXMqR4bYsvjqQMQW9J6amZPL0TEBi7mmSiCnCXiymall9/oszJz5O4yQEbU3hTrsEhyMSiHoZrSOXNej1i1KbOdiVZRiYpLE1D0FxW3Ldbxu01SXzdntN3Cfucor9ixx3b7rwRql5uH5ZZoHclWNjG3hTgmHwwjKyCOFQyHlJyNve+XxcwAEXS//t0xPWADk1DO7WWgCqDpCg/M4AA1p1ycgKvIXlSJb1Q1L/KRSmHmJs5lMviQ+mxLCI7Dy/w5IRwcKkukD83yeOM/5Pqaq5mWRpqvNA9FAO1iCIU/ZvRIY6Ifb5e99xPPM35xWZb5W9pe/k+cujSnHJXjQLTA0RemciLehPT0YqHVqZpFnOtsxV0+4p70mXz60mTplLatq7v+3yKwAQXCgCdCxYhCyEDCEdBG0aoGdIppQvGxTwnKExRW+H1TEiomouxS/ku2T/m0g/OaqkXgP3MB1gGxFRtffPVOxwytqq6mcnoqrln6M9eJHDwfJt5/8b+UDR33IWt31VIFp9bua3v+H6agAAVG6BYhet3VqIULbT/T5Y/BdiCoPlJRxgJ//uUxPEAGaktR/mckAIpK6l/sLAApEIGuJYqWOAyf+5b93LOn//yRsGohqZecZ08HVWlUyI+c+57yZc142VJrmcyU1bubPCoII8YKCXY779/Kg2cN31//y6Hcrabz/yKnIgABQ6wCUVTPABvhVknBHGswmL3h4iBLCIsQPbmvW5QmBRFVK+MzsbEb+0xaplZNRPXzLoEYzSnOTS7TjUz1u+X9bfv7u73jpb4nM3Gdm9dpZpKHP/NLylRwEGgWwNbkr0IWGT7kevLuf/svq4AAADGYiBYCsrCMDGFKKU47xSjvJs019rI5IJAvaob1ej9bgLhEFSqNw543/yoJ18qrTytbMMH02kK55sUJj8VyAwmQI8TrYSmynbdN+MIzjCHvNtRFPsIFEksTWxhuNPdYfBJ5wPyag/ETnRFBRDr2jIMVg2Z/O/pk7CDt9/7/9q8rP78nLzIAAcJCApgsR/EFFtA/C4ieGspOoNYYHyZkViOLAcjx81QFWtqlBnm9hZm//tUxPqADSD3UeegU4mbH2o9gw25qu+IFj/3a3MygNZ0hNSCGm8YXuzKpe9lqLcq3Q5GHJ/rTHc977KiQskPf1CrbnBHnPooY8J//oqlH8+wq6+t/qio6AAALdgGhB74BhtHxDu/sFzkPxCWc1rUkrTMYitep3KrK6SIs0isM0VyWb/sbnL/yvzNTJCyAyh3T6QhgRmgoZWInrM10+6uPbHr/5NczXbe0PJpTz7OmXWlMOuDZ50y9VhegRQYIAns//t0xOgADaEJT+eky0IaIWn9h6T9EzNxdkVACUQo5dXJ3f/8i4zAABcegA5IpMqZYTDRoX89TeRuhkc1lXqwAzAUmzVXd50lh6oShX9KxYh//7hJxzCVeUovLWUMJ5KtjVtMeOyErRpmdYv4/3XnDzWJ2H0dCRKHSN5zVEqSIib4t+/WYf+4vcf2b/0zWT2/EXWIAABUeEDS5A9keAmIqliSoiWzoonyl1RdG4plM/US7jPUysvxZi46y6zr+GshL/fMKEEGpKCcKoeNEI0aINDDkcUuaLXK0k2bmoPQtvf3mI1R4eMmZm+BhtLdEDMUZiaps5L/GmWTgUCapZDbLXZSpbj73th4OUAAAouwMkRkWsBbAXRpx7obFjWgrHsu//tkxPOADbDVT+eYVsnioOm9hJrYwumw0ylvv9Q+hkt8QSSdI+AOH//TtlgqDpMTISzQZeqiHk2T7g/My+bcFu9di4UxgZd1JVM6aA1qvB0ydZMyMKHMTuw2Ykjf+cKJgwgP+Vs16/re/OqaKsAEl4F2PUeYCQBqClCYI8XZov1iuMVS7Gr8Cpq1/sC0IhpvEep1BC//4wWHiyOVecHNDEFUSLvgzzpp1DJX520r8PptyVS25GvSMgwogwRCM0GWPIuCQ9z3XacCAUUFYUUbiqr7/f7pegMYJRnCgI04ledapb4eNWGdx316girPXDZY//tkxO2ADYzxUewkb8nYoul9h6D4cjobo5o6n/wCX/2YGQgSBH73QV45fYGErDJTmFePnewjneUrmRUqSlav5ld550Gdk2VxFNknvtY2h4u32s/++x7A7iH59nMzsh7TsgAAALIDtNgNEMOGNTbDvFAKDBMAUltkzOLFIl40REmfiko91JJ/8xjQnzP+YBYQJb/38/D5KqneVRMn6pA5zep9r0ntcvTaPdU42P23IbPryZuzZnBXKkZLRRyG4XVzIlgJejocxvXv/lV0VauDOE6AAAALyHPICxsSLnNXHbqmXNu1M522hv5FFg1plgDD//tkxOmADeElS+ekb8Gknum89A4o5Ugld6vMnC4uEEGBYfpH3H47gTLa/JmZnrOs1MDqCNnoqLVqNWVlsMTAhO+erNbyDCB6TMOSCUsjpaHOYl2jRqfPzl3bKkfknhfJJgZDKARI0FJLTZW0WS4XvsPrV43/GEDvGFYXsgPATuFlytWA6ANAqWG4iK+KhQMBlv0cbZusNmqTfxiZSCaggEJgx4DjldRFwXND2fP970jHKhx3400XBUMgg40RQkxlB12eh7xwxc9LdTBdOpQqzxR8WLv7kHEjPoVG5Y4UHB6OOvGMw7vJc5IPpoV1BMqE//tkxOqADIjrS+ywaMm/oSk9rZh1jH1jCJgesBLGluZij+Wbk6R0qoW+aMA7JZNLAuQjQHS0mTTLcCw1n5ylcLw8FptXP/q4qmBow5beDsZo/WnMnYdZDpmRXpdLvneSWbM62r9Kakm7sCv9+OIOLObNPh/xpAYthiE1aSBgWWOrADHtkSXiQlhgdIzxesrBXdQUBCCFtCzZmb0UGj+dNnF5LLwoRKs/81VVlc/E9FCUrR7d8FBVlCHc5nCzX/L/s/5kSLX3UTAttotQ997uhW8H5frsM2QQi1FoWHJIqBD96RpDpu4VQpf20xLDBl1T//t0xO2AUKkZP+0wz+nZIyg9h6E9QA/gIGSQG1iGf/uJY4JX+fnskJU4pL2fjBcIYmGdQXDfAgZpRQkm2NI7va1RTyPO/sfIVMtfJ+d0YmgMVquILM1Y/VaDlDDBHnXaTIBaGA2ZmMIlhorEFQ0bXVBhESBFY5e3FjsZjzSaFDYRRYP5P7kJhYWn9uHi0WT2HI/hVBW3T04zyVb2X26VxVjV14Rf//tO8+2kRgkisrM4tO0oJ4Xp/luKXe7v/1UUIHaCRljqTSglIIAqjIHGB4DNZwnFbgM4zsEcEQdyasZCBzPylODV1f3Y48gQeZv+0MerrjyBmNq0WWipmWVj/jKvUct/f3E9cwkVvNLxz9xsTAgSaDaT4cpKmJNNQbzC//tUxPUADHkJTewwa6mFHql9hg11UI6BEwSuvdcrmFQcAGcAcgzgbYpTYDWO5QjaXR7qiZIBYZYaMrK/+aBCUuq9XBC9VrP/6vS1bfxHNREEsdfHeDKJwitiabENl3//75Fl72o+1UUHDA3Mps8sylqcoZ0ZS/kjiu0OKlIxWWAlOKNMuCGDEYocyVWgHXFsMNFgQKv5lR0SAMqHi4lYkhW3/ZFVgEj5nAxA5Rbf3UpdTKGY7FNSxpykSzscZEJI//tkxOgADKklSewka6F4H6j9hI2tt7Xay169qWlQhuzCxhYZIGw8eJOwUn/mWIQTXEFKKpxOhJQwDHxOgmKSCVyyZIeFqkSyqz7YZRGnIEVsRRbr4PIC91crkZrK/X3jVYbuuu1LdFms13iqWbBECgbFYrgaUOfF/yL/pfoCudk+iUDhB9pI6/e/HskFoevQ5w9C6kMlanBnOrSaTB8BAUWEu6IiRHvSYVueRdL9SeGYAyrxCWxqZUSHl1DwiBB8sBneIDE/SIlMjSjsHdDEhVQRJxeZCVqsRuFqnH75/bK/IYCc+aTIEYott/l4S+B9//tkxPOADDz9SeexCOGWJGm89I2tv1/EYQWmEHGrN1uhTokmnMJia8XEUnK0SY2ztXZYaIysQkau1iJVjKgOCiBzqSiCItZvo4/Z3V3dUHAxyj1bVXsYzixXVTmVypmbV17sa9WsmnRxUYLl+n9NUQyjjf1VIwFqgDUafHXKGxDgxZLO0ekrQ5z9K1vg77ilovAJg2FZLJrSp01+ikmW13aQYkU2/lVXe9sQ0DYsdJTKxTA7IhTO6zs0yW+2vnRgY9AYkyPMwMcoKZCYZHlkHQrPstEQRJYUUOc21IG7F5xrLgo7KrojLpYJLW/VyeB2//tUxP0AC4j5R+wkSyGYJOi9hA38FESIoJrc7f/4uWQZck/cWS2xx/nBGmMjO6kZw8r1QJMdS9hjkNSJ629+vRgyzGMamDcKQSAgq1K39d4TwpjVoS83qlAQiYF3fPuRsBSolOUhwZ0hzDkXS70AMqYhTwxInKBoHEgfE2eIKBxubDsUxxZW/5eRmDJmIIWbo3sAWLak7Y1VcUGZTf+Hlfn9lLPyPDrkZhQRQ5nr9GBg82kS/+ksoHihECUMsfQi//tUxPEAC9CzS+wUcWlzpWj9hJVcQpnFMZS2jBmDO82Lkvexxv2CojsdplAuc36gvmAQ75/F87lEPqJA+YKvZEUg+RKCEM0YkH+5FU+H+0PpViJB9VuIBaKzwublNTEAiIJ3bOksoBbYN0WRaOv0vIiU86MyJcaeqNQG/WDxxkZMuhL0XRQOhEhLylzDkD/uPe5uVuu4kc+fon87IXOy5GS2HM+12f23+tvzfWfu260b03jYXkX6nXEGkgCtaC+A//tkxOiAC9D5RewsS2F7n2f9hIl12VEArNwsQ32crQEtKolB4WuGug+sRCN3nNab9mFzVl9wDlTQwePkW7KLW7nG1Rynf/3XEQkXXGSxp5VUOhltc+oYc0tFVXyw1GmLRoHrUX3P1Fyv/McWsz/6lOsqBAREWFJ0SEOBnqyCAAAAAEUAtUY0apUBIoMOm7PlAAAiGhCZgeTu8xaICAKzBnjHBRCPAlgWSTZOFYh5uWi2FDAcCHT7kOFjF4JQAxEDPVuUi8MkeZSJPADzC6gLADKhjFiGugbHiyZGLmpuNMkBWhdIOSSSt36l9Tl9B2M6//tUxPcACtzzPewYbWlmHqf9gw4d3Wr/5o6ZuZpGiC6af//pppIospi4Z////5X3dy4YMsxrTRL3US6uoFq67mbCkgAaTIZYKGHkRDBT10GCblQEYwSnyY4pNrCmFKQIhAAQQcXCBl8LUZwGZNo7S8RYW2Wrpl7ju6OaAoMAFg7LPG5SpMR5YPYqu9V5eB9l4tUbxgrzOE/i820idt5c8n8m+QrUcirzNJdy0oexWXxjjXJBLHYkEB2dYS57uU+N//tUxPQADHUVNewgz+FqIee+sIAFrtDFaWTwJL1fw5el7XocfubiUzKuP7n+rmfc8uUl7t7G/nUxs7+3u5Vm5XX1T6n5/K/LAwiAwX2GDKUUNIwfP0S33uh5EhNpObiH40KSISUd1z2zaBpzGmZTKwrvPA6dADyFgOIJ+idL9bObmDKnCeZGTm6KS001NXSWXTyJipNSn12UmicWk1U2MUDjKb9KkipI2NknSZ3+9S/eiq1utlqemyKSda0Z50ii//uUxOoAE61zO/mpkEsuJWf/NZAA6KKKLVX1VLdSklLOGTom5dPHB5EbNutV5eNlCQAoUeSCKIPc6MMgw4ZSDVNewKyywwh+b8OtekMiloN3ofNDGOLKqoPQgXah7VJMMnNm0y3NQ09Rd0y1cxzwMsNPDf8rJtK6hYTBjUvIkyNSyPheRdn8M7WBM2SiVVV6xw/X+elzMz7QVDACFNZnyM1SFBCkUjoiQr0EE2M5VsC8YEfh8bafTZPFBiJ6g3rQRS1FKahgwLpStrHZNMOEZ3OObHSpZn/lJtIcA5QMXGd+5TM1UKsuWspKa8h8/KT55HQpEfS5TqC4FD2zfsbdnqIp5SAJiSokQhbGCo0xBR9XyRWbcmTQOyGbXRHFhVgnvTAVPOqXtbRgwdgZTpkNBdSWxhYg6Luh2QzEIgkmXDtDqLFBXBUwQ1FruZYVmCXP+/nYsWglRao1o6szhrufvi9jRKkgNUaMRSguFKBxPQZKUCSqolCGpg6CUTCUXTBV//t0xOsAEEljS/2GgAHGq6j5hA48Aevc6/7UENFoZqMThVKK/t0vuoRF3WGbHSt46z+Dgox1/tu9S27y/t+3zeRxtfqPIUvdRcYcNV0f77fPBoDyRkpxulOQN3DgkxW0bGhJX9pKGQNaZ89r6130wk5QiC0rMoojRnstbFp2Wnl532feyWYrCpmLruX5l/X1LUSAOMkbWkmJPvRFMN9+Z8/LNRRV0Tfm4Pqne99aVS+SUyClJXVmo0imAoIbGyGg8AWzIRAFRkDhbi+C2EIX1tFJxsev3XeZbw4Ae5tQYcOLFiGL45EEXVbqJaNo++iCNpoEUBQk5Ga5CwRWe5PXO5z7payu5ivZipdqU1aZQgkNQL3l2ygC8NDzX+9stArc//tUxPaADEUjRewwasmDGKg9hI2NKmloUbWFqLMVeRXjQ4CZ8wUOQXuG+XOrxid2XK5RZYoMKR5f0OCQGAjAoIDA0qfVSkY2L9R0H1MXcX9PM9N0giGX7cLXC0zpct8rX6jUIABClDAVPsvdbzHaMTf4IZf+VTMBSWNFeT+RuiGjGgasuZ0BGpZraMUjD0VKndi2iYEsOA+25geWfn+E/uHD3T/7XTNLmaPBrk33VEWXWH0UX/f979TQEp34XT1M//tkxOqAC1ydO+ewaUl/IOa9gw3xhlW2nwu3YmBBat/uoyiRJm09Cyg4MIUAQPi4sDQkAwyETIl/q3Ae4ogMQ3S/gL4G0nCCDdYxzOJgv2Qnos4pC5ZzkQwcaHhWLFIOc/8l1zydCDMH06J33/zcEODGm9IqeDMM2ZFAQgKh/YYDBRkRx/tVjLYWEEjuxK019WpzmGOiafSk9ynO/+uKKAtoCLHrZKCsqejCUHlyjEwdOPIburfbKzHZAcFpZE6PA0z8ipdwi0bPua/97avR7DunIJD9XZIcSJ7Kc6XlFClf6WQpgyWOJtHt2Uzau6fd//tUxPqADH0lO+y8RaGtHCj9l6GdiCYkQDkK9UV0dshxg4XINRiO5C2OyKhbOQbNU7fSZgbTJCiV77KUH6BxBviEK0hwN5zGeOtgLqkELMjGEVKnoxqzRG6eKuI/g5p5JeGHARSO3sZqVOd7N6QFFIJcxVBOighSoS9V/+vRHZOt0cg8n9CerLBe/83soSl3AiJaUxII/44wDMA+gPoArDpAZgjB1hxHMfgirQX18SwCZQPmz4pdlLFr/V2RiI2P//tkxOgADNz/Q+w8aeGyISg88w6VIhixz7sp/H0I5F/+0qGMDUUrtptI10UzmCE7tVFFEM2mi0R3cMV2OxACWIUyDT9yMAlE2EoI6CzmZl6MS/iuWsrPhtuj7Q/Dj+RmIzzy0J4CxRSGuZr4BGotfTjOpsuXDmVDPmf//5GZcVCbq4Nc5LVU2C3NHPJVNwhRPv5pXlkDBaqVcgAhiENVC31skgdAEXD+hiS/4sJH6BEsmcX2X0zdpBA1NUtrCTXaRPQSmTQDO5k2XK2zeN5DhFjs9cmhhyej/6srXTDynqfxcmCqdrc+fsC19L5HsaFy//tkxOuADd01O6w8q+F0H2h88wodnIwFZqtYtUzt3/sAAUlGYh8+laAaMFxALrc1comotvwrRWdxndO6eoPtum/qwUmntjoUWsMFxQ4t3OcHUHmhEQgtahDIMfSTsRwMRE0UAAWpHn/k97SG88ufMocgjtF5EP7FMxB4YyQXflI2EPG5CUEaGHJpqFxRDFwoaVRi7FZlzjKhmba2cGSWuYGpDocIe6ZUEs7BFfsCcfwY7U1mmzLB8uY+xc1WF+APyvMhwkNPYZs0YrbqGUQChAs6Hns0bf3KUIECsUYrJM1cLnwoGCRZAu3c4pCgTo0a//tUxPMACwEFO+egTel0IKc9gw4tNtSDmJVHUbRvxIEEChImT7mLtwFRH94RHZklOtEgmIABCAgpgDQQNbmXBUKXAybOPOji8HZ3iuYYk8GK9zJi3jI8/1W88efWPesF+cxtn4rUWo02SpWp8M8I2kCEJ5GMUSC1E5UVpoRACEwho2uTFGFZ/wn8n7ua83wmtCa6Oy8Ay4oTJLIEDpJRUUW6b1KTICRG3BNdeCUWhZejA2I3ozZaCrD6mi8oZ/E3//tkxO4ADCB7M+wkcOleHOb9hA4UJdWGNquXRUaBLaoGBl2jW0t06CSjc3NXqv8sR3mSY6hrDN1utV9EcraxHqmRSmZ9Nq9viSuMt6n3+RCArYhaRfoUYQMJUiIwtOZz8iYCftJN1W1SpUpnz/upZ3P42Z/0sHjoNybEPOmtkuQCkTKmohltKUNICIIjJyiIj+ol2Ee3njFO6zEYEucmyQySJwCh2s0qOCkIEb0pCRCMslWn75WhQWujUnKqNoiCJD4q0oZrdf8+LGY4cbjf7TtVVK9mu+qBEAaQPEY7LxTbZN1RlNzKEROXqCIwfJnK//t0xP8AEjUnOew9LepKqWa1h6W8BAARFZQKkjaDCMTlv+tdx33d+lgaT1WokkpJQFzUu6bpEg8q1tfV2anDZ6DdRdTMUbD5Hpc9N+5na1fPn5PKoqvf27R+fm6//+u/juP4uZlzl3ktfcN/5qtnaYsufd/QAAFIdwAzQmVLcW0WQAAAD3OBdp0QGvQWjDMibqVBkU8TAQ2g2KVP+wVaSCQPRBaZGhvQHZAGoxOBDQMsjnh6YbWRAOGHPDmhfELJx8iQAFVLwsQckHYHSYkNEjByyLGo6RxCeiutZIGxxJIsDmlwlB4J4mzUXIQ8iJqdIERhElIlwuLSTfdxSAjQ+gkmeQQOlwuooUtFJ9akFs88ozPmruicpLZNH1VuLkIg//tkxPIADQ0jP+w8acmcIWd9hA35qq7LUZJNVS///M00+aNytQLT/eQ48rbMXiIAACADItjxujRJzMKzYrwVbWiXqBSeCDbgmbqbA71E4pGzDAgq+B4Rw8eJXY2qsRieo+stIWkUWpInwAyV9YCirYQUk0+AYHYjDFmAGtO7Idy+u5GVeo5T8vS82qz1z8JgT87UDVbdR04nJLWXdUv8sa/H9bva3jlveWUu1v+b/fcN47/////86aPyHH997jnq9euf/4/r7G////6Xl7v/+rWVRetAFsunI189lkQRlUNKBv2kVQOsX6BSi0UBwTG6//t0xPeADRD7PfWFgArrrmY/MzAABukWdaAgUkqH1HWpmHoQDSKBqWKlFZFGmolPbjennazGj4OhnqUFRWhAm3UqK+34bvSZ/6tIhomqZr/r04Y6ro6FKoy8X/q2qiBHoKg4azR1oDAGlB2kY0PUJpXAv0aD0f6egmgrYtE9GnZz+KbEW7bBd10xbvq19R5E7SxlECHxy5VGKj5mrRFDgXEh8x1Q10a6WKeis9aMZxg7WfqnSqEcyAQlbtMCpMRCo+tcbQDjCO5QZuapg4CkYokXTk88WlVBMXYlhIJyCuvOsPaGBQo6w+/RL0vX1qViJjb76J/HU/jBXoOsiKpP+fnzUqcIKesOgo1aN/2dJVQN0kJOKaowA5ioRa+1cbQn//uExOsAFeFBO7mskgGQoOe/sIAEhGAeUpZBTClwVEroKlF6C6SK0MUoWFWN6Ohfr6VUy5FUMR0pjFPMnDcd6mZUcgDrUkNxcy+IxEJo68N8GdtVcW/8B1ff/9INt/2vitv//v/43v///5+t63803j51fV84zvPr60hzQH+K21Eh0lZP0/8wy/AACo0lVkVQFYL6qgAAAAADACQOQ0ExQNA2rMpNBoE2XnayNINt+tSyPPo0WIO6NIFwLWOxKcRARw3AC/X5XkbmR53R5baPwkioqCkgZ6zIuwFib6vq2FHlvYivB14FjrObW/zqds/38dYa5rGQoq8j/8R8XJp/oYy//9FNMCaZmQAAF9Y0CpEM80oiqJZQQjB2Wvxch6B5B9rd2LquJAgQOm/82RB8AeghnjRUkLDUwnKnYm76+ml6p6qn54+O0g8CCGl1Ozzv//tUxP6AC7UFN+w8qelnn2Z9hg09//3/0//Zxvg4HwRAZT6Qq6A/tm3dgiUTUuACB/lssVBREAQOe3IKEiLLDzql5pdo+9rQ1BUBvKx3dZEIajNeePkhOLmdWy0oUs5m1rulZFK33/X+TSCw85y//uW5IyEa8yKn6BwACKqpICAn+kAkqPAshzxITyBY8FuxFEQhKnzpto0654rBYFGTp12zkJx8ahefozW1qzPVsqhMKlDxsz8qq6MOExfQ9G/V//tkxPgAD7kTNfWHgCnvkud/N4IIrtsrP9KGnGH9K+eYVHjC6Dc6rSwAtxMyQEB/xWBNqyDRBGFQmHEB7+N5SlK3aMSf7C9YHIL0Wx2Za6CBsowcIRp6naXgnBIFwaV8WNGyJz/iHLBuLC5m1ap+ADiJmDAyfoAQINHMBkGZoGvoGYlnqNERX28SsbZctYDteqKczC6c7myS4SdVb9+f9iZEmJf1f///o2gCw7u7AqfobqVNMbGRCJSeY/zqU7smQQfDmMIwITBghE4eftr84XpM5Bk1ak3mQI7FVQH9/4GlwAAA9Ijck2h1ThbdByUl//tkxOiATAzTOf2FgCE+Emd9hiT8SaMLRFtCkCcaEFqkMJ+/rQ8gTY+7y7gluheDBIeHcxangJ/gUCaQiIDko3jwlmIVgWJCZgyiEEUlC9qBNCqMHzlloPa0qQx96JbJTlFaADVmhzBGOAAAI+DgBhCMzAgVBBDDLfRSbNA+S6E9EuBcTyaZiQbE9I8WjTE8/GRQITQCM7DGmZvjGLEf/////rEAaIZSByOBAabwlUOGX4jqQVl5q8VvbCZleBKB+otTK2hgHwdyzznXH76cGPl85sJZtQAJiVEghr8AABsaVBclcZGCFgDQRlV1QpQ2//tExP4ACzz9O+ww6ekXjqe9hgz0XyXIxFyCBcas4QaHoxvXap/VJMrtb/lS1PZt62AAjwQADM8BuoMQAhYpYESs2UIvzNWkjXMHJk7gZncSHUO+40pf8+Oj9/tW6jXunnGsLBIwCTeUlSWWmEnzgAAAAAABQMEhzAxTLOGOAoCGGo0RIcRKBNpOFuU0hZo9xlWGiCgMINJ2CFVMzUFs3CamnAR7OW5C//s0xPeAR1RpN+wwxaDGCuZ9h5iN0gfCHqo6TY18/reP/GukABZdAAFR4AAAyJCjDDBxADzXIYILNE3XellPZ9rtBH38DWVp+bORRxkOlpW8O18xoqlQUR9DYruadiao7RVgA7qDAFJ4AAAb0MIgTX4Tusps5r0bQS5bUg42wRlRiRj0lRfEoTU1r0aLAjYT//skxP6ARdBrM6wZBmDNjWY9hJjkmpFIbdMASqpAAwOBFkqUIhgoYJ90Ip+PS2Xw7EnohnChiKE4XPCd26roYWjLY1Z8GR+cqd0PXnUAVq7EGy1+SAAAAAAAADPDhJjJ1DFQQKnNiKEqElEkFgiA3X0Zo3oNISEQ//skxP8ASBBrL+w9JyDJi6a9h5jlACzZfsgBCChgNt2znFsdECcpmpAO1UhVZAXgcQa68aBQIVmRyRMMsk0FJRf/9svsXefGl+AADNSoAAE4DAEoEDUGioEWxIlW0q/YAV0+1+rINQ1Ady6TBDPXumsmMATiKquW//skxPcARsxlN+w9JSjOC+Z+ssAFUyBAC4sl2nvzIoTXd///WWMRVKoABZiEAQA3AYAbEKKgQIvGPgvoirHGVv2wbx0hg4sVWD8eJr9O4hlQGRFgj53W8OjW6NwKRXMo06EdOYuv//////2KyljMQAEl3YBABfRo//tExPOACjhtP/mnggD2i+Z/svAFBsRVOEoTqDmv4jHSP/X1X/He6CbOSEqPu/usEQKul45OJgo9CUFcf6gQAgKEBhLJzmI3+U6tGRisVz/+rzpPurf29X/xbCHbci2mYCaplyYAXf5GEtgoMSgj8kjLBo0ghupYt7u4fMX68ftPF+W3z7wV9npjGGfOduCai6t6QG5MMaHsA6FNBQt+ui2bxWh9yqsv//skxPUARlBbPewwySjMC6e+sJAFiy5HnH21FgcBcFY3qN+nFRK8rDh3pvUJcTSqwsN35BC9awAhkEdBCEPtvZa2tNNPcu/en++BIj9Z/b9MFqLmXRCTNXaHwDYJiIUISW2Gl9dmPLdqZgH7VQvmLOf8y5P4UDk2//tUxPOAC/RrL7msgAkGC6c/sMAEV+7x60ewFBXMkVXw1yaaOOJVRL5UDP17IEFevAsI9bDC6JoYuizmg2pUg5TrweSkLqLoEkVh2GOdDgqm9zYIjH8JRhULdHYaqSLuA/azoLhOrlIyQF2qEIUxqPMOEGNY/U83HU4MrO+Qtdw4T6qcWWY+RYyYF5Q5QIQybisiGMEeJqiglnTisZ5/ZVV73dyYeIJ1u24hySfQBDx4JRpgwUkpZCxFKYfzObI///tExPgACMjhN+ywqelOHCb9hIn8W5SatvWmrNH2ZD12/nJpJJbssZD8/pRcjgLF1RUFI7B42Yw3dPXCqc2HILSkIw1RD87C0teRPaVXzAl2U0hg1ZaNs4aHET6niQ5Qk11P/NHFKwluRwUlY7HOVK50PEKqBS4YF+BiBZDSWbupMrP5MzuVprc62zr8jlJHSP3f2ZfIAtO7QKIY5dgdeBDRI1bfdEQ///uExPSAEGkXO+w80erJqSe8/D9MQ3K6T3YMsGda/3Qwz+fR4WZe+ohb+4g4w4kShZqJprSYATArs7kWFSIG2SGRZynlXTuXcudAs/T+w9DYgUb/p/HNlFiyQZwhRNTv/fN+uT9D1Ybv/f+rasgIqXEQgDxtQIAMTSYeB2X+5qZh+KAYCpxQOSQmOZfrBqBBh6+z/4Hif/0oWAFCQ6yz4N5p1TRGaT86YGh5vLT/hXpZF6EdPI7vC/8jqKqF1t7+iBkgl5//EVaVYv8vPORhBVmvnxv7d/q5tAAipIyFwlI2gh0okKzF2YYB2EAzFdHLH+b8a37gCgRlX4m8ZBIPgT/S0VKLahW6om8u4c8+FeqGDkxURqx0X9jPmH5Tir97qTP4bieJ5mmZW6/qE9DkWuaG78RWkk0I1/FHfBD/6pXP//+9bQAol6lCpUmqQrTK//t0xPcAE1FpSewlh+mqJGm89A7RZcx+D7FPHoagHOE1Y20t/q246p/mw8IIO+XVLLcMv44tyKBU+4QayrNCgAQhDMQt6FJLLf9znUSMyHd8h0fLZUK7e+lKon4w5cRZZ8/vy+/9RiAFItCNn28X/d+173gBJS1EdRoTlj07ULf2WQilsUsNTdavKIRR1G83UpvUaoqTf0qDbUUAYL//wUcSJyCLd67oGaSbRzk1B9QNVWS7DRoGPOT7k7Vqc2Yj9HMqmSW/U+Bg7k/V1OdhTX9cv8vyf8g1ylWLn/3trnyABJcbEIhiwgcMoVKUCDIVQq8uS3JwYH+WRGCLTuklw/Gvk+TETl5+e/n4Sv/m0lzckDuOue5F1GtM1BP6xczZ//tkxPoADXlhTewgbcmvpKm9hiCxTSN5kVmfUu5dI0MqxatlPnnE+eNX7yeZsvl8eSPmV+//lMEaNgtEVvf/Rd8gAAGTQqNNVy0ao6uCOsDjDuRaXOA6f2Csz21prRs4BoIZ+AImXWosn5nbbfdmchiWuqSSilaob6lq5CY9MEuTQQGSKaoORFCJISlnEbVSX2MyQtiK1HY4LChAxzWF7BuKMo2qj5770W9/VmhMuurbt/3c7s54gE250PASQIp6gSYdIXLS/bZ4KdYUVAXJbGMr5mCc6DuJIWBGdzdrt+ZdLfmphrVHQcyMyhI3FW/l//tkxPuADS0hT+wssUmvLKn9hA5hmtTlPXeFq12yYuKd8renTLpGZHKLEnY1YuqRyAih573XDOABoiScaxhKn3t3cza7IKBQxGBIipgpOsYXSrjG/VhqvOT89JYJVSd6wRUmoYaEpKGwKjPKW864IUBflzEhcBL0Myomgl/V4TdZhWUZiI0e+ZEv/9hWf6rHJXvA9w0OopM/xHr8S/y19ke7u7qJXsAAAjAnAp4gIKwD8KM+SDrkZeRicSLsh7QDrK2+xGSwhR/Y8kazygaf//85wQYPbTzLO/VsTDPTd6W2lN9aP/p2ak6vtYb5f0db//tkxP4ADYVXS+wscUHXpOl9hg29I/5GQ5sxbnGJJGnziAM+d8vsnWFy0sou6MUFamjcy9urj1BOPDYqQiHImcPOj/UZdamrL7NiyNTXylo3iKekTygnMfnNf+Rgc//cRSUy3NXqGokEtYFw4ZmzkyU86k8jDo1t6UQ+Kh0JYmfkacbrDX4vmOq03rxkm8VKQ6uquqldUQkoII7BVR0kSNYLuwx2RlRqlVdjUZWRgwrPKkwNsvehn/Yqx1+eQQWolWoIQbZLftW21DKn9UY/yMu6qUPpnn+eeb5lmYYxPXZw8rPwsVXOFj7zIm9LLVTE//tUxPqADRkjSeekcIGEn6k9hI4VxLp2AAABiKmRjl7WFiqqRoXZVlSQ8qoSl40o7U5xg8RoNJLv+YKu//tbPGtS1QisbMkxI6DUk6h2fSf+OupqLiGi2dK5qa7ueFkV2u7nEenVu6ejqhR2S82TlIl4iJc7iCSYLAVInHRrsmHBdtKwskfBtm2Qglsoy7RYnfhoGkf0cEOBL9mUDiRA/WGyNXBhN4xqDpWYs+8y+9sZKxmeW6U/s9fQi4aHYYpC//tkxOsADYEfP+ekyKF6Iyh9gw2pW+9gEGtvOe8q+SYpqigmT2YTbolToFs1hwJzOD/XdYTldTEA86ECd/iyREtssp/JPy3/+63eW5qUWLZGnaza0py35W42Q44tRb45mJ/WDgQdpjjhnSkehUNVYIfTr/3ViJmViIhNUFEoNMopozUCdSdUqJZW7b9aGNZ4bGd4MB426J79LX9NT+wQQddut32UGSlHZzJWzc1JnmRspNS/y8+/en+WVpvRSmvXyf6fgmkgiJVAiHO1qJiIhnhoW1BpJi51QxKHSkS7JFbZ5/2RZA9uyNPO0iqm3tRm//tUxPMAC5UZPeeYbUF1oqd9gyDEmBwVutR/8BiYItkGI65igWHKqHAjKiy0Mziyfn3hzK9Pcz81JuH6i+bRc9LBmWR8H/9k21P7tYmXl4h4iRlNBhgQoBhGYsFHOpznhT6tBrZm3tdIetIyDLh/2Q7U+O2/vcfo4a21vf0JS4bqYC2ckuapGVuo4te3w/iLJQdRDv7Wr9ohx/7zagkQRj9v719tQ6wzMzO0hCiDCmHoEYQHgltJ7aBDzPv5p3Zh//tUxOuAC2kFNewYZ8lTkmc88CGBQ/DrD4RxgFy8OLqbnJ9V/KFwPyjUiUq4VlmRLDIfUWlEizJdmHTgqEFc8vPjGfGSCb55fxuRzZKt8oeTClPBIK5Ma4mKdnTGd/SWeIBmZ2kJKQImAIIVKc6vKwNs00K+0q5NFJXpVVDjNqKEMFYviefK9qi2azg9IyrzMrmWaiw2xT+ALFQ6NAsExOTT4VmcYikULu3OgKbBv9m3/3yXGiGdnZ3SZIohCELM//tkxOiACwEXN+eYacFmHma88w05MEnAZCOpL4uO62KqmHd2JcAzbDiA6oHBagpKFF/S9aCZidabUHEy74InZJaac5czJTLyv/kf+Zd++2f78qPD6n5thFhcVHEA9MP/rnh3c1ZVZVlMhBMizEmWUu1IwvpXpeb7UcN55pa5AiboIsukZj+zjKDCiaGE5sL88BU8yV7axkpow8KJginsZfz/p/wjL8rnKuR+RLsXtMZliNYKuY5I4TLTf//+m/aqaWuoIkoUKIIOA0INPnUaKFvlp/Do8GqbXaNaVB1ZITiYetHCb2/kpswMUWWK1MJi//tUxP0ACyS3NeeYbcmTJyY89A35l/PEhDMeQzMrSkP/2y4f88jNJ6LM+oeoafBKOhg5qp30rVQRhqkXmnfV2pbKY1I6QmQRooKhMEoSHyCJaGsJbym97taG3cJdKFRhyFiG74yvjcyVWDZ5NjciGeht5qUtFIzyzPLUeyf+MmX/hwMXdZL+pf+npb0tG6CnWdDdzVv3tWWNxuLIJokTU+AqwdkY9EPcre1m5Lwr5m6li88OTCfYYQkzVlhz9mQL//tUxPOACqihMew8YMleI2Y89gxQXaV85mBbAncQdPLi2CTJA5iXggyUuI5yHlus58fN58hwqevbUFxoppJpFdLotZdW5JI8y0iBttXSaNJSs5KymsIydSB4ubVTDiAQVBEBBAGQECADrgFbEOEJGsD2ElDVIDYBKEUiMUTYj2g2l/09SrnOaMhYSknIWxgbaQJhHV7V/fU2oiSABoFysSreQI3i2+8MDEwu25V2eNXExRJdrxOVXT///KVUCXNt//tUxPKAC5EZL+e8YMF0JWU09A05TxM+tKeWQ0yo8Ii7n7Kf0vvRieTHrajGpTI0U2i4QkCBcwoC4MgAFZHHz3rTinhRuvm67SxKTQdFHaUSVJsL8qRgrld3Z0UZtZ9hlA1o3csv/XfDiyBdQKCUFCrPrUKaQLh3ABghQgOrXKN4K0if8zMEjhmEzg2DIeVqP0vu5XBFjIsBZuGEs6f/V/86VGplUlSQADySIgFsHhGeMts9bcYbcgefUC5dszoa//tUxOsACtDBJaY9BglcoeT0xI1wJBYNTw33P3cPJKEWITBZo3SHL/+js67diTgPL+zve/XInFElBG1AnVAtjZtCc14NOjUn5lRZh2BAD6uIEtY/bYIzjPRR1ISBQbcC1brJZbILYAAA2SyqDpVsXedfLbyqoESgURQ5kUpv/A08Ez3n7u7ahLM58PmlGxK5KrLiGFpBBo6Z2jowGFtyRuhozztUBAnfbFfdq1qSRkWRG05//yyCar4qvKgAJCEn//tUxOmACmThJ6eMScEKkOQowJlQBYICpA0nVa+Jw9Rdc3XMWuw5eHFGpXeP9zMYrjMvktoYDLWrIlJrpMBU0oVQafBWcHFc9ZdfKcGDLFFYz1m30ZGARK1Mt1V94AAoNhaMoka0hK22fcYZ0DkGATWaEZyFG3t96EE1lr12FomUSAQx7pLqOw2ZiVugI8HIHixzusdSDZlMQU1F/zq94AAwbJjfB8Ahvdb10N4FFsNWryYqlBwdSUcAEOXVZ77q//s0xPQACJiDIaSYScDDjmQwkYko78GgYJ1qtaaiqSaKEWjFeGu7IgKJb9JHaYuOKdQheWdKmIpMQU1FMy4xMDCqqqqVllnQACgXbSmmhrDUSMYl1lqm1WrT8dxqtnmhAKRbFRqla5JZsuSCFILm1G6RFCjmoQ3NQaAyM0tTs08iMOp9oCZwAClgaCIDhdHY//skxPaAR4RxGyYFEACvECR0kQ3omaYR5Y6EMaPKT2YwoT0hJ6YjO7/jqM8JodLiiDjk/Bc2ND2yLHMveimcltzfM23zoyiaEFrBsNieTtW4bArVTEFNRTMuMTAwVSpKWvAALYJx6JGJhPGVnizHbadug6dpFwYc//skxPQARbhtJ6YNCwiij+QoYKUsiEgcvPN2hlHUb2NwONxvhYPZNSzTrbhY0xXSgWaWkIQfI8WBsNJMQU1FMy4xMDCqO/rtsAA+JkkmxgwH10Wy9922zb5VR8+BECKcveHFOnaJNeqiriQSEw/OE8CA6dfPEVk1//sUxPoARURvHySExiCGDeOkwYkYR5BEs6ozSYoVAM875apMQU1FMy4xMDCqqqqqqqqqqqqqm1SHgKAsqoCgB5waPXeEbbWOcPUmOoc/xdpqhZQaDAwGqKCXYIOOzSOU//sUxPkARAxrHySI54B2iWQkkJlk0RK/sU4IQgFP7TxLSLpMQU1FMy4xMDCqqqq64b6wAC8Dg9mbEubAwdE2Ltg33z513B65vpmszel0lEpqDCHVwdAy5Qkfq8m4sQCB//sUxP2ARDhJISSFCqiTiaPkwyTxAN6MubuGDLtefQO73lpMQU1FMy4xMDCqqqqqZjYTbbwABIEo0D5IeCgRS75psOJUIgnZwuzQ8sYknE3/7iamEdQqu4RJo56LJ2EL//sUxPmARABRHSSMyUB8DCOgFIwkyl2ByqIbOSXX9UshHppMQU1FMy4xMDCqqqqqqqqqqqqqiaSmoAAwOdNxjFHNtpj+ELAEcmWfplC4/bGZ0NgAexKLLAWs4s26YVtW//sUxP+ARNxjHSSFKuiRDGRwkwz9Q1maY8ccgsCHLOQanLVMQU1FMy4xMDBVVWRUbWAAJMLBNEFWhvyl7oijkikJUUs7hKKigIGG2kEkpUCQRgYL1B88HSnIKOj7/TzX//sUxPoARIhlHSSBCAhtiCSwYIzk6RlESTlYYhxwA+f068pMQU1FMy4xMDCqqhJGYUl0AAWPxdHgaAzDIuL9lI8+80rM3e5qNjhzGC5I/w73SqXOXBUluPRMDGzZ9iZM//sUxPqAREhnISSYaah4CSPkkwx8abfe91VgcDQuHWX5IfVMQU1FMy4xMDBVVVVVVVVVVVVVX6mi8AAx3X0I9GT5xWGqvURmgpeAnEU1dw2tnhmAZcLKTiCoAKNxHNgL//sUxPYAQ1AVHQGkQKh0COOkkYitcKCY48CDYhgcULib8kpMQU1FMy4xMDBVVVVVVVVVVVVVVVVyhVeA4mBcAlniQRFkKO0QlmDjkkvnRSVVXPmeldvqUmmQsQAL0QEJ//sUxPmAQ9BHISSEyKiBCSNkkA0BBf6a1/KvCFbUb3vV+VpMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqqOVZwBNBYI0MoFG6DrreJOYtrchf9/thQBUYIShIroF//sUxPkARFhLIYSYZihrCSOgkJkUhCdJz373OKOUS97PDapMQU1FMy4xMDCqqqqqqqqqqqqqqqryqr0gABYLFCG+BHVEJq5pJAWFhAICh2KO8QVNEKCsEHBi7JVhBANH//sUxPYAQ9RbHySEyyBkBiOkwIkdLKv+7q1y857++Hdzb7WKJBpltxsgAMAQgXFQh3hh7MtZq+agnz6sKGy8kOF9IxW7jbWo1xv+X/A4079vVusscbccYbAgURYBAAAI//sUxPoAQ5A/HSMYYiCNiOPwxJhFS4dxcoJXrSIfPM2lqaepbqQM6bpGiKTK69ab/+p2QV/oaaCB8wKAy1qRerahXOIDHBWx5j3N7f/8c58MnP/l3gT6a23W3bSW26Wy//sUxPoARERJIYCwYWB1B+Og8I1MMIlAAmaqSB26upEOqweeNXdoL3ESm4MBnPhRwGKeZINesV3vEGe+K4hW1rVfe/j7Uq8aMFzH9GtvcV1Fke3owo9ZEjBgGOfiFvap//sUxPYAQ7Q/ISYESyhpgqQwkLBEGj5dQp7Icb8VtiMD5TM9n0an1///DvWlYUPGArkKXIJAEFjL3tLI5brGQSxvQ70k+Uj6sHEC8fXx/NsVy05QjyIjjRyXTc6XXY1a//sUxPUAQ8ArGwSEaGhegePkkZgFm6a2hilennFe7giTXMZxZZ+h0AulR2uTV8PwUdryvfccrUy10tptE113FXVQdWtaJSJ3Zld2Vo91AAIOh1GaxQmUuTUz+selP8yX//sUxPEAQtgXHwSFIihbA2NgkpiF6PHNMbFvVopqfINiiaYspDjgwByM/W7TLQnDhRIxW1y0QcH6Ncex+tj3Zdpu7X1boUuGlFm2uYSZG1wPtd/v6M6n/jitNwat1RRh//sUxPUAQ2wrISSYZKBoAuOkUwQdnx6zKr66HZ5RdrdiVRb9i0KRxrKyGAUQiKdZVBtpUTdtL+h6YHy2NFlMWpQDdbHG445LIAkA+Bk+LF6sKoKQy1Wqny3Xv3dd6at+//s0xP+ABdhbIbTBgAk9HOV3GNAAdrqHqEH/m29Ozs/0xMgFXn985iBmWzSqKw4n9CWYNGcdk7KRL/HN7mWRxyFQzYEKcIMsbjcckZBQFMGkvFVMUnF+PiSHyQ+tu/kfAxIjrx0a2Qlpdi/cbfdjWIc8IOilqFYUU3ZhyEK1eQP/+bfKr+nbzrWWaNtySVgp//tUxP4ADyjvL7j3gAFhoyU3noABoAI5Oj5nXJYReChks9O73s63NEtTH0kKNVb2Vb5stBeHqZifnMEemW/lJaGTij0kQRCEEQg+Co9YIPHH9LYwoky6aYt0vh6mDLRi1Z1tZEJYLEAs9RYXSdfizdElrcskssAJASvkUfPLAbB93trTMMBha2Zq5OCqto0kv6OVgtDlo3MQ5Fb7OzjOs8hRhTDtzCCbaKEiGyzf27f7+CDPfriTSVtt21kNgduS//tUxOqACVCtMeSEVmkbleV08ZT5hkAQs0zJEKIur+bnv1TMzinhIa1f2+tD7/pTpehHZ1UqK5OIbtwgtzgwiqcp62ZXa1S7ECQW5RU5EbG4lEnZGwSgAnAgQo4WCxJUWgdKKVskaLKA9AwtYSkMhkYzRz5+VcveiyDbirMXQoZJCBmYzBkFq53ytfP3AsJp29V5bm3A2Un/IoCQFxs4mNgboEysN3ec9TVRbXcQXbSJ15tRZFRavp7rc33K+6PM//tExPcACdEJJaYYbckIFeS0wYk5pDWdhARDTAhq8sKKBc2Bbtb6NI3mfaNalqmFqmUAJoDgLUWB5JxzbsyXC25ApAAhDIFOShrO2Ff61yMKfuRD6pdpCHgqoZnMYlBlBcIqgEi32r0Vmlmav1AYHrGjA7Dx7aHt7n4slKkNxiyUl6iKb+uQSRpLURuggMfdfJeBaNeJ0Cxq8ctFbqedrugOlgTpQASx//tUxPgADF0TJaM9AIEUFeT0wYkxEyKCbJh9tlq3swF0wXdWpCf/24i+O2pVijYbDTjBYABdAa/cvGxdWXeybMWW3Cszx4ieI0GYH/+n6SpYOGFnUpMpJIEokEBcVzCIQQ+QvCnrnrjbqmB96pszAJ6CYvd9Nn/7O/m//Oaf8DqM/////////6maDp+BuAo1GNQ0dr/2R0zHZXdMpyGMz3Mjf/////9/UrS6J5gzrW8NZDMQW+wV3hQzgV1IwhJB//tExPmACIz5J6SMS8kRlyR0gI7ZUCwCHFWAWWpGCIsAiegYYsY8WR//9qpMQU1FMy4xMDCqqqqqqqqqqvcLfwA+xgs3hdpbLhB50o4iBhajVJg48ABRAOXHAjPYEBzzcuRgqJYpT9VMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVkYdqEAAoZZ96lBuj1UULIOMuaC5YR/GWsKKLgEoLkccQJFCw//s0xP6ACJC3H4YMTUjrmKOkgI4o05HvxmsfkPV9DfNMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVEkJJuOKgby3nxzSC8USMxjcCCLdAAfEkARgk1sz/lM6YpqX2P4kVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVWVUWAJCGUxgaBhRk//sUxPwARtitHyQEcUB+BeOkkCUII6eNofENe9IpBPatlVEGEsDCiB0TAAZcR/ako3AMOfgRWvje+SpMQU1FMy4xMDCqqqqvSQuAQgdLax4STMBEbsgkG5q5W9RnYMKi//skxPYABPwjI7TAAADPh6QTGDAAxoQkKqptwRNJJ3A+WiYV85OC0cXusCXgosraQfrkmRewYMFnMyVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVQmIk0n+AAXag1Fah6S5G3OIngdMskFUSBSCxw4lbmpB//sUxPmARmDDITxhAAhogiPwYbAIbeQIWc6pUo4b5R4UCqpMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqpRRWgAxMMmg2BiIfkMgA9NeSenz3ZBNFEhkEAHnyEWd//sUxO+AQpQhIQMEZmBYB6PkMAzNbuQIGbCijQBki4p9Fz5MQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqqplFVmAccSkSOLmnHQeUjscuc1bD9+279O5TS4YQAwr//sUxPGAQwQlHySEaGBbgmOgNIwFCpQgQ4CETg+7gsv+ojVMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVWpjW2APGnmwlm6hX1DVuZbcEG+nIWtqQytYFREyMAAYJqL//sUxO2AQgAFIoGAAChaAmRwcxgNXcsXBA4fE5lLmBXLblJMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqhFFWYBEJrsRGD32sJh7pJrigP2LY6tZcfV2JgpJN+BYCCEI//sUxPMAQugZGwMkwGhnhONgxJiVjniUmDRwaU7RxCrGdPtMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqtympIAAWEAIeiDSh4gWuKGhLk0WT+/3/Xp7JVLRaEgq3BRMW//sUxPmAQ9g3HQYMSOB/ieQwwI1FrIzhx4w8o0TAQHP+hVVMQU1FMy4xMDBVVVVVVVVVVVVVVf5JqjAANCVBsQAR4+NeB9y0x58DVUtv//PRuFBIoLiCR8yEsDzIEqLZ//sUxPEAQrgVJYGAxCBdhCOkkIjM3tJjSkxmFGPQ0KrYp9BMQU1FMy4xMDCqqqrryt6wABcnPLLjYiNi4qLelEAL9MPoelhjr6901CL5FpUWwqCiYSyqVQImxBSUHl1T//sUxPEAQpQZHQMEYihkhOOglIwUYmlEd5HUnOLquZuedQlMQU1FMy4xMDCqqqqqqqJET4BwLgFZ/HSHhC4t7ogZ33AkMOEoEg4ienj6FfVfE8CYRVC0x56NCeRqW2gZ//sUxPCAQxwTHQEkIKhOAiQkIQwEpWb+19cG4IA4eUr+I7dMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVWo2qqAACB5ROAExxBtMR7hnCDJ+9gWEJkO6s5aucDQuNgK//sUxPIAQsA3IQMEbKBmg+PkkJhcJZXVNDWobP3HH8zigcpMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqvloA5lg1EigshkOZrwmX9Cw7Lp/ZsMYRVnnEBh8OvCe//sUxPKAQzgjGwCYYOhdAaRwYIwFyoTttbirRLAKig6PHV1MQU1FMy4xMDBVVVVVVVVVVVVVVVVPZamAABBrh4SAIZNASFdiwkGUNs7PEX/gGpIIi027AkiEqCqGAijk//sUxPMAQ1whHyGkZChZA2PgkYyEbbHNwipqVbtsh9xM005MQU1FMy4xMDCqqqqqqqqqqqoOVptJ+AAFtMkIQAFPXWrf0N2cI7qdrG9sTKBHxk0wkk5UFHQktpjDcJzs//sUxPWAQ3QRISMkwChtB+NgJgwUXf1iGmgWijGnrrjQyipMQU1FMy4xMDCqqqqqqqqqqqqqqqqqquYbfsAAIgQkpKLC4+StOaWrARBvNzA9OBLSSqkDCstkqhFgGz2G//sUxPmAQ+hHISSMZyh/CSNgthgVThNZbIKze04z//VZnBtMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVXaSGmAbHl2GFaCu2eEahj2qA9kHYkB7yWl+19+5XskGhU2ukEC//sUxPiAQ7xFGwSATCB8BGPktKQFPDJZlktQqRstAgz6NqpMQU1FMy4xMDCqqqqqqqqqqqqqWFCaoAAc01MABG2hIGLlHOR52rTFi2EhbxyKm69DJ64iu/hVcrfoU5Vq//sUxPIAQ0AdHyMNImhXgeQkYIwFm9MFVaxuWqCxV1U4PjpMQU1FMy4xMDCqqqqqqqqqqqqqqqqquqoZgAAOAALlEkLBT2IspyoS6/AD5qiuztVbuyV3B4ORBNAKBSAW//sUxPEAQsg/GqMAaihdhmOgYAzEWAm9+dsbVBwrPddgrB9MQU1FMy4xMDBVVVVVVVVVVVW66higABNEC4CyBgmGwYpkDQddSESlQ+1tYQcbUsUHTfCNipnEhCWsBNxc//sUxPUAQ0wxHyEkYmhuCaRwkYj1WCdT0aTC1xor4lmUnG1MQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVWIQhIt1AACgIkrKkgTGlZ0FyEHUKLBIY85enatdC0VMSEM//sUxPaAQ6AhI4ClgGhtB6QwNIwUlU41oUS90QgtNr9VHapMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqKUDQTbAAAboJeoBgpuYgItvRxTJQOur/478LbdGkBU+mMedD//sUxPQAQxQ9ISSEYihtA+OkZIxNw4FjEIKy19by9SI2evtMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVhRBQCwQZLhQfVQMKD4P2JQR8bZAKP/a3+PVtBQXPDoeSQtyITI//sUxPOAQ2whHQYAyChbBOQkwKBE4oNgv2TAcrbu/V//i6pMQU1FMy4xMDCqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqppkalgACAJwo6zIGlWiDKB//sUxPYAw/hhHSMEaKhgB+QgYI2EhgOlH0zrG6iaFIQVuDlMQU1FMy4xMDBVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUxPSAQ2AhHyMkwChnhmOgZIwlVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUxPaAQ+QnHySwZmBmiGOgwI1dVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUxPIAQ4wvIYQEZuBMAyQgkIxEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUxPMAQ1AdIYGkYmhdhCPkkwDVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUxPQAQwQXGQSlIkhsBCQklIwVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV//sUxOkBwzwXHyGYwCAQACNUAAAEVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVVV""" + + +@require_mistral_common +class TestMistralCommonTokenizer(unittest.TestCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.tokenizer: MistralCommonTokenizer = AutoTokenizer.from_pretrained( + "hf-internal-testing/namespace-mistralai-repo_name-Mistral-Small-3.1-24B-Instruct-2503", + tokenizer_type="mistral", + ) + cls.ref_tokenizer: MistralTokenizer = MistralTokenizer.from_hf_hub( + "hf-internal-testing/namespace-mistralai-repo_name-Mistral-Small-3.1-24B-Instruct-2503" + ) + # cls.tokenizer_audio: MistralCommonTokenizer = AutoTokenizer.from_pretrained( + # "hf-internal-testing/namesspace-mistralai-repo_name-Voxtral-Mini-3B-2507" + # ) + cls.tokenizer_audio: MistralCommonTokenizer = AutoTokenizer.from_pretrained("mistralai/Voxtral-Mini-3B-2507") + cls.ref_tokenizer_audio: MistralCommonTokenizer = MistralTokenizer.from_hf_hub( + "mistralai/Voxtral-Mini-3B-2507" + ) + cls.fixture_conversations = [ + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + ], + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can I help you?"}, + {"role": "user", "content": "What is the temperature in Paris?"}, + ], + ] + cls.tokenized_fixture_conversations = [ + cls.ref_tokenizer.encode_chat_completion(ChatCompletionRequest.from_openai(conversation)) + for conversation in cls.fixture_conversations + ] + + cls.ref_special_ids = {t["rank"] for t in cls.ref_tokenizer.instruct_tokenizer.tokenizer._all_special_tokens} + + def _ref_piece_to_id(self, piece: str) -> int: + pieces = self.ref_tokenizer.instruct_tokenizer.tokenizer._model.encode( + piece, allowed_special="all", disallowed_special=set() + ) + assert len(pieces) == 1, f"Expected to decode 1 token, got {len(pieces)}" + return pieces[0] + + def test_vocab_size(self): + self.assertEqual(self.tokenizer.vocab_size, self.ref_tokenizer.instruct_tokenizer.tokenizer.n_words) + + def test_save_pretrained(self): + with tempfile.TemporaryDirectory() as tmp_dir: + self.tokenizer.save_pretrained(tmp_dir) + loaded_tokenizer = MistralCommonTokenizer.from_pretrained(tmp_dir) + + self.assertIsNotNone(loaded_tokenizer) + self.assertEqual(self.tokenizer.get_vocab(), loaded_tokenizer.get_vocab()) + self.assertEqual( + self.tokenizer.tokenizer.instruct_tokenizer.tokenizer.version, + loaded_tokenizer.tokenizer.instruct_tokenizer.tokenizer.version, + ) + + with self.assertRaises( + ValueError, msg="Kwargs [unk_args] are not supported by `MistralCommonTokenizer.save_pretrained`." + ): + with tempfile.TemporaryDirectory() as tmp_dir: + self.tokenizer.save_pretrained(tmp_dir, unk_args="") + + def test_encode(self): + string = "Hello, world!" + + # Test 1: + # encode with add_special_tokens + expected_with_special = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(string, bos=True, eos=True) + tokens_with_special = self.tokenizer.encode(string, add_special_tokens=True) + self.assertEqual(tokens_with_special, expected_with_special) + + # Test 2: + # encode without add_special_tokens + expected_without_special = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(string, bos=False, eos=False) + tokens_without_special = self.tokenizer.encode(string, add_special_tokens=False) + self.assertEqual(tokens_without_special, expected_without_special) + + # Test 3: + # encode with return_tensors + tokens_with_return_tensors = self.tokenizer.encode(string, add_special_tokens=False, return_tensors="pt") + self.assertIsInstance(tokens_with_return_tensors, torch.Tensor) + self.assertEqual(tokens_with_return_tensors.tolist()[0], expected_without_special) + + # Test 4: + # encode with max_length + tokens_with_max_length = self.tokenizer.encode(string, add_special_tokens=False, max_length=3) + self.assertEqual(tokens_with_max_length, expected_without_special[:3]) + + # Test 5: + # encode with padding + tokens_with_padding = self.tokenizer.encode( + string, add_special_tokens=False, padding=True, pad_to_multiple_of=6 + ) + expected_padding = [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] * ( + 6 - len(expected_without_special) % 6 + ) + expected_without_special + self.assertEqual(tokens_with_padding, expected_padding) + + for padding in [ + False, + True, + "longest", + "max_length", + "do_not_pad", + PaddingStrategy.LONGEST, + PaddingStrategy.MAX_LENGTH, + PaddingStrategy.DO_NOT_PAD, + ]: + tokens_with_padding = self.tokenizer.encode(string, add_special_tokens=False, padding=padding) + self.assertEqual(tokens_with_padding, expected_without_special) + + # For truncation, we use a longer string + string_long = ( + "Hello world! It is a beautiful day today. The sun is shining brightly and the birds are singing." + ) + expected_long = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(string_long, bos=False, eos=False) + + # Test 6: + # encode with truncation + tokens_with_truncation = self.tokenizer.encode( + string_long, add_special_tokens=False, truncation=True, max_length=12 + ) + self.assertEqual(tokens_with_truncation, expected_long[:12]) + + # Test 7: + # encode with padding and truncation + tokens_with_padding_and_truncation = self.tokenizer.encode( + string_long, add_special_tokens=False, padding=True, pad_to_multiple_of=12, truncation=True, max_length=36 + ) + expected_long_padding = [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] * ( + 12 - len(expected_long) % 12 + ) + expected_long + self.assertEqual(tokens_with_padding_and_truncation, expected_long_padding) + + # Test encode with unsupported kwargs + with self.assertRaises( + ValueError, msg="Kwargs [unk_args] are not supported by `MistralCommonTokenizer.encode`." + ): + self.tokenizer.encode("Hello, world!", add_special_tokens=True, unk_args="") + + def test_decode(self): + string = "Hello, world!" + string_with_space = "Hello, world !" + + tokens_ids = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(string, bos=True, eos=True) + tokens_ids_with_space = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode( + string_with_space, bos=True, eos=True + ) + + # Test 1: + # decode with and without skip_special_tokens + self.assertEqual(self.tokenizer.decode(tokens_ids, skip_special_tokens=True), string) + self.assertEqual(self.tokenizer.decode(tokens_ids, skip_special_tokens=False), "" + string + "") + self.assertEqual(self.tokenizer.decode(tokens_ids_with_space, skip_special_tokens=True), string_with_space) + + # Test 2: + # decode with clean_up_tokenization_spaces + self.assertEqual( + self.tokenizer.decode(tokens_ids_with_space, skip_special_tokens=True, clean_up_tokenization_spaces=True), + "Hello, world!", + ) + + # Test 3: + # decode with unsupported kwargs + with self.assertRaises( + ValueError, msg="Kwargs [unk_args] are not supported by `MistralCommonTokenizer.decode`." + ): + self.tokenizer.decode(tokens_ids, skip_special_tokens=False, unk_args="") + + def test_batch_decode(self): + string = "Hello, world!" + string_with_space = "Hello, world !" + + batch_tokens_ids = [ + self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(string, bos=True, eos=True), + self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(string_with_space, bos=True, eos=True), + ] + + # Test 1: + # batch_decode with and without skip_special_tokens + self.assertEqual( + self.tokenizer.batch_decode(batch_tokens_ids, skip_special_tokens=True), + [string, string_with_space], + ) + self.assertEqual( + self.tokenizer.batch_decode(batch_tokens_ids, skip_special_tokens=False), + ["" + string + "", "" + string_with_space + ""], + ) + self.assertEqual( + self.tokenizer.batch_decode(batch_tokens_ids, skip_special_tokens=True, clean_up_tokenization_spaces=True), + ["Hello, world!", "Hello, world!"], + ) + + # Test 2: + # batch_decode with unsupported kwargs + with self.assertRaises( + ValueError, msg="Kwargs [unk_args] are not supported by `MistralCommonTokenizer.batch_decode`." + ): + self.tokenizer.batch_decode(batch_tokens_ids, skip_special_tokens=False, unk_args="") + + def test_convert_ids_to_tokens(self): + # Test 1: + # with skip_special_tokens=False + ids = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode("Hello world!", bos=True, eos=True) + expected_tokens = [self.ref_tokenizer.instruct_tokenizer.tokenizer.id_to_piece(id) for id in ids] + + tokens = self.tokenizer.convert_ids_to_tokens(ids, skip_special_tokens=False) + self.assertEqual(tokens, expected_tokens) + + token = self.tokenizer.convert_ids_to_tokens(ids[0], skip_special_tokens=False) + self.assertEqual(token, expected_tokens[0]) + + # Test 2: + # with skip_special_tokens=True + expected_tokens = expected_tokens[1:-1] + tokens = self.tokenizer.convert_ids_to_tokens(ids, skip_special_tokens=True) + self.assertEqual(tokens, expected_tokens) + + with self.assertRaises(ValueError): + self.tokenizer.convert_ids_to_tokens(ids[0], skip_special_tokens=True) + token = self.tokenizer.convert_ids_to_tokens(ids[1], skip_special_tokens=True) + self.assertEqual(token, expected_tokens[0]) + + def test_convert_tokens_to_ids(self): + tokens = ["Hello", "world", "!"] + expected_ids = [self._ref_piece_to_id(token) for token in tokens] + # Test 1: + # list of tokens + ids = self.tokenizer.convert_tokens_to_ids(tokens) + self.assertEqual(ids, expected_ids) + + # Test 2: + # single token + id = self.tokenizer.convert_tokens_to_ids(tokens[0]) + self.assertEqual(id, expected_ids[0]) + self.assertEqual(id, self.tokenizer.convert_tokens_to_ids(tokens[0])) + + def test_tokenize(self): + string = "Hello world!" + expected_tokens = [ + self.ref_tokenizer.instruct_tokenizer.tokenizer.id_to_piece(id) + for id in self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(string, bos=False, eos=False) + ] + tokens = self.tokenizer.tokenize(string) + self.assertEqual(tokens, expected_tokens) + + with self.assertRaises( + ValueError, msg="Kwargs [add_special_tokens] are not supported by `MistralCommonTokenizer.tokenize`." + ): + self.tokenizer.tokenize(string, add_special_tokens=True) + + def test_get_special_tokens_mask(self): + # Test 1: + # with skip_special_tokens=False + ids = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode("Hello world!", bos=True, eos=True) + expected_mask = [1 if id in self.ref_special_ids else 0 for id in ids] + + mask = self.tokenizer.get_special_tokens_mask(ids) + self.assertEqual(mask, expected_mask) + + # Test 2: + # already_has_special_tokens=True should raise an error + with self.assertRaises(ValueError): + self.tokenizer.get_special_tokens_mask(ids, already_has_special_tokens=True) + + # Test 3: + # token_ids_1 not None should raise an error + with self.assertRaises(ValueError): + self.tokenizer.get_special_tokens_mask(ids, token_ids_1=ids) + + def test_pad_batch_encoding_input(self): + # Test 1: + # padding and default values + + def get_batch_encoding(): + return self.tokenizer("Hello world!", return_special_tokens_mask=True) + + batch_encoding = get_batch_encoding() + + for padding in [ + False, + True, + "longest", + "max_length", + "do_not_pad", + PaddingStrategy.LONGEST, + PaddingStrategy.MAX_LENGTH, + PaddingStrategy.DO_NOT_PAD, + ]: + padded_batch_encoding = self.tokenizer.pad(get_batch_encoding(), padding=padding) + self.assertEqual(padded_batch_encoding, batch_encoding) + + # Test 2: + # padding_strategy="max_length" or PaddingStrategy.MAX_LENGTH and max_length + for padding in ["max_length", PaddingStrategy.MAX_LENGTH]: + padded_batch_encoding = self.tokenizer.pad(get_batch_encoding(), padding=padding, max_length=12) + self.assertEqual( + padded_batch_encoding["input_ids"], + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] * (12 - len(batch_encoding["input_ids"])) + + batch_encoding["input_ids"], + ) + self.assertEqual( + padded_batch_encoding["attention_mask"], + [0] * (12 - len(batch_encoding["input_ids"])) + batch_encoding["attention_mask"], + ) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + [1] * (12 - len(batch_encoding["input_ids"])) + batch_encoding["special_tokens_mask"], + ) + + # Test 3: + # padding_strategy=True or "longest" or PaddingStrategy.LONGEST or "max_length" or PaddingStrategy.MAX_LENGTH and pad_to_multiple_of 16 + for padding in [True, "longest", PaddingStrategy.LONGEST]: + padded_batch_encoding = self.tokenizer.pad(get_batch_encoding(), padding=padding, pad_to_multiple_of=16) + self.assertEqual( + padded_batch_encoding["input_ids"], + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] * (16 - len(batch_encoding["input_ids"])) + + batch_encoding["input_ids"], + ) + self.assertEqual( + padded_batch_encoding["attention_mask"], + [0] * (16 - len(batch_encoding["input_ids"])) + batch_encoding["attention_mask"], + ) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + [1] * (16 - len(batch_encoding["input_ids"])) + batch_encoding["special_tokens_mask"], + ) + + # Test 4: + # padding_side="right" + right_tokenizer = MistralCommonTokenizer.from_pretrained( + "hf-internal-testing/namespace-mistralai-repo_name-Mistral-Small-3.1-24B-Instruct-2503", + padding_side="right", + ) + right_paddings = [ + right_tokenizer.pad(get_batch_encoding(), padding="max_length", max_length=12), + self.tokenizer.pad(get_batch_encoding(), padding="max_length", max_length=12, padding_side="right"), + ] + for padded_batch_encoding in right_paddings: + self.assertEqual( + padded_batch_encoding["input_ids"], + batch_encoding["input_ids"] + + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] * (12 - len(batch_encoding["input_ids"])), + ) + self.assertEqual( + padded_batch_encoding["attention_mask"], + batch_encoding["attention_mask"] + [0] * (12 - len(batch_encoding["input_ids"])), + ) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + batch_encoding["special_tokens_mask"] + [1] * (12 - len(batch_encoding["input_ids"])), + ) + + # Test 5: + # return_attention_mask=False + padded_batch_encoding = self.tokenizer.pad( + get_batch_encoding(), padding="max_length", max_length=12, return_attention_mask=False + ) + self.assertEqual( + padded_batch_encoding["input_ids"], + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] * (12 - len(batch_encoding["input_ids"])) + + batch_encoding["input_ids"], + ) + self.assertEqual(padded_batch_encoding["attention_mask"], batch_encoding["attention_mask"]) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + [1] * (12 - len(batch_encoding["input_ids"])) + batch_encoding["special_tokens_mask"], + ) + + # Test 6: + # return_tensors="pt" or "np" + for return_tensors in ["pt", "np"]: + padded_batch_encoding = self.tokenizer.pad( + get_batch_encoding(), padding="max_length", max_length=12, return_tensors=return_tensors + ) + self.assertEqual(padded_batch_encoding["input_ids"].shape, torch.Size((12,))) + self.assertEqual(padded_batch_encoding["attention_mask"].shape, torch.Size((12,))) + self.assertEqual(padded_batch_encoding["special_tokens_mask"].shape, torch.Size((12,))) + + def test_list_batch_encoding_input(self): + def get_batch_encoding(): + return self.tokenizer(["Hello world!", "Hello world! Longer sentence."], return_special_tokens_mask=True) + + # Test 1: + # padding=True or "longest" or PaddingStrategy.LONGEST + batch_encoding = get_batch_encoding() + for padding in [ + True, + "longest", + PaddingStrategy.LONGEST, + ]: + padded_batch_encoding = self.tokenizer.pad(get_batch_encoding(), padding=padding) + self.assertEqual( + padded_batch_encoding["input_ids"], + [ + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] + * (len(batch_encoding["input_ids"][1]) - len(batch_encoding["input_ids"][0])) + + batch_encoding["input_ids"][0], + batch_encoding["input_ids"][1], + ], + ) + self.assertEqual( + padded_batch_encoding["attention_mask"], + [ + [0] * (len(batch_encoding["input_ids"][1]) - len(batch_encoding["input_ids"][0])) + + batch_encoding["attention_mask"][0], + batch_encoding["attention_mask"][1], + ], + ) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + [ + [1] * (len(batch_encoding["input_ids"][1]) - len(batch_encoding["input_ids"][0])) + + batch_encoding["special_tokens_mask"][0], + batch_encoding["special_tokens_mask"][1], + ], + ) + + # Test 2: + # padding_strategy="max_length" or PaddingStrategy.MAX_LENGTH and max_length + for padding in ["max_length", PaddingStrategy.MAX_LENGTH]: + padded_batch_encoding = self.tokenizer.pad(get_batch_encoding(), padding=padding, max_length=12) + self.assertEqual( + padded_batch_encoding["input_ids"], + [ + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] + * (12 - len(batch_encoding["input_ids"][0])) + + batch_encoding["input_ids"][0], + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] + * (12 - len(batch_encoding["input_ids"][1])) + + batch_encoding["input_ids"][1], + ], + ) + self.assertEqual( + padded_batch_encoding["attention_mask"], + [ + [0] * (12 - len(batch_encoding["input_ids"][0])) + batch_encoding["attention_mask"][0], + [0] * (12 - len(batch_encoding["input_ids"][1])) + batch_encoding["attention_mask"][1], + ], + ) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + [ + [1] * (12 - len(batch_encoding["input_ids"][0])) + batch_encoding["special_tokens_mask"][0], + [1] * (12 - len(batch_encoding["input_ids"][1])) + batch_encoding["special_tokens_mask"][1], + ], + ) + + # Test 3: + # padding_strategy=True or "longest" or PaddingStrategy.LONGEST or "max_length" or PaddingStrategy.MAX_LENGTH and pad_to_multiple_of 16 + for padding in [True, "longest", PaddingStrategy.LONGEST]: + padded_batch_encoding = self.tokenizer.pad(get_batch_encoding(), padding=padding, pad_to_multiple_of=16) + self.assertEqual( + padded_batch_encoding["input_ids"], + [ + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] + * (16 - len(batch_encoding["input_ids"][0])) + + batch_encoding["input_ids"][0], + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] + * (16 - len(batch_encoding["input_ids"][1])) + + batch_encoding["input_ids"][1], + ], + ) + self.assertEqual( + padded_batch_encoding["attention_mask"], + [ + [0] * (16 - len(batch_encoding["input_ids"][0])) + batch_encoding["attention_mask"][0], + [0] * (16 - len(batch_encoding["input_ids"][1])) + batch_encoding["attention_mask"][1], + ], + ) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + [ + [1] * (16 - len(batch_encoding["input_ids"][0])) + batch_encoding["special_tokens_mask"][0], + [1] * (16 - len(batch_encoding["input_ids"][1])) + batch_encoding["special_tokens_mask"][1], + ], + ) + + # Test 4: + # padding_side="right" + right_tokenizer = MistralCommonTokenizer.from_pretrained( + "hf-internal-testing/namespace-mistralai-repo_name-Mistral-Small-3.1-24B-Instruct-2503", + padding_side="right", + ) + right_paddings = [ + right_tokenizer.pad(get_batch_encoding(), padding="max_length", max_length=12), + self.tokenizer.pad(get_batch_encoding(), padding="max_length", max_length=12, padding_side="right"), + ] + for padded_batch_encoding in right_paddings: + self.assertEqual( + padded_batch_encoding["input_ids"], + [ + batch_encoding["input_ids"][0] + + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] + * (12 - len(batch_encoding["input_ids"][0])), + batch_encoding["input_ids"][1] + + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] + * (12 - len(batch_encoding["input_ids"][1])), + ], + ) + self.assertEqual( + padded_batch_encoding["attention_mask"], + [ + batch_encoding["attention_mask"][0] + [0] * (12 - len(batch_encoding["input_ids"][0])), + batch_encoding["attention_mask"][1] + [0] * (12 - len(batch_encoding["input_ids"][1])), + ], + ) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + [ + batch_encoding["special_tokens_mask"][0] + [1] * (12 - len(batch_encoding["input_ids"][0])), + batch_encoding["special_tokens_mask"][1] + [1] * (12 - len(batch_encoding["input_ids"][1])), + ], + ) + + # Test 5: + # return_attention_mask=False + padded_batch_encoding = self.tokenizer.pad( + get_batch_encoding(), padding="max_length", max_length=12, return_attention_mask=False + ) + self.assertEqual( + padded_batch_encoding["input_ids"], + [ + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] * (12 - len(batch_encoding["input_ids"][0])) + + batch_encoding["input_ids"][0], + [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] * (12 - len(batch_encoding["input_ids"][1])) + + batch_encoding["input_ids"][1], + ], + ) + self.assertEqual(padded_batch_encoding["attention_mask"], batch_encoding["attention_mask"]) + self.assertEqual( + padded_batch_encoding["special_tokens_mask"], + [ + [1] * (12 - len(batch_encoding["input_ids"][0])) + batch_encoding["special_tokens_mask"][0], + [1] * (12 - len(batch_encoding["input_ids"][1])) + batch_encoding["special_tokens_mask"][1], + ], + ) + + # Test 6: + # return_tensors="pt" or "np" + for return_tensors in ["pt", "np"]: + padded_batch_encoding = self.tokenizer.pad( + get_batch_encoding(), padding="max_length", max_length=12, return_tensors=return_tensors + ) + self.assertEqual(padded_batch_encoding["input_ids"].shape, torch.Size((2, 12))) + self.assertEqual(padded_batch_encoding["attention_mask"].shape, torch.Size((2, 12))) + self.assertEqual(padded_batch_encoding["special_tokens_mask"].shape, torch.Size((2, 12))) + + def test_truncate_sequences(self): + # Test 1: + # truncation_strategy="longest_first" or TruncationStrategy.LONGEST_FIRST + text = "Hello world!" + ids = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(text, bos=True, eos=True) + for truncation in ["longest_first", TruncationStrategy.LONGEST_FIRST]: + for num_tokens_to_remove in [0, 2]: + tokens, none, overflowing_tokens = self.tokenizer.truncate_sequences( + ids, truncation_strategy=truncation, num_tokens_to_remove=num_tokens_to_remove + ) + self.assertEqual(tokens, ids[:-num_tokens_to_remove] if num_tokens_to_remove > 0 else ids) + self.assertIsNone(none) + self.assertEqual(overflowing_tokens, ids[-num_tokens_to_remove:] if num_tokens_to_remove > 0 else []) + + # Test 2: + # truncation_strategy="only_first" or "only_second" or TruncationStrategy.ONLY_FIRST or TruncationStrategy.ONLY_SECOND + # Should raise a ValueError + for truncation in ["only_first", "only_second", TruncationStrategy.ONLY_FIRST, TruncationStrategy.ONLY_SECOND]: + with self.assertRaises(ValueError): + self.tokenizer.truncate_sequences(ids, truncation_strategy=truncation, num_tokens_to_remove=1) + + # Test 3: + # truncation_strategy="do_not_truncate" or TruncationStrategy.DO_NOT_TRUNCATE + for truncation in ["do_not_truncate", TruncationStrategy.DO_NOT_TRUNCATE]: + tokens, none, overflowing_tokens = self.tokenizer.truncate_sequences( + ids, truncation_strategy=truncation, num_tokens_to_remove=1 + ) + self.assertEqual(tokens, ids) + self.assertIsNone(none) + self.assertEqual(overflowing_tokens, []) + + # Test 4: + # pair_ids is not None + # Should raise a ValueError + with self.assertRaises(ValueError): + self.tokenizer.truncate_sequences( + ids, pair_ids=ids, truncation_strategy="longest_first", num_tokens_to_remove=1 + ) + + # Test 5: + # stride + for stride in [0, 2]: + tokens, none, overflowing_tokens = self.tokenizer.truncate_sequences( + ids, truncation_strategy="longest_first", num_tokens_to_remove=2, stride=stride + ) + self.assertEqual(tokens, ids[:-2]) + self.assertIsNone(none) + self.assertEqual(overflowing_tokens, ids[-2 - stride :]) + + # Test 6: + # truncation_side="left" + left_tokenizer = MistralCommonTokenizer.from_pretrained( + "hf-internal-testing/namespace-mistralai-repo_name-Mistral-Small-3.1-24B-Instruct-2503", + truncation_side="left", + ) + tokens, none, overflowing_tokens = left_tokenizer.truncate_sequences( + ids, truncation_strategy="longest_first", num_tokens_to_remove=2 + ) + self.assertEqual(tokens, ids[2:]) + self.assertIsNone(none) + self.assertEqual(overflowing_tokens, ids[:2]) + + def test_apply_chat_template_basic(self): + conversation = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can I help you?"}, + {"role": "user", "content": "What is the capital of France?"}, + ] + + expected_tokenized = self.ref_tokenizer.encode_chat_completion(ChatCompletionRequest.from_openai(conversation)) + + # Test 1: + # with tokenize + self.assertEqual( + self.tokenizer.apply_chat_template(conversation, tokenize=False), + expected_tokenized.text, + ) + + # Test 2: + # without tokenize + self.assertEqual(self.tokenizer.apply_chat_template(conversation, tokenize=True), expected_tokenized.tokens) + + with self.assertRaises( + ValueError, msg="Kwargs [unk_args] are not supported by `MistralCommonTokenizer.apply_chat_template`." + ): + self.tokenizer.apply_chat_template(conversation, tokenize=True, unk_args="") + + def test_apply_chat_template_continue_final_message(self): + conversation = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can I help you?"}, + {"role": "user", "content": "What is the capital of France?"}, + {"role": "assistant", "content": "Paris"}, + ] + + expected_tokenized = self.ref_tokenizer.encode_chat_completion( + ChatCompletionRequest.from_openai(conversation, continue_final_message=True) + ) + + self.assertEqual( + self.tokenizer.apply_chat_template(conversation, tokenize=False, continue_final_message=True), + expected_tokenized.text, + ) + self.assertEqual( + self.tokenizer.apply_chat_template(conversation, tokenize=True, continue_final_message=True), + expected_tokenized.tokens, + ) + + with self.assertRaises(InvalidMessageStructureException): + self.tokenizer.apply_chat_template(conversation, tokenize=False, continue_final_message=False) + + def test_apply_chat_template_with_tools(self): + conversation = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can I help you?"}, + {"role": "user", "content": "What is the temperature in Paris?"}, + { + "role": "assistant", + "tool_calls": [ + { + "id": "azerty123", + "function": { + "name": "get_current_weather", + "arguments": {"location": "Paris", "format": "text", "unit": "celsius"}, + }, + } + ], + }, + {"role": "tool", "name": "get_current_weather", "content": "22", "tool_call_id": "azerty123"}, + ] + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + "required": ["location"], + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + "format": { + "type": "string", + "enum": ["text", "json"], + "description": "The format of the response", + "required": ["format"], + }, + }, + }, + }, + } + ] + + expected_tokenized = self.ref_tokenizer.encode_chat_completion( + ChatCompletionRequest.from_openai(conversation, tools) + ) + self.assertEqual( + self.tokenizer.apply_chat_template(conversation, tools=tools, tokenize=False), + expected_tokenized.text, + ) + + def test_apply_chat_template_with_image(self): + ref_conversation = conversation = [ + {"role": "system", "content": "You are a helpful assistant."}, + { + "role": "user", + "content": [ + {"type": "text", "text": "What is this?"}, + { + "type": "image_url", + "image_url": {"url": IMG_URL}, + }, + ], + }, + ] + + expected_tokenized = self.ref_tokenizer.encode_chat_completion( + ChatCompletionRequest.from_openai(ref_conversation) + ) + image_contents = [ + { + "type": "image_url", + "image_url": {"url": IMG_URL}, + }, + { + "type": "image", + "url": IMG_URL, + }, + {"type": "image", "base64": IMG_BASE_64}, + ] + for image_content in image_contents: + conversation = [ + {"role": "system", "content": "You are a helpful assistant."}, + { + "role": "user", + "content": [{"type": "text", "text": "What is this?"}, image_content], + }, + ] + + output = self.tokenizer.apply_chat_template(conversation, tokenize=True) + self.assertEqual(output, expected_tokenized.tokens) + + output_dict = self.tokenizer.apply_chat_template(conversation, tokenize=True, return_dict=True) + self.assertEqual(output_dict["input_ids"], expected_tokenized.tokens) + self.assertEqual(len(output_dict["pixel_values"]), len(expected_tokenized.images)) + for o, e in zip(output_dict["pixel_values"], expected_tokenized.images): + self.assertTrue(np.allclose(o, e)) + + output_dict = self.tokenizer.apply_chat_template( + conversation, tokenize=True, return_dict=True, return_tensors="pt" + ) + self.assertEqual(output_dict["input_ids"].tolist()[0], expected_tokenized.tokens) + self.assertTrue(torch.allclose(output_dict["pixel_values"], torch.tensor(expected_tokenized.images))) + + def test_apply_chat_template_with_audio(self): + ref_conversation = conversation = [ + { + "role": "user", + "content": [ + {"type": "text", "text": "What is this?"}, + { + "type": "input_audio", + "input_audio": { + "data": AUDIO_BASE_64, + "format": "wav", + }, + }, + ], + }, + ] + + expected_tokenized = self.ref_tokenizer_audio.encode_chat_completion( + ChatCompletionRequest.from_openai(ref_conversation) + ) + audio_contents = [ + { + "type": "audio", + "url": AUDIO_URL, + }, + { + "type": "audio", + "path": hf_hub_download( + repo_id=f"{AUDIO_NAMESPACE}/{AUDIO_REPO_NAME}", filename=AUDIO_FILENAME, repo_type="dataset" + ), + }, + {"type": "audio", "base64": AUDIO_BASE_64}, + ] + for audio_content in audio_contents: + conversation = [ + { + "role": "user", + "content": [{"type": "text", "text": "What is this?"}, audio_content], + }, + ] + + output = self.tokenizer_audio.apply_chat_template(conversation, tokenize=True) + self.assertEqual(output, expected_tokenized.tokens) + + output_dict = self.tokenizer_audio.apply_chat_template(conversation, tokenize=True, return_dict=True) + self.assertEqual(output_dict["input_ids"], expected_tokenized.tokens) + self.assertEqual(len(output_dict["audio"]), len(expected_tokenized.audios)) + for o, e in zip(output_dict["audio"], expected_tokenized.audios): + audio_array = e.audio_array + self.assertTrue(np.allclose(o, audio_array)) + + with self.assertRaises(NotImplementedError): + output_dict = self.tokenizer_audio.apply_chat_template( + conversation, tokenize=True, return_dict=True, return_tensors="pt" + ) + + def test_appsly_chat_template_with_truncation(self): + conversation = [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can I help you?"}, + {"role": "user", "content": "What is the capital of France?"}, + ] + + expected_tokenized = self.ref_tokenizer.encode_chat_completion(ChatCompletionRequest.from_openai(conversation)) + + # Test 1: + # with truncation + self.assertEqual( + self.tokenizer.apply_chat_template(conversation, tokenize=True, truncation=True, max_length=20), + expected_tokenized.tokens[:20], + ) + + # Test 2: + # without truncation + self.assertEqual( + self.tokenizer.apply_chat_template(conversation, tokenize=True, truncation=False, max_length=20), + expected_tokenized.tokens, + ) + + # Test 3: + # assert truncation is boolean + with self.assertRaises(ValueError): + self.tokenizer.apply_chat_template( + conversation, tokenize=True, truncation=TruncationStrategy.LONGEST_FIRST, max_length=20 + ) + + def test_batch_apply_chat_template(self): + conversations = [ + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can I help you?"}, + { + "role": "user", + "content": [ + {"type": "text", "text": "What is this?"}, + { + "type": "image_url", + "image_url": {"url": IMG_URL}, + }, + ], + }, + ], + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can I help you?"}, + {"role": "user", "content": "What is the temperature in Paris?"}, + { + "role": "assistant", + "tool_calls": [ + { + "id": "azerty123", + "function": { + "name": "get_current_weather", + "arguments": {"location": "Paris", "format": "text", "unit": "celsius"}, + }, + } + ], + }, + {"role": "tool", "name": "get_current_weather", "content": "22", "tool_call_id": "azerty123"}, + ], + ] + + tools = [ + { + "type": "function", + "function": { + "name": "get_current_weather", + "description": "Get the current weather in a given location", + "parameters": { + "type": "object", + "properties": { + "location": { + "type": "string", + "description": "The city and state, e.g. San Francisco, CA", + "required": ["location"], + }, + "unit": {"type": "string", "enum": ["celsius", "fahrenheit"]}, + "format": { + "type": "string", + "enum": ["text", "json"], + "description": "The format of the response", + "required": ["format"], + }, + }, + }, + }, + } + ] + + expected_tokenized = [ + self.ref_tokenizer.encode_chat_completion(ChatCompletionRequest.from_openai(conversation, tools=tools)) + for conversation in conversations + ] + + text_outputs = self.tokenizer.apply_chat_template(conversations, tools=tools, tokenize=False) + token_outputs = self.tokenizer.apply_chat_template(conversations, tools=tools, tokenize=True) + + self.assertEqual(len(text_outputs), len(token_outputs)) + self.assertEqual(len(text_outputs), len(expected_tokenized)) + for text, token, expected in zip(text_outputs, token_outputs, expected_tokenized): + self.assertEqual(text, expected.text) + self.assertEqual(token, expected.tokens) + + with self.assertRaises( + ValueError, + msg="Kwargs [unk_args] are not supported by `MistralCommonTokenizer.batch_apply_chat_template`.", + ): + self.tokenizer.apply_chat_template(conversations, tools=tools, tokenize=True, unk_args="") + + def test_batch_apply_images(self): + conversations = [ + [ + {"role": "system", "content": "You are a helpful assistant."}, + { + "role": "user", + "content": [ + {"type": "text", "text": "What is this?"}, + { + "type": "image_url", + "image_url": {"url": IMG_URL}, + }, + ], + }, + ], + [ + {"role": "system", "content": "You are a helpful assistant."}, + { + "role": "user", + "content": [ + {"type": "text", "text": "What is this?"}, + { + "type": "image", + "url": IMG_URL, + }, + ], + }, + ], + [ + {"role": "system", "content": "You are a helpful assistant."}, + { + "role": "user", + "content": [ + {"type": "text", "text": "What is this?"}, + {"type": "image", "base64": IMG_BASE_64}, + ], + }, + ], + ] + + ref_conversation = [ + {"role": "system", "content": "You are a helpful assistant."}, + { + "role": "user", + "content": [ + {"type": "text", "text": "What is this?"}, + { + "type": "image_url", + "image_url": {"url": IMG_URL}, + }, + ], + }, + ] + + expected_tokenized = self.ref_tokenizer.encode_chat_completion( + ChatCompletionRequest.from_openai(ref_conversation) + ) + + output = self.tokenizer.apply_chat_template(conversations, tokenize=True) + self.assertEqual(output, [expected_tokenized.tokens] * 3) + + output = self.tokenizer.apply_chat_template(conversations, tokenize=True, return_dict=True) + self.assertEqual(output["input_ids"], [expected_tokenized.tokens] * 3) + self.assertEqual(len(output["pixel_values"]), len(expected_tokenized.images) * 3) + for o, e in zip(output["pixel_values"], [expected_tokenized.images] * 3): + self.assertTrue(np.allclose(o, e)) + + output = self.tokenizer.apply_chat_template( + conversations, tokenize=True, return_dict=True, return_tensors="pt" + ) + self.assertEqual(output["input_ids"].tolist(), [expected_tokenized.tokens] * 3) + self.assertEqual(output["input_ids"].shape[0], len(expected_tokenized.images) * 3) + self.assertTrue(torch.allclose(output["pixel_values"], torch.tensor([expected_tokenized.images] * 3))) + + output = self.tokenizer.apply_chat_template( + conversations, tokenize=True, return_dict=True, return_tensors="np" + ) + self.assertEqual(output["input_ids"].tolist(), [expected_tokenized.tokens] * 3) + self.assertTrue(np.allclose(output["pixel_values"], np.array([expected_tokenized.images] * 3))) + + def test_batch_apply_chat_template_with_continue_final_message(self): + conversations = [ + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can "}, + ], + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + {"role": "assistant", "content": "Hello! How can I help you? Ou préférez vous "}, + ], + ] + + # Test 1: + # with continue_final_message + expected_tokenized = [ + self.ref_tokenizer.encode_chat_completion( + ChatCompletionRequest.from_openai(conversation, continue_final_message=True) + ) + for conversation in conversations + ] + + token_outputs = self.tokenizer.apply_chat_template(conversations, tokenize=True, continue_final_message=True) + + for output, expected in zip(token_outputs, expected_tokenized): + self.assertEqual(output, expected.tokens) + + # Test 2: + # without continue_final_message + with self.assertRaises(InvalidMessageStructureException): + self.tokenizer.apply_chat_template( + conversations, + tokenize=False, + continue_final_message=False, + ) + + # Test 3: + # with continue_final_message and last role is not assistant + with self.assertRaises(InvalidMessageStructureException): + self.tokenizer.apply_chat_template( + conversation=[ + [ + {"role": "system", "content": "You are a helpful assistant."}, + {"role": "user", "content": "Hi!"}, + ] + ], + tokenize=True, + continue_final_message=True, + ) + + def test_batch_apply_chat_template_with_truncation( + self, + ): + # Test 1: + # with truncation + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=True, truncation=True, max_length=20 + ) + + for output, expected in zip(token_outputs, self.tokenized_fixture_conversations): + self.assertEqual(output, expected.tokens[:20]) + + # Test 2: + # without truncation + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=True, truncation=False, max_length=20 + ) + self.assertEqual(len(token_outputs), len(self.tokenized_fixture_conversations)) + for output, expected in zip(token_outputs, self.tokenized_fixture_conversations): + self.assertEqual(output, expected.tokens) + + # Test 3: + # assert truncation is boolean + with self.assertRaises(ValueError): + self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=True, truncation=TruncationStrategy.LONGEST_FIRST, max_length=20 + ) + + def test_batch_apply_chat_template_with_padding( + self, + ): + for padding in [True, "max_length", PaddingStrategy.LONGEST, PaddingStrategy.MAX_LENGTH]: + if padding == PaddingStrategy.MAX_LENGTH: + # No padding if no max length is provided + token_outputs = self.tokenizer.apply_chat_template(self.fixture_conversations, padding=padding) + self.assertEqual(len(token_outputs), len(self.tokenized_fixture_conversations)) + for output, expected in zip(token_outputs, self.tokenized_fixture_conversations): + self.assertEqual(output, expected.tokens) + + max_length = 20 if padding == PaddingStrategy.MAX_LENGTH else None + + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=True, padding=padding, max_length=max_length + ) + + if padding != PaddingStrategy.MAX_LENGTH: + longest = max(len(tokenized.tokens) for tokenized in self.tokenized_fixture_conversations) + self.assertEqual(len(token_outputs), len(self.tokenized_fixture_conversations)) + for output, expected in zip(token_outputs, self.tokenized_fixture_conversations): + self.assertEqual( + output, + [self.tokenizer.pad_token_id] * (longest - len(expected.tokens)) + expected.tokens, + ) + else: + self.assertEqual(len(token_outputs), len(self.tokenized_fixture_conversations)) + for output, expected in zip(token_outputs, self.tokenized_fixture_conversations): + if len(expected.tokens) < max_length: + self.assertEqual( + output, + [self.tokenizer.pad_token_id] * (20 - len(expected.tokens)) + expected.tokens, + ) + else: + self.assertEqual(output, expected.tokens) + + for padding in [False, "do_not_pad", PaddingStrategy.DO_NOT_PAD]: + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=True, padding=padding + ) + self.assertEqual(len(token_outputs), len(self.tokenized_fixture_conversations)) + for output, expected in zip(token_outputs, self.tokenized_fixture_conversations): + self.assertEqual(output, expected.tokens) + + def test_batch_apply_chat_template_with_padding_and_truncation( + self, + ): + max_length = 20 + for padding in [True, "max_length", PaddingStrategy.LONGEST, PaddingStrategy.MAX_LENGTH]: + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=True, truncation=True, padding=padding, max_length=max_length + ) + self.assertEqual(len(token_outputs), len(self.tokenized_fixture_conversations)) + for output, expected in zip(token_outputs, self.tokenized_fixture_conversations): + self.assertEqual( + output, [self.tokenizer.pad_token_id] * (20 - len(expected.tokens)) + expected.tokens[:20] + ) + for padding in [False, "do_not_pad", PaddingStrategy.DO_NOT_PAD]: + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=True, truncation=True, padding=padding, max_length=max_length + ) + self.assertEqual(len(token_outputs), len(self.tokenized_fixture_conversations)) + for output, expected in zip(token_outputs, self.tokenized_fixture_conversations): + self.assertEqual(output, expected.tokens[:20]) + + def test_batch_apply_chat_template_return_tensors(self): + # Test 1: + # with tokenize + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=True, return_tensors="pt", padding=True + ) + self.assertIsInstance(token_outputs, torch.Tensor) + self.assertEqual( + token_outputs.shape, + (len(self.fixture_conversations), max(len(t.tokens) for t in self.tokenized_fixture_conversations)), + ) + + # Test 2: + # without tokenize, should ignore return_tensors + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=False, return_tensors="pt", padding=True + ) + self.assertEqual(token_outputs, [t.text for t in self.tokenized_fixture_conversations]) + + def test_batch_apply_chat_template_return_dict(self): + # Test 1: + # with tokenize + token_outputs = self.tokenizer.apply_chat_template(self.fixture_conversations, tokenize=True, return_dict=True) + self.assertIn("input_ids", token_outputs) + self.assertIn("attention_mask", token_outputs) + self.assertEqual(token_outputs["input_ids"], [t.tokens for t in self.tokenized_fixture_conversations]) + self.assertEqual( + token_outputs["attention_mask"], [[1] * len(t.tokens) for t in self.tokenized_fixture_conversations] + ) + + # Test 2: + # without tokenize, should ignore return_dict + token_outputs = self.tokenizer.apply_chat_template( + self.fixture_conversations, tokenize=False, return_dict=True + ) + self.assertNotIsInstance(token_outputs, dict) + self.assertEqual(token_outputs, [t.text for t in self.tokenized_fixture_conversations]) + + def test_call(self): + # Test 1: + # default case + text = "Hello world!" + expected_tokens = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(text, bos=True, eos=True) + tokens = self.tokenizer(text) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [1] * len(expected_tokens)) + + # Test 2: + # return_attention_mask=False + tokens = self.tokenizer(text, return_attention_mask=False) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertNotIn("attention_mask", tokens) + + # Test 3: + # return_tensors="pt" + tokens = self.tokenizer(text, return_tensors="pt") + self.assertIsInstance(tokens["input_ids"], torch.Tensor) + self.assertTrue(torch.equal(tokens["input_ids"], torch.Tensor(expected_tokens).unsqueeze(0))) + self.assertIsInstance(tokens["attention_mask"], torch.Tensor) + self.assertTrue(torch.equal(tokens["attention_mask"], torch.ones(1, len(expected_tokens)))) + + # Test 4: + # return_special_tokens_mask=True + tokens = self.tokenizer(text, return_special_tokens_mask=True) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [1] * len(expected_tokens)) + self.assertEqual(tokens["special_tokens_mask"], [1] + [0] * (len(expected_tokens) - 2) + [1]) + + # Test 5: + # add_special_tokens=False + expected_tokens = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(text, bos=False, eos=False) + tokens = self.tokenizer(text, add_special_tokens=False, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [1] * len(expected_tokens)) + self.assertEqual(tokens["special_tokens_mask"], [0] * len(expected_tokens)) + + with self.assertRaises( + ValueError, msg="Kwargs [wrong_kwarg] are not supported by `MistralCommonTokenizer.__call__`." + ): + self.tokenizer(text, wrong_kwarg=True) + + with self.assertRaises( + ValueError, + msg="`text_pair`, `text_target` and `text_pair_target` are not supported by `MistralCommonTokenizer`.", + ): + self.tokenizer(text, text_pair="Hello world!") + with self.assertRaises( + ValueError, + msg="`text_pair`, `text_target` and `text_pair_target` are not supported by `MistralCommonTokenizer`.", + ): + self.tokenizer(text, text_target="Hello world!") + with self.assertRaises( + ValueError, + msg="`text_pair`, `text_target` and `text_pair_target` are not supported by `MistralCommonTokenizer`.", + ): + self.tokenizer(text, text_pair_target="Hello world!") + + def test_call_with_truncation(self): + # Test 1: + # truncation=True or "longest_first" or TruncationStrategy.LONGEST_FIRST + text = "Hello world!" * 10 + expected_tokens = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(text, bos=True, eos=True) + + for truncation in [True, "longest_first", TruncationStrategy.LONGEST_FIRST]: + tokens = self.tokenizer(text, truncation=True, max_length=10, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens[:10]) + self.assertEqual(tokens["attention_mask"], [1] * 10) + self.assertEqual(tokens["special_tokens_mask"], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + + # Test 2: + # truncation=False + for truncation in [False, "do_not_truncate", TruncationStrategy.DO_NOT_TRUNCATE]: + tokens = self.tokenizer(text, truncation=truncation, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [1] * len(expected_tokens)) + self.assertEqual(tokens["special_tokens_mask"], [1] + [0] * (len(expected_tokens) - 2) + [1]) + + # Test 3: + # truncation=True or "longest_first" or TruncationStrategy.LONGEST_FIRST with return_overflowing_tokens=True and stride + for truncation in [True, "longest_first", TruncationStrategy.LONGEST_FIRST]: + for stride in [0, 2]: + tokens = self.tokenizer( + text, + truncation=truncation, + max_length=10, + return_overflowing_tokens=True, + return_special_tokens_mask=True, + stride=stride, + ) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens[:10]) + self.assertEqual(tokens["attention_mask"], [1] * 10) + self.assertEqual(tokens["special_tokens_mask"], [1, 0, 0, 0, 0, 0, 0, 0, 0, 0]) + self.assertEqual(tokens["overflowing_tokens"], expected_tokens[10 - stride :]) + self.assertEqual(tokens["num_truncated_tokens"], len(expected_tokens) - 10) + + # Test 4: + # truncation="only_first" or TruncationStrategy.ONLY_FIRST or "only_second" or TruncationStrategy.ONLY_SECOND + # should raise an error + for truncation in ["only_first", TruncationStrategy.ONLY_FIRST, "only_second", TruncationStrategy.ONLY_SECOND]: + with self.assertRaises( + ValueError, + msg="Truncation strategy `only_first` and `only_second` are not supported by `MistralCommonTokenizer`.", + ): + self.tokenizer(text, truncation=truncation) + + def test_call_with_padding(self): + text = "Hello world!" + expected_tokens = self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(text, bos=True, eos=True) + + # Test 1: + # padding=False or padding=True or "do_not_pad" or PaddingStrategy.DO_NOT_PAD or padding="longest" or PaddingStrategy.LONGEST + for padding in [False, True, "do_not_pad", PaddingStrategy.DO_NOT_PAD, "longest", PaddingStrategy.LONGEST]: + tokens = self.tokenizer(text, padding=padding, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [1] * len(expected_tokens)) + self.assertEqual(tokens["special_tokens_mask"], [1] + [0] * (len(expected_tokens) - 2) + [1]) + + # Test 2: + # padding="max_length" or PaddingStrategy.MAX_LENGTH + for padding in ["max_length", PaddingStrategy.MAX_LENGTH]: + tokens = self.tokenizer(text, padding=padding, max_length=20, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + num_padding = 20 - len(expected_tokens) + self.assertEqual(tokens["input_ids"], num_padding * [self.tokenizer.pad_token_id] + expected_tokens) + self.assertEqual(tokens["attention_mask"], num_padding * [0] + [1] * len(expected_tokens)) + self.assertEqual( + tokens["special_tokens_mask"], num_padding * [1] + [1] + [0] * (len(expected_tokens) - 2) + [1] + ) + + # Test 3: + # pad_to_multiple_of + tokens = self.tokenizer( + text, padding=True, max_length=20, pad_to_multiple_of=16, return_special_tokens_mask=True + ) + self.assertIsInstance(tokens, BatchEncoding) + num_padding = 16 - len(expected_tokens) + self.assertEqual(tokens["input_ids"], num_padding * [self.tokenizer.pad_token_id] + expected_tokens) + self.assertEqual(tokens["attention_mask"], num_padding * [0] + [1] * len(expected_tokens)) + self.assertEqual( + tokens["special_tokens_mask"], num_padding * [1] + [1] + [0] * (len(expected_tokens) - 2) + [1] + ) + + # Test 4: + # padding="max_length" and padding_side="right" + tokens = self.tokenizer( + text, padding="max_length", max_length=20, padding_side="right", return_special_tokens_mask=True + ) + self.assertIsInstance(tokens, BatchEncoding) + num_padding = 20 - len(expected_tokens) + self.assertEqual(tokens["input_ids"], expected_tokens + num_padding * [self.tokenizer.pad_token_id]) + self.assertEqual(tokens["attention_mask"], [1] * len(expected_tokens) + num_padding * [0]) + self.assertEqual( + tokens["special_tokens_mask"], [1] + [0] * (len(expected_tokens) - 2) + [1] + num_padding * [1] + ) + + def test_batch_call(self): + # Test 1: + # default case + text = ["Hello world!", "Hello world! Longer"] + expected_tokens = [self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(t, bos=True, eos=True) for t in text] + tokens = self.tokenizer(text) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [[1] * len(t) for t in expected_tokens]) + + # Test 2: + # return_attention_mask=False + tokens = self.tokenizer(text, return_attention_mask=False) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertNotIn("attention_mask", tokens) + + # Test 3: + # return_tensors="pt" + tokens = self.tokenizer(text, return_tensors="pt", padding="longest", return_special_tokens_mask=True) + self.assertIsInstance(tokens["input_ids"], torch.Tensor) + self.assertEqual(tokens["input_ids"].shape, torch.Size([2, len(expected_tokens[1])])) + self.assertTrue( + torch.equal( + tokens["input_ids"][0], + torch.Tensor( + (len(expected_tokens[1]) - len(expected_tokens[0])) + * [self.ref_tokenizer.instruct_tokenizer.tokenizer.pad_id] + + expected_tokens[0] + ), + ) + ) + self.assertIsInstance(tokens["attention_mask"], torch.Tensor) + self.assertEqual(tokens["attention_mask"].shape, torch.Size([2, len(expected_tokens[1])])) + self.assertTrue( + torch.equal( + tokens["attention_mask"][0], + torch.Tensor( + [0] * (len(expected_tokens[1]) - len(expected_tokens[0])) + [1] * len(expected_tokens[0]) + ), + ) + ) + self.assertTrue(torch.equal(tokens["attention_mask"][1], torch.Tensor([1] * len(expected_tokens[1])))) + self.assertIsInstance(tokens["special_tokens_mask"], torch.Tensor) + self.assertEqual(tokens["special_tokens_mask"].shape, torch.Size([2, len(expected_tokens[1])])) + self.assertTrue( + torch.equal( + tokens["special_tokens_mask"][0], + torch.Tensor( + (len(expected_tokens[1]) - len(expected_tokens[0])) * [1] + + [1] + + [0] * (len(expected_tokens[0]) - 2) + + [1] + ), + ) + ) + self.assertTrue( + torch.equal( + tokens["special_tokens_mask"][1], torch.Tensor([1] + [0] * (len(expected_tokens[1]) - 2) + [1]) + ) + ) + + # Test 4: + # add_special_tokens=False + expected_tokens = [ + self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(t, bos=False, eos=False) for t in text + ] + tokens = self.tokenizer(text, add_special_tokens=False, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [[1] * len(t) for t in expected_tokens]) + self.assertEqual(tokens["special_tokens_mask"], [[0] * len(t) for t in expected_tokens]) + + def test_batch_call_with_truncation(self): + # Test 1: + # truncation=True + text = ["Hello world!", "Hello world! Longer" * 10] + expected_tokens = [self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(t, bos=True, eos=True) for t in text] + + for truncation in [True, "longest_first", TruncationStrategy.LONGEST_FIRST]: + tokens = self.tokenizer(text, truncation=True, max_length=10, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], [expected_tokens[0][:10], expected_tokens[1][:10]]) + self.assertEqual(tokens["attention_mask"], [[1] * min(len(t), 10) for t in expected_tokens]) + self.assertEqual( + tokens["special_tokens_mask"], + [[1 if id in self.ref_special_ids else 0 for id in ids[:10]] for ids in expected_tokens], + ) + + # Test 2: + # truncation=False + for truncation in [False, "do_not_truncate", TruncationStrategy.DO_NOT_TRUNCATE]: + tokens = self.tokenizer(text, truncation=truncation, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [[1] * len(t) for t in expected_tokens]) + self.assertEqual( + tokens["special_tokens_mask"], + [[1] + [0] * (len(t) - 2) + [1] for t in expected_tokens], + ) + + # Test 3: + # truncation=True or "longest_first" or TruncationStrategy.LONGEST_FIRST with return_overflowing_tokens=True and stride + + for truncation in [True, "longest_first", TruncationStrategy.LONGEST_FIRST]: + for stride in [0, 2]: + tokens = self.tokenizer( + text, + truncation=truncation, + max_length=10, + return_overflowing_tokens=True, + return_special_tokens_mask=True, + stride=stride, + ) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], [expected_tokens[0][:10], expected_tokens[1][:10]]) + self.assertEqual(tokens["attention_mask"], [[1] * min(len(t), 10) for t in expected_tokens]) + self.assertEqual( + tokens["overflowing_tokens"], + [expected_tokens[0][10 - stride :], expected_tokens[1][10 - stride :]], + ) + self.assertEqual( + tokens["num_truncated_tokens"], [len(expected_tokens[0]) - 10, len(expected_tokens[1]) - 10] + ) + self.assertEqual( + tokens["special_tokens_mask"], + [[1 if id in self.ref_special_ids else 0 for id in ids[:10]] for ids in expected_tokens], + ) + + def test_batch_call_with_padding(self): + # Test 1: + # padding=False or padding=True or "do_not_pad" or PaddingStrategy.DO_NOT_PAD or padding="longest" or PaddingStrategy.LONGEST + text = ["Hello world!", "Hello world! Longer"] + expected_tokens = [self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(t, bos=True, eos=True) for t in text] + for padding in [False, "do_not_pad", PaddingStrategy.DO_NOT_PAD]: + tokens = self.tokenizer(text, padding=padding, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual(tokens["input_ids"], expected_tokens) + self.assertEqual(tokens["attention_mask"], [[1] * len(t) for t in expected_tokens]) + self.assertEqual( + tokens["special_tokens_mask"], + [[1] + [0] * (len(t) - 2) + [1] for t in expected_tokens], + ) + + # Test 2: + # padding="max_length" or PaddingStrategy.MAX_LENGTH + for padding in ["max_length", PaddingStrategy.MAX_LENGTH]: + tokens = self.tokenizer(text, padding=padding, max_length=20, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + num_padding = [20 - len(t) for t in expected_tokens] + self.assertEqual( + tokens["input_ids"], + [ + num_padding[0] * [self.tokenizer.pad_token_id] + expected_tokens[0], + num_padding[1] * [self.tokenizer.pad_token_id] + expected_tokens[1], + ], + ) + self.assertEqual( + tokens["attention_mask"], + [ + num_padding[0] * [0] + [1] * len(expected_tokens[0]), + num_padding[1] * [0] + [1] * len(expected_tokens[1]), + ], + ) + self.assertEqual( + tokens["special_tokens_mask"], + [ + num_padding[0] * [1] + [1] + [0] * (len(expected_tokens[0]) - 2) + [1], + num_padding[1] * [1] + [1] + [0] * (len(expected_tokens[1]) - 2) + [1], + ], + ) + + # Test 3: + # padding=True or "longest" or PaddingStrategy.LONGEST + for padding in [True, "longest", PaddingStrategy.LONGEST]: + tokens = self.tokenizer(text, padding=padding, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + num_padding = [len(expected_tokens[1]) - len(t) for t in expected_tokens] + self.assertEqual( + tokens["input_ids"], + [ + num_padding[0] * [self.tokenizer.pad_token_id] + expected_tokens[0], + num_padding[1] * [self.tokenizer.pad_token_id] + expected_tokens[1], + ], + ) + self.assertEqual( + tokens["attention_mask"], + [ + num_padding[0] * [0] + [1] * len(expected_tokens[0]), + num_padding[1] * [0] + [1] * len(expected_tokens[1]), + ], + ) + self.assertEqual( + tokens["special_tokens_mask"], + [ + num_padding[0] * [1] + [1] + [0] * (len(expected_tokens[0]) - 2) + [1], + num_padding[1] * [1] + [1] + [0] * (len(expected_tokens[1]) - 2) + [1], + ], + ) + + # Test 4: + # pad_to_multiple_of + tokens = self.tokenizer( + text, padding=True, max_length=32, pad_to_multiple_of=16, return_special_tokens_mask=True + ) + self.assertIsInstance(tokens, BatchEncoding) + num_padding = [16 - len(t) for t in expected_tokens] + self.assertEqual( + tokens["input_ids"], + [ + num_padding[0] * [self.tokenizer.pad_token_id] + expected_tokens[0], + num_padding[1] * [self.tokenizer.pad_token_id] + expected_tokens[1], + ], + ) + self.assertEqual( + tokens["attention_mask"], + [ + num_padding[0] * [0] + [1] * len(expected_tokens[0]), + num_padding[1] * [0] + [1] * len(expected_tokens[1]), + ], + ) + self.assertEqual( + tokens["special_tokens_mask"], + [ + num_padding[0] * [1] + [1] + [0] * (len(expected_tokens[0]) - 2) + [1], + num_padding[1] * [1] + [1] + [0] * (len(expected_tokens[1]) - 2) + [1], + ], + ) + + # Test 5: + # padding="max_length" or PaddingStrategy.MAX_LENGTH and padding_side="right" + for padding in ["max_length", PaddingStrategy.MAX_LENGTH]: + tokens = self.tokenizer( + text, padding=padding, max_length=20, padding_side="right", return_special_tokens_mask=True + ) + self.assertIsInstance(tokens, BatchEncoding) + num_padding = [20 - len(t) for t in expected_tokens] + self.assertEqual( + tokens["input_ids"], + [ + expected_tokens[0] + num_padding[0] * [self.tokenizer.pad_token_id], + expected_tokens[1] + num_padding[1] * [self.tokenizer.pad_token_id], + ], + ) + self.assertEqual( + tokens["attention_mask"], + [ + [1] * len(expected_tokens[0]) + num_padding[0] * [0], + [1] * len(expected_tokens[1]) + num_padding[1] * [0], + ], + ) + self.assertEqual( + tokens["special_tokens_mask"], + [ + [1] + [0] * (len(expected_tokens[0]) - 2) + [1] + num_padding[0] * [1], + [1] + [0] * (len(expected_tokens[1]) - 2) + [1] + num_padding[1] * [1], + ], + ) + + def test_batch_call_with_padding_and_truncation(self): + # Test 1: + # padding=True or "longest" or PaddingStrategy.LONGEST or "max_length" or PaddingStragy.MAX_LENGTH + # and truncation=True or "longest_first" or TruncationStrategy.LONGEST_FIRST + # and max_length + text = ["Hello world!", "Hello world! Longer" * 10] + expected_tokens = [self.ref_tokenizer.instruct_tokenizer.tokenizer.encode(t, bos=True, eos=True) for t in text] + for padding in [True, "longest", PaddingStrategy.LONGEST, "max_length", PaddingStrategy.MAX_LENGTH]: + for truncation in [True, "longest_first", TruncationStrategy.LONGEST_FIRST]: + tokens = self.tokenizer( + text, padding=padding, truncation=truncation, max_length=10, return_special_tokens_mask=True + ) + num_padding = [max(0, 10 - len(t)) for t in expected_tokens] + self.assertIsInstance(tokens, BatchEncoding) + self.assertEqual( + tokens["input_ids"], + [num_padding[i] * [self.tokenizer.pad_token_id] + t[:10] for i, t in enumerate(expected_tokens)], + ) + self.assertEqual( + tokens["attention_mask"], + [num_padding[i] * [0] + [1] * min(len(t), 10) for i, t in enumerate(expected_tokens)], + ) + self.assertEqual( + tokens["special_tokens_mask"], + [ + num_padding[i] * [1] + [1 if id in self.ref_special_ids else 0 for id in ids[:10]] + for i, ids in enumerate(expected_tokens) + ], + ) + + # Test 2: + # padding=True or "longest" or PaddingStrategy.LONGEST and truncation=True or "longest_first" or TruncationStrategy.LONGEST_FIRST + # and no max_length + for padding in ["longest", PaddingStrategy.LONGEST]: + for truncation in [True, "longest_first", TruncationStrategy.LONGEST_FIRST]: + tokens = self.tokenizer(text, padding=padding, truncation=truncation, return_special_tokens_mask=True) + self.assertIsInstance(tokens, BatchEncoding) + num_padding = [max(len(t) for t in expected_tokens) - len(t) for t in expected_tokens] + self.assertEqual( + tokens["input_ids"], + [num_padding[i] * [self.tokenizer.pad_token_id] + t for i, t in enumerate(expected_tokens)], + ) + self.assertEqual( + tokens["attention_mask"], + [num_padding[i] * [0] + [1] * len(t) for i, t in enumerate(expected_tokens)], + ) + self.assertEqual( + tokens["special_tokens_mask"], + [ + num_padding[i] * [1] + [1 if id in self.ref_special_ids else 0 for id in ids] + for i, ids in enumerate(expected_tokens) + ], + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_training_args.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_training_args.py new file mode 100644 index 0000000000000000000000000000000000000000..c207196abc8c8d042c854ea0bd05acb7c21d7aca --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_training_args.py @@ -0,0 +1,67 @@ +import os +import tempfile +import unittest + +from transformers import TrainingArguments + + +class TestTrainingArguments(unittest.TestCase): + def test_default_output_dir(self): + """Test that output_dir defaults to 'trainer_output' when not specified.""" + args = TrainingArguments(output_dir=None) + self.assertEqual(args.output_dir, "trainer_output") + + def test_custom_output_dir(self): + """Test that output_dir is respected when specified.""" + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(output_dir=tmp_dir) + self.assertEqual(args.output_dir, tmp_dir) + + def test_output_dir_creation(self): + """Test that output_dir is created only when needed.""" + with tempfile.TemporaryDirectory() as tmp_dir: + output_dir = os.path.join(tmp_dir, "test_output") + + # Directory should not exist before creating args + self.assertFalse(os.path.exists(output_dir)) + + # Create args with save_strategy="no" - should not create directory + args = TrainingArguments( + output_dir=output_dir, + do_train=True, + save_strategy="no", + report_to=None, + ) + self.assertFalse(os.path.exists(output_dir)) + + # Now set save_strategy="steps" - should create directory when needed + args.save_strategy = "steps" + args.save_steps = 1 + self.assertFalse(os.path.exists(output_dir)) # Still shouldn't exist + + # Directory should be created when actually needed (e.g. in Trainer) + + def test_torch_empty_cache_steps_requirements(self): + """Test that torch_empty_cache_steps is a positive integer or None.""" + + # None is acceptable (feature is disabled): + args = TrainingArguments(torch_empty_cache_steps=None) + self.assertIsNone(args.torch_empty_cache_steps) + + # non-int is unacceptable: + with self.assertRaises(ValueError): + TrainingArguments(torch_empty_cache_steps=1.0) + with self.assertRaises(ValueError): + TrainingArguments(torch_empty_cache_steps="none") + + # negative int is unacceptable: + with self.assertRaises(ValueError): + TrainingArguments(torch_empty_cache_steps=-1) + + # zero is unacceptable: + with self.assertRaises(ValueError): + TrainingArguments(torch_empty_cache_steps=0) + + # positive int is acceptable: + args = TrainingArguments(torch_empty_cache_steps=1) + self.assertEqual(args.torch_empty_cache_steps, 1) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_video_processing_common.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_video_processing_common.py new file mode 100644 index 0000000000000000000000000000000000000000..5f8f378c12cc978260ee5a72754f7bde57ae50d7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/test_video_processing_common.py @@ -0,0 +1,490 @@ +# coding=utf-8 +# Copyright 2025 HuggingFace 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. + +import inspect +import json +import os +import tempfile +import warnings +from copy import deepcopy + +import numpy as np +import pytest +from packaging import version + +from transformers import AutoVideoProcessor +from transformers.testing_utils import ( + check_json_file_has_correct_format, + require_torch, + require_torch_accelerator, + require_vision, + slow, + torch_device, +) +from transformers.utils import is_torch_available, is_vision_available + + +if is_torch_available(): + import torch + +if is_vision_available(): + from PIL import Image + + +def prepare_video(num_frames, num_channels, width=10, height=10, return_tensors="pil"): + """This function prepares a video as a list of PIL images/NumPy arrays/PyTorch tensors.""" + + video = [] + for i in range(num_frames): + video.append(np.random.randint(255, size=(width, height, num_channels), dtype=np.uint8)) + + if return_tensors == "pil": + # PIL expects the channel dimension as last dimension + video = [Image.fromarray(frame) for frame in video] + elif return_tensors == "torch": + # Torch images are typically in channels first format + video = torch.tensor(video).permute(0, 3, 1, 2) + elif return_tensors == "np": + # Numpy images are typically in channels last format + video = np.array(video) + + return video + + +def prepare_video_inputs( + batch_size, + num_frames, + num_channels, + min_resolution, + max_resolution, + equal_resolution=False, + return_tensors="pil", +): + """This function prepares a batch of videos: a list of list of PIL images, or a list of list of numpy arrays if + one specifies return_tensors="np", or a list of list of PyTorch tensors if one specifies return_tensors="torch". + + One can specify whether the videos are of the same resolution or not. + """ + + video_inputs = [] + for i in range(batch_size): + if equal_resolution: + width = height = max_resolution + else: + width, height = np.random.choice(np.arange(min_resolution, max_resolution), 2) + video = prepare_video( + num_frames=num_frames, + num_channels=num_channels, + width=width, + height=height, + return_tensors=return_tensors, + ) + video_inputs.append(video) + + return video_inputs + + +class VideoProcessingTestMixin: + test_cast_dtype = None + fast_video_processing_class = None + video_processor_list = None + input_name = "pixel_values_videos" + + def setUp(self): + video_processor_list = [] + + if self.fast_video_processing_class: + video_processor_list.append(self.fast_video_processing_class) + + self.video_processor_list = video_processor_list + + def test_video_processor_to_json_string(self): + for video_processing_class in self.video_processor_list: + video_processor = video_processing_class(**self.video_processor_dict) + obj = json.loads(video_processor.to_json_string()) + for key, value in self.video_processor_dict.items(): + self.assertEqual(obj[key], value) + + def test_video_processor_to_json_file(self): + for video_processing_class in self.video_processor_list: + video_processor_first = video_processing_class(**self.video_processor_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + json_file_path = os.path.join(tmpdirname, "video_processor.json") + video_processor_first.to_json_file(json_file_path) + video_processor_second = video_processing_class.from_json_file(json_file_path) + + self.assertEqual(video_processor_second.to_dict(), video_processor_first.to_dict()) + + def test_video_processor_from_dict_with_kwargs(self): + video_processor = self.fast_video_processing_class.from_dict(self.video_processor_dict) + self.assertEqual(video_processor.size, {"shortest_edge": 20}) + self.assertEqual(video_processor.crop_size, {"height": 18, "width": 18}) + + video_processor = self.fast_video_processing_class.from_dict(self.video_processor_dict, size=42, crop_size=84) + self.assertEqual(video_processor.size, {"shortest_edge": 42}) + self.assertEqual(video_processor.crop_size, {"height": 84, "width": 84}) + + def test_video_processor_from_and_save_pretrained(self): + for video_processing_class in self.video_processor_list: + video_processor_first = video_processing_class(**self.video_processor_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = video_processor_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + video_processor_second = video_processing_class.from_pretrained(tmpdirname) + + self.assertEqual(video_processor_second.to_dict(), video_processor_first.to_dict()) + + def test_video_processor_save_load_with_autovideoprocessor(self): + for video_processing_class in self.video_processor_list: + video_processor_first = video_processing_class(**self.video_processor_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + saved_file = video_processor_first.save_pretrained(tmpdirname)[0] + check_json_file_has_correct_format(saved_file) + + use_fast = video_processing_class.__name__.endswith("Fast") + video_processor_second = AutoVideoProcessor.from_pretrained(tmpdirname, use_fast=use_fast) + + self.assertEqual(video_processor_second.to_dict(), video_processor_first.to_dict()) + + def test_init_without_params(self): + for video_processing_class in self.video_processor_list: + video_processor = video_processing_class() + self.assertIsNotNone(video_processor) + + @slow + @require_torch_accelerator + @require_vision + @pytest.mark.torch_compile_test + def test_can_compile_fast_video_processor(self): + if self.fast_video_processing_class is None: + self.skipTest("Skipping compilation test as fast video processor is not defined") + if version.parse(torch.__version__) < version.parse("2.3"): + self.skipTest(reason="This test requires torch >= 2.3 to run.") + + torch.compiler.reset() + video_inputs = self.video_processor_tester.prepare_video_inputs(equal_resolution=False, return_tensors="torch") + video_processor = self.fast_video_processing_class(**self.video_processor_dict) + output_eager = video_processor(video_inputs, device=torch_device, do_sample_frames=False, return_tensors="pt") + + video_processor = torch.compile(video_processor, mode="reduce-overhead") + output_compiled = video_processor( + video_inputs, device=torch_device, do_sample_frames=False, return_tensors="pt" + ) + + torch.testing.assert_close( + output_eager[self.input_name], output_compiled[self.input_name], rtol=1e-4, atol=1e-4 + ) + + @require_torch + @require_vision + def test_cast_dtype_device(self): + for video_processing_class in self.video_processor_list: + if self.test_cast_dtype is not None: + # Initialize video_processor + video_processor = video_processing_class(**self.video_processor_dict) + + # create random PyTorch tensors + video_inputs = self.video_processor_tester.prepare_video_inputs( + equal_resolution=False, return_tensors="torch" + ) + + encoding = video_processor(video_inputs, return_tensors="pt") + + self.assertEqual(encoding[self.input_name].device, torch.device("cpu")) + self.assertEqual(encoding[self.input_name].dtype, torch.float32) + + encoding = video_processor(video_inputs, return_tensors="pt").to(torch.float16) + self.assertEqual(encoding[self.input_name].device, torch.device("cpu")) + self.assertEqual(encoding[self.input_name].dtype, torch.float16) + + encoding = video_processor(video_inputs, return_tensors="pt").to("cpu", torch.bfloat16) + self.assertEqual(encoding[self.input_name].device, torch.device("cpu")) + self.assertEqual(encoding[self.input_name].dtype, torch.bfloat16) + + with self.assertRaises(TypeError): + _ = video_processor(video_inputs, return_tensors="pt").to(torch.bfloat16, "cpu") + + # Try with text + video feature + encoding = video_processor(video_inputs, return_tensors="pt") + encoding.update({"input_ids": torch.LongTensor([[1, 2, 3], [4, 5, 6]])}) + encoding = encoding.to(torch.float16) + + self.assertEqual(encoding[self.input_name].device, torch.device("cpu")) + self.assertEqual(encoding[self.input_name].dtype, torch.float16) + self.assertEqual(encoding.input_ids.dtype, torch.long) + + def test_call_pil(self): + for video_processing_class in self.video_processor_list: + # Initialize video_processing + video_processing = video_processing_class(**self.video_processor_dict) + video_inputs = self.video_processor_tester.prepare_video_inputs(equal_resolution=False) + + # Each video is a list of PIL Images + for video in video_inputs: + self.assertIsInstance(video[0], Image.Image) + + # Test not batched input + encoded_videos = video_processing(video_inputs[0], return_tensors="pt")[self.input_name] + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape([video_inputs[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = video_processing(video_inputs, return_tensors="pt")[self.input_name] + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape(video_inputs) + self.assertEqual( + tuple(encoded_videos.shape), (self.video_processor_tester.batch_size, *expected_output_video_shape) + ) + + def test_call_numpy(self): + for video_processing_class in self.video_processor_list: + # Initialize video_processing + video_processing = video_processing_class(**self.video_processor_dict) + # create random numpy tensors + video_inputs = self.video_processor_tester.prepare_video_inputs( + equal_resolution=False, return_tensors="np" + ) + for video in video_inputs: + self.assertIsInstance(video, np.ndarray) + + # Test not batched input + encoded_videos = video_processing(video_inputs[0], return_tensors="pt")[self.input_name] + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape([video_inputs[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = video_processing(video_inputs, return_tensors="pt")[self.input_name] + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape(video_inputs) + self.assertEqual( + tuple(encoded_videos.shape), (self.video_processor_tester.batch_size, *expected_output_video_shape) + ) + + def test_call_pytorch(self): + for video_processing_class in self.video_processor_list: + # Initialize video_processing + video_processing = video_processing_class(**self.video_processor_dict) + # create random PyTorch tensors + video_inputs = self.video_processor_tester.prepare_video_inputs( + equal_resolution=False, return_tensors="torch" + ) + + for video in video_inputs: + self.assertIsInstance(video, torch.Tensor) + + # Test not batched input + encoded_videos = video_processing(video_inputs[0], return_tensors="pt")[self.input_name] + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape([video_inputs[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape(video_inputs) + encoded_videos = video_processing(video_inputs, return_tensors="pt")[self.input_name] + self.assertEqual( + tuple(encoded_videos.shape), + (self.video_processor_tester.batch_size, *expected_output_video_shape), + ) + + def test_call_sample_frames(self): + for video_processing_class in self.video_processor_list: + video_processing = video_processing_class(**self.video_processor_dict) + + prev_num_frames = self.video_processor_tester.num_frames + self.video_processor_tester.num_frames = 8 + video_inputs = self.video_processor_tester.prepare_video_inputs( + equal_resolution=False, + return_tensors="torch", + ) + + # Force set sampling to False. No sampling is expected even when `num_frames` exists + video_processing.do_sample_frames = False + + encoded_videos = video_processing(video_inputs[0], return_tensors="pt", num_frames=3)[self.input_name] + encoded_videos_batched = video_processing(video_inputs, return_tensors="pt", num_frames=3)[self.input_name] + self.assertEqual(encoded_videos.shape[1], 8) + self.assertEqual(encoded_videos_batched.shape[1], 8) + + # Set sampling to True. Video frames should be sampled with `num_frames` in the output + video_processing.do_sample_frames = True + + encoded_videos = video_processing(video_inputs[0], return_tensors="pt", num_frames=3)[self.input_name] + encoded_videos_batched = video_processing(video_inputs, return_tensors="pt", num_frames=3)[self.input_name] + self.assertEqual(encoded_videos.shape[1], 3) + self.assertEqual(encoded_videos_batched.shape[1], 3) + + # Sample with `fps` requires metadata to infer number of frames from total duration + with self.assertRaises(ValueError): + encoded_videos = video_processing(video_inputs[0], return_tensors="pt", fps=3)[self.input_name] + encoded_videos_batched = video_processing(video_inputs, return_tensors="pt", fps=3)[self.input_name] + + metadata = [[{"duration": 2.0, "total_num_frames": 8, "fps": 4}]] + batched_metadata = metadata * len(video_inputs) + encoded_videos = video_processing(video_inputs[0], return_tensors="pt", fps=3, video_metadata=metadata)[ + self.input_name + ] + encoded_videos_batched = video_processing( + video_inputs, return_tensors="pt", fps=3, video_metadata=batched_metadata + )[self.input_name] + self.assertEqual(encoded_videos.shape[1], 6) + self.assertEqual(encoded_videos_batched.shape[1], 6) + + # We should raise error when asked to sample more frames than there are in input video + with self.assertRaises(ValueError): + encoded_videos = video_processing(video_inputs[0], return_tensors="pt", num_frames=10)[self.input_name] + encoded_videos_batched = video_processing(video_inputs, return_tensors="pt", num_frames=10)[ + self.input_name + ] + + # Assign back the actual num frames in tester + self.video_processor_tester.num_frames = prev_num_frames + + def test_nested_input(self): + """Tests that the processor can work with nested list where each video is a list of arrays""" + for video_processing_class in self.video_processor_list: + video_processing = video_processing_class(**self.video_processor_dict) + video_inputs = self.video_processor_tester.prepare_video_inputs( + equal_resolution=False, return_tensors="np" + ) + + # Test not batched input + video_inputs = [list(video) for video in video_inputs] + encoded_videos = video_processing(video_inputs[0], return_tensors="pt")[self.input_name] + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape([video_inputs[0]]) + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape(video_inputs) + encoded_videos = video_processing(video_inputs, return_tensors="pt")[self.input_name] + self.assertEqual( + tuple(encoded_videos.shape), + (self.video_processor_tester.batch_size, *expected_output_video_shape), + ) + + def test_call_numpy_4_channels(self): + for video_processing_class in self.video_processor_list: + # Test that can process videos which have an arbitrary number of channels + # Initialize video_processing + video_processor = video_processing_class(**self.video_processor_dict) + + # create random numpy tensors + self.video_processor_tester.num_channels = 4 + video_inputs = self.video_processor_tester.prepare_video_inputs( + equal_resolution=False, return_tensors="pil" + ) + + # Test not batched input + encoded_videos = video_processor( + video_inputs[0], + return_tensors="pt", + input_data_format="channels_last", + image_mean=0, + image_std=1, + )[self.input_name] + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape([video_inputs[0]]) + if video_processor.do_convert_rgb: + expected_output_video_shape = list(expected_output_video_shape) + expected_output_video_shape[1] = 3 + self.assertEqual(tuple(encoded_videos.shape), (1, *expected_output_video_shape)) + + # Test batched + encoded_videos = video_processor( + video_inputs, + return_tensors="pt", + input_data_format="channels_last", + image_mean=0, + image_std=1, + )[self.input_name] + expected_output_video_shape = self.video_processor_tester.expected_output_video_shape(video_inputs) + if video_processor.do_convert_rgb: + expected_output_video_shape = list(expected_output_video_shape) + expected_output_video_shape[1] = 3 + self.assertEqual( + tuple(encoded_videos.shape), (self.video_processor_tester.batch_size, *expected_output_video_shape) + ) + + def test_video_processor_preprocess_arguments(self): + is_tested = False + + for video_processing_class in self.video_processor_list: + video_processor = video_processing_class(**self.video_processor_dict) + + # validation done by _valid_processor_keys attribute + if hasattr(video_processor, "_valid_processor_keys") and hasattr(video_processor, "preprocess"): + preprocess_parameter_names = inspect.getfullargspec(video_processor.preprocess).args + preprocess_parameter_names.remove("self") + preprocess_parameter_names.sort() + valid_processor_keys = video_processor._valid_processor_keys + valid_processor_keys.sort() + self.assertEqual(preprocess_parameter_names, valid_processor_keys) + is_tested = True + + # validation done by @filter_out_non_signature_kwargs decorator + if hasattr(video_processor.preprocess, "_filter_out_non_signature_kwargs"): + if hasattr(self.video_processor_tester, "prepare_video_inputs"): + inputs = self.video_processor_tester.prepare_video_inputs() + elif hasattr(self.video_processor_tester, "prepare_video_inputs"): + inputs = self.video_processor_tester.prepare_video_inputs() + else: + self.skipTest(reason="No valid input preparation method found") + + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter("always") + video_processor(inputs, extra_argument=True) + + messages = " ".join([str(w.message) for w in raised_warnings]) + self.assertGreaterEqual(len(raised_warnings), 1) + self.assertIn("extra_argument", messages) + is_tested = True + + if not is_tested: + self.skipTest(reason="No validation found for `preprocess` method") + + def test_override_instance_attributes_does_not_affect_other_instances(self): + if self.fast_video_processing_class is None: + self.skipTest( + "Only testing fast video processor, as most slow processors break this test and are to be deprecated" + ) + + video_processing_class = self.fast_video_processing_class + video_processor_1 = video_processing_class() + video_processor_2 = video_processing_class() + if not (hasattr(video_processor_1, "size") and isinstance(video_processor_1.size, dict)) or not ( + hasattr(video_processor_1, "image_mean") and isinstance(video_processor_1.image_mean, list) + ): + self.skipTest( + reason="Skipping test as the image processor does not have dict size or list image_mean attributes" + ) + + original_size_2 = deepcopy(video_processor_2.size) + for key in video_processor_1.size: + video_processor_1.size[key] = -1 + modified_copied_size_1 = deepcopy(video_processor_1.size) + + original_image_mean_2 = deepcopy(video_processor_2.image_mean) + video_processor_1.image_mean[0] = -1 + modified_copied_image_mean_1 = deepcopy(video_processor_1.image_mean) + + # check that the original attributes of the second instance are not affected + self.assertEqual(video_processor_2.size, original_size_2) + self.assertEqual(video_processor_2.image_mean, original_image_mean_2) + + for key in video_processor_2.size: + video_processor_2.size[key] = -2 + video_processor_2.image_mean[0] = -2 + + # check that the modified attributes of the first instance are not affected by the second instance + self.assertEqual(video_processor_1.size, modified_copied_size_1) + self.assertEqual(video_processor_1.image_mean, modified_copied_image_mean_1) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tokenization/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tokenization/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tokenization/test_tokenization_fast.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tokenization/test_tokenization_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..903dc0c67a2ed5d736c9ef4a021d5cfee1bb01c3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tokenization/test_tokenization_fast.py @@ -0,0 +1,272 @@ +# Copyright 2019 HuggingFace 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. + +import concurrent.futures +import json +import os +import shutil +import tempfile +import unittest + +from transformers import AutoTokenizer, LlamaTokenizerFast, PreTrainedTokenizerFast +from transformers.testing_utils import require_tokenizers + +from ..test_tokenization_common import TokenizerTesterMixin + + +@require_tokenizers +class PreTrainedTokenizationFastTest(TokenizerTesterMixin, unittest.TestCase): + rust_tokenizer_class = PreTrainedTokenizerFast + test_slow_tokenizer = False + test_rust_tokenizer = True + from_pretrained_vocab_key = "tokenizer_file" + + @classmethod + def setUpClass(cls): + cls.test_rust_tokenizer = False # because we don't have pretrained_vocab_files_map + super().setUpClass() + cls.test_rust_tokenizer = True + + model_paths = ["robot-test/dummy-tokenizer-fast", "robot-test/dummy-tokenizer-wordlevel"] + cls.bytelevel_bpe_model_name = "SaulLu/dummy-tokenizer-bytelevel-bpe" + + # Inclusion of 2 tokenizers to test different types of models (Unigram and WordLevel for the moment) + cls.tokenizers_list = [(PreTrainedTokenizerFast, model_path, {}) for model_path in model_paths] + + tokenizer = PreTrainedTokenizerFast.from_pretrained(model_paths[0]) + tokenizer.save_pretrained(cls.tmpdirname) + + @unittest.skip( + "We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any model" + ) + def test_tokenizer_mismatch_warning(self): + pass + + @unittest.skip( + "We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any model" + ) + def test_encode_decode_with_spaces(self): + pass + + @unittest.skip( + "We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any model" + ) + def test_added_tokens_serialization(self): + pass + + @unittest.skip( + "We disable this test for PreTrainedTokenizerFast because it is the only tokenizer that is not linked to any model" + ) + def test_additional_special_tokens_serialization(self): + pass + + @unittest.skip(reason="PreTrainedTokenizerFast is the only tokenizer that is not linked to any model") + def test_prepare_for_model(self): + pass + + @unittest.skip(reason="PreTrainedTokenizerFast doesn't have tokenizer_file in its signature") + def test_rust_tokenizer_signature(self): + pass + + def test_training_new_tokenizer(self): + tmpdirname_orig = self.tmpdirname + # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel. + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + try: + self.tmpdirname = tempfile.mkdtemp() + tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + tokenizer.save_pretrained(self.tmpdirname) + super().test_training_new_tokenizer() + finally: + # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer + # is restored + shutil.rmtree(self.tmpdirname) + self.tmpdirname = tmpdirname_orig + + def test_training_new_tokenizer_with_special_tokens_change(self): + tmpdirname_orig = self.tmpdirname + # Here we want to test the 2 available tokenizers that use 2 different types of models: Unigram and WordLevel. + for tokenizer, pretrained_name, kwargs in self.tokenizers_list: + with self.subTest(f"{tokenizer.__class__.__name__} ({pretrained_name})"): + try: + self.tmpdirname = tempfile.mkdtemp() + tokenizer = self.rust_tokenizer_class.from_pretrained(pretrained_name, **kwargs) + + tokenizer.save_pretrained(self.tmpdirname) + super().test_training_new_tokenizer_with_special_tokens_change() + finally: + # Even if the test fails, we must be sure that the folder is deleted and that the default tokenizer + # is restored + shutil.rmtree(self.tmpdirname) + self.tmpdirname = tmpdirname_orig + + def test_training_new_tokenizer_with_bytelevel(self): + tokenizer = self.rust_tokenizer_class.from_pretrained(self.bytelevel_bpe_model_name) + + toy_text_iterator = ("a" for _ in range(1000)) + new_tokenizer = tokenizer.train_new_from_iterator(text_iterator=toy_text_iterator, length=1000, vocab_size=50) + + encoding_ids = new_tokenizer.encode("a🤗") + self.assertEqual(encoding_ids, [64, 172, 253, 97, 245]) + + def test_init_from_tokenizers_model(self): + from tokenizers import Tokenizer + + sentences = ["Hello, y'all!", "How are you 😁 ? There should not be any issue right?"] + + tokenizer = Tokenizer.from_pretrained("google-t5/t5-base") + # Enable padding + tokenizer.enable_padding(pad_id=0, pad_token="", length=512, pad_to_multiple_of=8) + self.assertEqual( + tokenizer.padding, + { + "length": 512, + "pad_to_multiple_of": 8, + "pad_id": 0, + "pad_token": "", + "pad_type_id": 0, + "direction": "right", + }, + ) + fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer) + tmpdirname = tempfile.mkdtemp() + fast_tokenizer.save_pretrained(tmpdirname) + fast_from_saved = PreTrainedTokenizerFast.from_pretrained(tmpdirname) + for tok in [fast_tokenizer, fast_from_saved]: + self.assertEqual(tok.pad_token_id, 0) + self.assertEqual(tok.padding_side, "right") + self.assertEqual(tok.pad_token, "") + self.assertEqual(tok.init_kwargs["max_length"], 512) + self.assertEqual(tok.init_kwargs["pad_to_multiple_of"], 8) + self.assertEqual(tok(sentences, padding = True), {'input_ids': [[8774, 6, 3, 63, 31, 1748, 55, 1, 0, 0, 0, 0,0, 0, 0, 0],[ 571, 33, 25, 3, 2, 3, 58, 290, 225, 59, 36, 136, 962, 269, 58, 1]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0],[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]}) # fmt: skip + + tokenizer.enable_truncation(8, stride=0, strategy="longest_first", direction="right") + self.assertEqual( + tokenizer.truncation, {"max_length": 8, "stride": 0, "strategy": "longest_first", "direction": "right"} + ) + fast_tokenizer = PreTrainedTokenizerFast(tokenizer_object=tokenizer) + tmpdirname = tempfile.mkdtemp() + fast_tokenizer.save_pretrained(tmpdirname) + fast_from_saved = PreTrainedTokenizerFast.from_pretrained(tmpdirname) + for tok in [fast_tokenizer, fast_from_saved]: + self.assertEqual(tok.truncation_side, "right") + self.assertEqual(tok.init_kwargs["truncation_strategy"], "longest_first") + self.assertEqual(tok.init_kwargs["max_length"], 8) + self.assertEqual(tok.init_kwargs["stride"], 0) + # NOTE even if the model has a default max_length, it is not used... + # thus tok(sentences, truncation = True) does nothing and does not warn either + self.assertEqual(tok(sentences, truncation = True, max_length = 8), {'input_ids': [[8774, 6, 3, 63, 31, 1748, 55, 1],[ 571, 33, 25, 3, 2, 3, 58, 1]], 'token_type_ids': [[0, 0, 0, 0, 0, 0, 0, 0],[0, 0, 0, 0, 0, 0, 0, 0]], 'attention_mask': [[1, 1, 1, 1, 1, 1, 1, 1],[1, 1, 1, 1, 1, 1, 1, 1]]}) # fmt: skip + + def test_class_after_save_and_reload(self): + # Model contains a `LlamaTokenizerFast` tokenizer with no slow fallback + model_id = "deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B" + + with tempfile.TemporaryDirectory() as temp_dir: + tokenizer = AutoTokenizer.from_pretrained(model_id, use_fast=True) + self.assertTrue( + isinstance(tokenizer, LlamaTokenizerFast), + f"Expected tokenizer(use_fast=True) type: `LlamaTokenizerFast`, actual=`{type(tokenizer)}`", + ) + + # Fast tokenizer will ignore `use_fast=False` + tokenizer = AutoTokenizer.from_pretrained(model_id, use_fast=False) + self.assertTrue( + isinstance(tokenizer, LlamaTokenizerFast), + f"Expected tokenizer type(use_fast=False): `LlamaTokenizerFast`, actual=`{type(tokenizer)}`", + ) + + # Save tokenizer + tokenizer.save_pretrained(temp_dir) + + tokenizer = AutoTokenizer.from_pretrained(temp_dir, use_fast=False) + # Verify post save and reload the fast tokenizer class did not change + self.assertTrue( + isinstance(tokenizer, LlamaTokenizerFast), + f"Expected tokenizer type: `LlamaTokenizerFast`, actual=`{type(tokenizer)}`", + ) + + tokenizer = AutoTokenizer.from_pretrained(temp_dir, use_fast=True) + # Verify post save and reload the fast tokenizer class did not change + self.assertTrue( + isinstance(tokenizer, LlamaTokenizerFast), + f"Expected tokenizer type: `LlamaTokenizerFast`, actual=`{type(tokenizer)}`", + ) + + +@require_tokenizers +class TokenizerVersioningTest(unittest.TestCase): + def test_local_versioning(self): + tokenizer = AutoTokenizer.from_pretrained("google-bert/bert-base-cased") + json_tokenizer = json.loads(tokenizer._tokenizer.to_str()) + json_tokenizer["model"]["vocab"]["huggingface"] = len(tokenizer) + + with tempfile.TemporaryDirectory() as tmp_dir: + # Hack to save this in the tokenizer_config.json + tokenizer.init_kwargs["fast_tokenizer_files"] = ["tokenizer.4.0.0.json"] + tokenizer.save_pretrained(tmp_dir) + json.dump(json_tokenizer, open(os.path.join(tmp_dir, "tokenizer.4.0.0.json"), "w")) + + # This should pick the new tokenizer file as the version of Transformers is > 4.0.0 + new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir) + self.assertEqual(len(new_tokenizer), len(tokenizer) + 1) + json_tokenizer = json.loads(new_tokenizer._tokenizer.to_str()) + self.assertIn("huggingface", json_tokenizer["model"]["vocab"]) + + # Will need to be adjusted if we reach v42 and this test is still here. + # Should pick the old tokenizer file as the version of Transformers is < 4.0.0 + shutil.move(os.path.join(tmp_dir, "tokenizer.4.0.0.json"), os.path.join(tmp_dir, "tokenizer.42.0.0.json")) + tokenizer.init_kwargs["fast_tokenizer_files"] = ["tokenizer.42.0.0.json"] + tokenizer.save_pretrained(tmp_dir) + new_tokenizer = AutoTokenizer.from_pretrained(tmp_dir) + self.assertEqual(len(new_tokenizer), len(tokenizer)) + json_tokenizer = json.loads(new_tokenizer._tokenizer.to_str()) + self.assertNotIn("huggingface", json_tokenizer["model"]["vocab"]) + + def test_repo_versioning(self): + # This repo has two tokenizer files, one for v4.0.0 and above with an added token, one for versions lower. + repo = "hf-internal-testing/test-two-tokenizers" + + # This should pick the new tokenizer file as the version of Transformers is > 4.0.0 + tokenizer = AutoTokenizer.from_pretrained(repo) + self.assertEqual(len(tokenizer), 28997) + json_tokenizer = json.loads(tokenizer._tokenizer.to_str()) + self.assertIn("huggingface", json_tokenizer["model"]["vocab"]) + + # Testing an older version by monkey-patching the version in the module it's used. + import transformers as old_transformers + + old_transformers.tokenization_utils_base.__version__ = "3.0.0" + old_tokenizer = old_transformers.models.auto.AutoTokenizer.from_pretrained(repo) + self.assertEqual(len(old_tokenizer), 28996) + json_tokenizer = json.loads(old_tokenizer._tokenizer.to_str()) + self.assertNotIn("huggingface", json_tokenizer["model"]["vocab"]) + + +@require_tokenizers +class ReduceMutableBorrowTests(unittest.TestCase): + def test_async_share_tokenizer(self): + # See https://github.com/huggingface/transformers/pull/12550 + # and https://github.com/huggingface/tokenizers/issues/537 + tokenizer = PreTrainedTokenizerFast.from_pretrained("robot-test/dummy-tokenizer-wordlevel") + text = "The Matrix is a 1999 science fiction action film." + + with concurrent.futures.ThreadPoolExecutor() as executor: + futures = [executor.submit(self.fetch, tokenizer, text) for i in range(10)] + return_value = [future.result() for future in futures] + self.assertEqual(return_value, [[1, 10, 0, 8, 0, 18, 0, 0, 0, 2] for i in range(10)]) + + def fetch(self, tokenizer, text): + return tokenizer.encode(text, truncation="longest_first", padding="longest") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tokenization/test_tokenization_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tokenization/test_tokenization_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fc74223110f8973cbcf3f60afeadd01b3c51fdbc --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/tokenization/test_tokenization_utils.py @@ -0,0 +1,407 @@ +# Copyright 2018 HuggingFace 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. +""" +ruff: isort: skip_file +""" + +import os +import pickle +import tempfile +import unittest +from typing import Callable, Optional + +import numpy as np + +from transformers import ( + AutoTokenizer, + BatchEncoding, + BertTokenizer, + BertTokenizerFast, + LlamaTokenizerFast, + PreTrainedTokenizer, + PreTrainedTokenizerFast, + TensorType, + TokenSpan, + is_tokenizers_available, +) +from transformers.models.gpt2.tokenization_gpt2 import GPT2Tokenizer +from transformers.testing_utils import ( + CaptureStderr, + require_sentencepiece, + require_tokenizers, + require_torch, + slow, +) + + +if is_tokenizers_available(): + import tokenizers + from tokenizers import Tokenizer + from tokenizers.models import WordPiece + + +class TokenizerUtilsTest(unittest.TestCase): + def check_tokenizer_from_pretrained(self, tokenizer_class): + s3_models = list(tokenizer_class.max_model_input_sizes.keys()) + for model_name in s3_models[:1]: + tokenizer = tokenizer_class.from_pretrained(model_name) + self.assertIsNotNone(tokenizer) + self.assertIsInstance(tokenizer, tokenizer_class) + self.assertIsInstance(tokenizer, PreTrainedTokenizer) + + for special_tok in tokenizer.all_special_tokens: + self.assertIsInstance(special_tok, str) + special_tok_id = tokenizer.convert_tokens_to_ids(special_tok) + self.assertIsInstance(special_tok_id, int) + + def assert_dump_and_restore(self, be_original: BatchEncoding, equal_op: Optional[Callable] = None): + batch_encoding_str = pickle.dumps(be_original) + self.assertIsNotNone(batch_encoding_str) + + be_restored = pickle.loads(batch_encoding_str) + + # Ensure is_fast is correctly restored + self.assertEqual(be_restored.is_fast, be_original.is_fast) + + # Ensure encodings are potentially correctly restored + if be_original.is_fast: + self.assertIsNotNone(be_restored.encodings) + else: + self.assertIsNone(be_restored.encodings) + + # Ensure the keys are the same + for original_v, restored_v in zip(be_original.values(), be_restored.values()): + if equal_op: + self.assertTrue(equal_op(restored_v, original_v)) + else: + self.assertEqual(restored_v, original_v) + + @slow + def test_pretrained_tokenizers(self): + self.check_tokenizer_from_pretrained(GPT2Tokenizer) + + def test_tensor_type_from_str(self): + self.assertEqual(TensorType("tf"), TensorType.TENSORFLOW) + self.assertEqual(TensorType("pt"), TensorType.PYTORCH) + self.assertEqual(TensorType("np"), TensorType.NUMPY) + + @require_tokenizers + def test_batch_encoding_pickle(self): + tokenizer_p = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + tokenizer_r = BertTokenizerFast.from_pretrained("google-bert/bert-base-cased") + + # Python no tensor + with self.subTest("BatchEncoding (Python, return_tensors=None)"): + self.assert_dump_and_restore(tokenizer_p("Small example to encode")) + + with self.subTest("BatchEncoding (Python, return_tensors=NUMPY)"): + self.assert_dump_and_restore( + tokenizer_p("Small example to encode", return_tensors=TensorType.NUMPY), np.array_equal + ) + + with self.subTest("BatchEncoding (Rust, return_tensors=None)"): + self.assert_dump_and_restore(tokenizer_r("Small example to encode")) + + with self.subTest("BatchEncoding (Rust, return_tensors=NUMPY)"): + self.assert_dump_and_restore( + tokenizer_r("Small example to encode", return_tensors=TensorType.NUMPY), np.array_equal + ) + + @require_torch + @require_tokenizers + def test_batch_encoding_pickle_pt(self): + import torch + + tokenizer_p = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + tokenizer_r = BertTokenizerFast.from_pretrained("google-bert/bert-base-cased") + + with self.subTest("BatchEncoding (Python, return_tensors=PYTORCH)"): + self.assert_dump_and_restore( + tokenizer_p("Small example to encode", return_tensors=TensorType.PYTORCH), torch.equal + ) + + with self.subTest("BatchEncoding (Rust, return_tensors=PYTORCH)"): + self.assert_dump_and_restore( + tokenizer_r("Small example to encode", return_tensors=TensorType.PYTORCH), torch.equal + ) + + @require_tokenizers + def test_batch_encoding_is_fast(self): + tokenizer_p = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + tokenizer_r = BertTokenizerFast.from_pretrained("google-bert/bert-base-cased") + + with self.subTest("Python Tokenizer"): + self.assertFalse(tokenizer_p("Small example to_encode").is_fast) + + with self.subTest("Rust Tokenizer"): + self.assertTrue(tokenizer_r("Small example to_encode").is_fast) + + @require_tokenizers + def test_batch_encoding_word_to_tokens(self): + tokenizer_r = BertTokenizerFast.from_pretrained("google-bert/bert-base-cased") + encoded = tokenizer_r(["Test", "\xad", "test"], is_split_into_words=True) + + self.assertEqual(encoded.word_to_tokens(0), TokenSpan(start=1, end=2)) + self.assertEqual(encoded.word_to_tokens(1), None) + self.assertEqual(encoded.word_to_tokens(2), TokenSpan(start=2, end=3)) + + def test_batch_encoding_with_labels(self): + batch = BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}) + tensor_batch = batch.convert_to_tensors(tensor_type="np") + self.assertEqual(tensor_batch["inputs"].shape, (2, 3)) + self.assertEqual(tensor_batch["labels"].shape, (2,)) + # test converting the converted + with CaptureStderr() as cs: + tensor_batch = batch.convert_to_tensors(tensor_type="np") + self.assertFalse(len(cs.err), msg=f"should have no warning, but got {cs.err}") + + batch = BatchEncoding({"inputs": [1, 2, 3], "labels": 0}) + tensor_batch = batch.convert_to_tensors(tensor_type="np", prepend_batch_axis=True) + self.assertEqual(tensor_batch["inputs"].shape, (1, 3)) + self.assertEqual(tensor_batch["labels"].shape, (1,)) + + @require_torch + def test_batch_encoding_with_labels_pt(self): + batch = BatchEncoding({"inputs": [[1, 2, 3], [4, 5, 6]], "labels": [0, 1]}) + tensor_batch = batch.convert_to_tensors(tensor_type="pt") + self.assertEqual(tensor_batch["inputs"].shape, (2, 3)) + self.assertEqual(tensor_batch["labels"].shape, (2,)) + # test converting the converted + with CaptureStderr() as cs: + tensor_batch = batch.convert_to_tensors(tensor_type="pt") + self.assertFalse(len(cs.err), msg=f"should have no warning, but got {cs.err}") + + batch = BatchEncoding({"inputs": [1, 2, 3], "labels": 0}) + tensor_batch = batch.convert_to_tensors(tensor_type="pt", prepend_batch_axis=True) + self.assertEqual(tensor_batch["inputs"].shape, (1, 3)) + self.assertEqual(tensor_batch["labels"].shape, (1,)) + + def test_padding_accepts_tensors(self): + features = [{"input_ids": np.array([0, 1, 2])}, {"input_ids": np.array([0, 1, 2, 3])}] + tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + + batch = tokenizer.pad(features, padding=True) + self.assertTrue(isinstance(batch["input_ids"], np.ndarray)) + self.assertEqual(batch["input_ids"].tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + batch = tokenizer.pad(features, padding=True, return_tensors="np") + self.assertTrue(isinstance(batch["input_ids"], np.ndarray)) + self.assertEqual(batch["input_ids"].tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + + @require_tokenizers + def test_decoding_single_token(self): + for tokenizer_class in [BertTokenizer, BertTokenizerFast]: + with self.subTest(f"{tokenizer_class}"): + tokenizer = tokenizer_class.from_pretrained("google-bert/bert-base-cased") + + token_id = 2300 + decoded_flat = tokenizer.decode(token_id) + decoded_list = tokenizer.decode([token_id]) + + self.assertEqual(decoded_flat, "Force") + self.assertEqual(decoded_list, "Force") + + token_id = 0 + decoded_flat = tokenizer.decode(token_id) + decoded_list = tokenizer.decode([token_id]) + + self.assertEqual(decoded_flat, "[PAD]") + self.assertEqual(decoded_list, "[PAD]") + + last_item_id = tokenizer.vocab_size - 1 + decoded_flat = tokenizer.decode(last_item_id) + decoded_list = tokenizer.decode([last_item_id]) + + self.assertEqual(decoded_flat, "##:") + self.assertEqual(decoded_list, "##:") + + def test_extra_special_tokens_multimodal(self): + special_tokens_list = [ + "bos_token", + "eos_token", + "unk_token", + "sep_token", + "pad_token", + "cls_token", + "mask_token", + "additional_special_tokens", + ] + llama_tokenizer = LlamaTokenizerFast.from_pretrained("huggyllama/llama-7b") + llama_tokenizer.extra_special_tokens = { + "boi_token": "", + "eoi_token": "", + "image_token": "", + } + self.assertListEqual(llama_tokenizer.SPECIAL_TOKENS_ATTRIBUTES, special_tokens_list) + with tempfile.TemporaryDirectory() as tmpdirname: + llama_tokenizer.save_pretrained(tmpdirname) + + # load back and check we have extra special tokens set + loaded_tokenizer = LlamaTokenizerFast.from_pretrained(tmpdirname) + multimodal_special_tokens_list = special_tokens_list + ["boi_token", "eoi_token", "image_token"] + self.assertListEqual(loaded_tokenizer.SPECIAL_TOKENS_ATTRIBUTES, multimodal_special_tokens_list) + + # We set an image_token_id before, so we can get an "image_token" as str that matches the id + self.assertTrue(loaded_tokenizer.image_token == "") + self.assertTrue(loaded_tokenizer.image_token_id == loaded_tokenizer.convert_tokens_to_ids("")) + + # save one more time and make sure the image token can get loaded back + with tempfile.TemporaryDirectory() as tmpdirname: + loaded_tokenizer.save_pretrained(tmpdirname) + loaded_tokenizer_with_extra_tokens = LlamaTokenizerFast.from_pretrained(tmpdirname) + self.assertTrue(loaded_tokenizer_with_extra_tokens.image_token == "") + + # test that we can also indicate extra tokens during load time + extra_special_tokens = { + "boi_token": "", + "eoi_token": "", + "image_token": "", + } + tokenizer = LlamaTokenizerFast.from_pretrained( + "huggyllama/llama-7b", extra_special_tokens=extra_special_tokens + ) + self.assertTrue(tokenizer.image_token == "") + self.assertTrue(tokenizer.image_token_id == loaded_tokenizer.convert_tokens_to_ids("")) + + @require_tokenizers + def test_decoding_skip_special_tokens(self): + for tokenizer_class in [BertTokenizer, BertTokenizerFast]: + with self.subTest(f"{tokenizer_class}"): + tokenizer = tokenizer_class.from_pretrained("google-bert/bert-base-cased") + tokenizer.add_tokens(["ஐ"], special_tokens=True) + + # test special token with other tokens, skip the special tokens + sentence = "This is a beautiful flower ஐ" + ids = tokenizer(sentence)["input_ids"] + decoded_sent = tokenizer.decode(ids, skip_special_tokens=True) + self.assertEqual(decoded_sent, "This is a beautiful flower") + + # test special token with other tokens, do not skip the special tokens + ids = tokenizer(sentence)["input_ids"] + decoded_sent = tokenizer.decode(ids, skip_special_tokens=False) + self.assertEqual(decoded_sent, "[CLS] This is a beautiful flower ஐ [SEP]") + + # test special token stand alone, skip the special tokens + sentence = "ஐ" + ids = tokenizer(sentence)["input_ids"] + decoded_sent = tokenizer.decode(ids, skip_special_tokens=True) + self.assertEqual(decoded_sent, "") + + # test special token stand alone, do not skip the special tokens + ids = tokenizer(sentence)["input_ids"] + decoded_sent = tokenizer.decode(ids, skip_special_tokens=False) + self.assertEqual(decoded_sent, "[CLS] ஐ [SEP]") + + # test single special token alone, skip + pad_id = 0 + decoded_sent = tokenizer.decode(pad_id, skip_special_tokens=True) + self.assertEqual(decoded_sent, "") + + # test single special token alone, do not skip + decoded_sent = tokenizer.decode(pad_id, skip_special_tokens=False) + self.assertEqual(decoded_sent, "[PAD]") + + @require_torch + def test_padding_accepts_tensors_pt(self): + import torch + + features = [{"input_ids": torch.tensor([0, 1, 2])}, {"input_ids": torch.tensor([0, 1, 2, 3])}] + tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-cased") + + batch = tokenizer.pad(features, padding=True) + self.assertTrue(isinstance(batch["input_ids"], torch.Tensor)) + self.assertEqual(batch["input_ids"].tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + batch = tokenizer.pad(features, padding=True, return_tensors="pt") + self.assertTrue(isinstance(batch["input_ids"], torch.Tensor)) + self.assertEqual(batch["input_ids"].tolist(), [[0, 1, 2, tokenizer.pad_token_id], [0, 1, 2, 3]]) + + @require_tokenizers + def test_instantiation_from_tokenizers(self): + bert_tokenizer = Tokenizer(WordPiece(unk_token="[UNK]")) + PreTrainedTokenizerFast(tokenizer_object=bert_tokenizer) + + @require_tokenizers + def test_instantiation_from_tokenizers_json_file(self): + bert_tokenizer = Tokenizer(WordPiece(unk_token="[UNK]")) + with tempfile.TemporaryDirectory() as tmpdirname: + bert_tokenizer.save(os.path.join(tmpdirname, "tokenizer.json")) + PreTrainedTokenizerFast(tokenizer_file=os.path.join(tmpdirname, "tokenizer.json")) + + def test_len_tokenizer(self): + for tokenizer_class in [BertTokenizer, BertTokenizerFast]: + with self.subTest(f"{tokenizer_class}"): + tokenizer = tokenizer_class.from_pretrained("bert-base-uncased") + added_tokens_size = len(tokenizer.added_tokens_decoder) + self.assertEqual(len(tokenizer), tokenizer.vocab_size) + + tokenizer.add_tokens([""]) + self.assertEqual(len(tokenizer), tokenizer.vocab_size + 1) + self.assertEqual(len(tokenizer.added_tokens_decoder), added_tokens_size + 1) + self.assertEqual(len(tokenizer.added_tokens_encoder), added_tokens_size + 1) + + @require_sentencepiece + def test_sentencepiece_cohabitation(self): + from sentencepiece import sentencepiece_model_pb2 as _original_protobuf # noqa: F401 + + from transformers.convert_slow_tokenizer import import_protobuf # noqa: F401 + + # Now this will try to import sentencepiece_model_pb2_new.py. This should not fail even if the protobuf + # was already imported. + import_protobuf() + + def test_training_new_tokenizer_edge_cases(self): + _tokenizer = Tokenizer(tokenizers.models.BPE(vocab={"a": 1, "b": 2, "ab": 3}, merges=[("a", "b")])) + _tokenizer.pre_tokenizer = None + + tokenizer = PreTrainedTokenizerFast(tokenizer_object=_tokenizer) + toy_text_iterator = ("a" for _ in range(1000)) + tokenizer.train_new_from_iterator(text_iterator=toy_text_iterator, length=1000, vocab_size=50) + + _tokenizer.normalizer = None + tokenizer = PreTrainedTokenizerFast(tokenizer_object=_tokenizer) + toy_text_iterator = ("a" for _ in range(1000)) + tokenizer.train_new_from_iterator(text_iterator=toy_text_iterator, length=1000, vocab_size=50) + + _tokenizer.post_processor = None + tokenizer = PreTrainedTokenizerFast(tokenizer_object=_tokenizer) + toy_text_iterator = ("a" for _ in range(1000)) + tokenizer.train_new_from_iterator(text_iterator=toy_text_iterator, length=1000, vocab_size=50) + + def test_encode_message(self): + tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") + conversation = [ + {"role": "system", "content": "You are a helpful assistant"}, + {"role": "user", "content": "Hey there, how are you?"}, + {"role": "assistant", "content": "Thank you for asking, I am doing well"}, + {"role": "user", "content": "What's the weather like today?"}, + {"role": "assistant", "content": "Today the weather is nice"}, + ] + + # First, test the default case, where we encode the whole conversation at once + whole_conversation_tokens = tokenizer.apply_chat_template(conversation, tokenize=True) + + # Now, test the message-by-message encoding + tokens = [] + for i, message in enumerate(conversation): + tokens += tokenizer.encode_message_with_chat_template(message, conversation_history=conversation[:i]) + + self.assertEqual(whole_conversation_tokens, tokens) + + def test_encode_message_raises_on_add_generation_prompt(self): + tokenizer = AutoTokenizer.from_pretrained("HuggingFaceH4/zephyr-7b-beta") + conversation = [ + {"role": "system", "content": "You are a helpful assistant"}, + {"role": "user", "content": "Hey there, how are you?"}, + ] + with self.assertRaises(ValueError): + tokenizer.encode_message_with_chat_template(conversation[0], add_generation_prompt=True) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_data_collator.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_data_collator.py new file mode 100644 index 0000000000000000000000000000000000000000..d25aa7ceba9aa12feabac21aa4d74f77b3de1969 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_data_collator.py @@ -0,0 +1,1844 @@ +# 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. + +import os +import shutil +import tempfile +import unittest + +import numpy as np + +from transformers import ( + BertTokenizer, + DataCollatorForLanguageModeling, + DataCollatorForPermutationLanguageModeling, + DataCollatorForSeq2Seq, + DataCollatorForTokenClassification, + DataCollatorForWholeWordMask, + DataCollatorWithFlattening, + DataCollatorWithPadding, + default_data_collator, + is_torch_available, + set_seed, +) +from transformers.testing_utils import require_torch +from transformers.utils import PaddingStrategy + + +if is_torch_available(): + import torch + + +@require_torch +class DataCollatorIntegrationTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] + self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_default_with_dict(self): + features = [{"label": i, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) + + # With label_ids + features = [{"label_ids": [0, 1, 2], "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue(batch["labels"].equal(torch.tensor([[0, 1, 2]] * 8))) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) + + # Features can already be tensors + features = [{"label": i, "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 10])) + + # Labels can already be tensors + features = [{"label": torch.tensor(i), "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertTrue(batch["labels"].equal(torch.tensor(list(range(8))))) + self.assertEqual(batch["labels"].dtype, torch.long) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 10])) + + def test_default_classification_and_regression(self): + data_collator = default_data_collator + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": i} for i in range(4)] + batch = data_collator(features) + self.assertEqual(batch["labels"].dtype, torch.long) + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": float(i)} for i in range(4)] + batch = data_collator(features) + self.assertEqual(batch["labels"].dtype, torch.float) + + def test_default_with_no_labels(self): + features = [{"label": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) + + # With label_ids + features = [{"label_ids": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features) + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape, torch.Size([8, 6])) + + def test_data_collator_with_padding(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + + data_collator = DataCollatorWithPadding(tokenizer) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) + + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) + + def test_data_collator_with_flattening(self): + features = [ + {"input_ids": [10, 11, 12]}, + {"input_ids": [20, 21, 22, 23, 24, 25]}, + {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, + ] + + data_collator = DataCollatorWithFlattening(return_tensors="pt") + batch = data_collator(features) + + for unexpected_key in [ + "attention_mask", + "cu_seq_lens_k", + "cu_seq_lens_q", + "max_length_k", + "max_length_q", + "seq_idx", + ]: + self.assertNotIn(unexpected_key, batch) + self.assertIn("position_ids", batch) + + self.assertEqual(batch["input_ids"].shape, torch.Size([1, 16])) + self.assertEqual( + batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] + ) + self.assertEqual(batch["position_ids"].shape, torch.Size([1, 16])) + self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) + + def test_data_collator_with_flattening_flash_attn_kwargs(self): + features = [ + {"input_ids": [10, 11, 12]}, + {"input_ids": [20, 21, 22, 23, 24, 25]}, + {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, + ] + data_collator = DataCollatorWithFlattening(return_tensors="pt", return_flash_attn_kwargs=True) + batch = data_collator(features) + + for unexpected_key in [ + "attention_mask", + "seq_idx", + ]: + self.assertNotIn(unexpected_key, batch) + for expected_key in [ + "position_ids", + "cu_seq_lens_k", + "cu_seq_lens_q", + "max_length_k", + "max_length_q", + ]: + self.assertIn(expected_key, batch) + + self.assertEqual(batch["input_ids"].shape, torch.Size([1, 16])) + self.assertEqual( + batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] + ) + self.assertEqual(batch["position_ids"].shape, torch.Size([1, 16])) + self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) + + self.assertEqual(batch["cu_seq_lens_k"].shape, torch.Size([4])) + self.assertEqual(batch["cu_seq_lens_k"].tolist(), [0, 3, 9, 16]) + self.assertEqual(batch["cu_seq_lens_q"].shape, torch.Size([4])) + self.assertEqual(batch["cu_seq_lens_q"].tolist(), [0, 3, 9, 16]) + # The flash attn max_length_{k,q} are simple python ints + self.assertEqual(batch["max_length_k"], 7) + self.assertEqual(batch["max_length_q"], 7) + + def test_data_collator_with_flattening_seq_idx(self): + features = [ + {"input_ids": [10, 11, 12]}, + {"input_ids": [20, 21, 22, 23, 24, 25]}, + {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, + ] + data_collator = DataCollatorWithFlattening(return_tensors="pt", return_seq_idx=True) + batch = data_collator(features) + + for unexpected_key in [ + "attention_mask", + "cu_seq_lens_k", + "cu_seq_lens_q", + "max_length_k", + "max_length_q", + ]: + self.assertNotIn(unexpected_key, batch) + for expected_key in [ + "position_ids", + "seq_idx", + ]: + self.assertIn(expected_key, batch) + + self.assertEqual(batch["input_ids"].shape, torch.Size([1, 16])) + self.assertEqual( + batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] + ) + self.assertEqual(batch["position_ids"].shape, torch.Size([1, 16])) + self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) + self.assertEqual(batch["seq_idx"].shape, batch["input_ids"].shape) + self.assertEqual(batch["seq_idx"][0].tolist(), [0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) + + def test_data_collator_for_token_classification(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2], "labels": [0, 1, 2]}, + {"input_ids": [0, 1, 2, 3, 4, 5], "labels": [0, 1, 2, 3, 4, 5]}, + ] + + data_collator = DataCollatorForTokenClassification(tokenizer) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) + + data_collator = DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 10])) + + data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 8])) + + data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) + + for feature in features: + feature.pop("labels") + + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + def test_data_collator_for_token_classification_works_with_pt_tensors(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": torch.tensor([0, 1, 2]), "labels": torch.tensor([0, 1, 2])}, + {"input_ids": torch.tensor([0, 1, 2, 3, 4, 5]), "labels": torch.tensor([0, 1, 2, 3, 4, 5])}, + ] + + data_collator = DataCollatorForTokenClassification(tokenizer) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) + + data_collator = DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 10])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 10])) + + data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 8])) + + data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) + + for feature in features: + feature.pop("labels") + + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + def _test_data_collator_for_seq2seq(self, to_torch): + def create_features(to_torch): + if to_torch: + features = [ + {"input_ids": torch.tensor(list(range(3))), "labels": torch.tensor(list(range(3)))}, + {"input_ids": torch.tensor(list(range(6))), "labels": torch.tensor(list(range(6)))}, + ] + else: + features = [ + {"input_ids": list(range(3)), "labels": list(range(3))}, + {"input_ids": list(range(6)), "labels": list(range(6))}, + ] + return features + + tokenizer = BertTokenizer(self.vocab_file) + features = create_features(to_torch) + + data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["input_ids"][1].tolist(), list(range(6))) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-100] * 3) + self.assertEqual(batch["labels"][1].tolist(), list(range(6))) + + data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.MAX_LENGTH, max_length=7) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 7])) + self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 4) + self.assertEqual(batch["input_ids"][1].tolist(), list(range(6)) + [tokenizer.pad_token_id] * 1) + self.assertEqual(batch["labels"].shape, torch.Size([2, 7])) + self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-100] * 4) + self.assertEqual(batch["labels"][1].tolist(), list(range(6)) + [-100] * 1) + + data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.DO_NOT_PAD) + with self.assertRaises(ValueError): + # expects an error due to unequal shapes to create tensor + data_collator(features) + batch = data_collator([features[0], features[0]]) + input_ids = features[0]["input_ids"] if not to_torch else features[0]["input_ids"].tolist() + labels = features[0]["labels"] if not to_torch else features[0]["labels"].tolist() + self.assertEqual(batch["input_ids"][0].tolist(), input_ids) + self.assertEqual(batch["input_ids"][1].tolist(), input_ids) + self.assertEqual(batch["labels"][0].tolist(), labels) + self.assertEqual(batch["labels"][1].tolist(), labels) + + data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, pad_to_multiple_of=8) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 8])) + self.assertEqual(batch["labels"].shape, torch.Size([2, 8])) + + # side effects on labels cause mismatch on longest strategy + features = create_features(to_torch) + + data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, label_pad_token_id=-1) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["input_ids"][1].tolist(), list(range(6))) + self.assertEqual(batch["labels"].shape, torch.Size([2, 6])) + self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-1] * 3) + self.assertEqual(batch["labels"][1].tolist(), list(range(6))) + + for feature in features: + feature.pop("labels") + + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size([2, 6])) + self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) + + def test_data_collator_for_seq2seq_with_lists(self): + self._test_data_collator_for_seq2seq(to_torch=False) + + def test_data_collator_for_seq2seq_with_pt(self): + self._test_data_collator_for_seq2seq(to_torch=True) + + def _test_no_pad_and_pad(self, no_pad_features, pad_features): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) + + tokenizer.pad_token = None + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False) + with self.assertRaises(ValueError): + # Expect error due to padding token missing + data_collator(pad_features) + + set_seed(42) # For reproducibility + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(torch.any(masked_tokens)) + self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(torch.any(masked_tokens)) + self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(torch.any(masked_tokens)) + self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 16))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 16))) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(torch.any(masked_tokens)) + self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + def test_data_collator_for_language_modeling(self): + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + no_pad_features = [list(range(10)), list(range(10))] + pad_features = [list(range(5)), list(range(10))] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + def test_data_collator_for_language_modeling_with_seed(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": list(range(1000))}, {"input_ids": list(range(1000))}] + + # check if seed is respected between two different DataCollatorForLanguageModeling instances + data_collator = DataCollatorForLanguageModeling(tokenizer, seed=42) + batch_1 = data_collator(features) + self.assertEqual(batch_1["input_ids"].shape, torch.Size((2, 1000))) + self.assertEqual(batch_1["labels"].shape, torch.Size((2, 1000))) + + data_collator = DataCollatorForLanguageModeling(tokenizer, seed=42) + batch_2 = data_collator(features) + self.assertEqual(batch_2["input_ids"].shape, torch.Size((2, 1000))) + self.assertEqual(batch_2["labels"].shape, torch.Size((2, 1000))) + + self.assertTrue(torch.all(batch_1["input_ids"] == batch_2["input_ids"])) + self.assertTrue(torch.all(batch_1["labels"] == batch_2["labels"])) + + # check if seed is respected in multiple workers situation + features = [{"input_ids": list(range(1000))} for _ in range(10)] + dataloader = torch.utils.data.DataLoader( + features, + batch_size=2, + num_workers=2, + generator=torch.Generator().manual_seed(42), + collate_fn=DataCollatorForLanguageModeling(tokenizer, seed=42), + ) + + batch_3_input_ids = [] + batch_3_labels = [] + for batch in dataloader: + batch_3_input_ids.append(batch["input_ids"]) + batch_3_labels.append(batch["labels"]) + + batch_3_input_ids = torch.stack(batch_3_input_ids) + batch_3_labels = torch.stack(batch_3_labels) + self.assertEqual(batch_3_input_ids.shape, torch.Size((5, 2, 1000))) + self.assertEqual(batch_3_labels.shape, torch.Size((5, 2, 1000))) + + dataloader = torch.utils.data.DataLoader( + features, + batch_size=2, + num_workers=2, + collate_fn=DataCollatorForLanguageModeling(tokenizer, seed=42), + ) + + batch_4_input_ids = [] + batch_4_labels = [] + for batch in dataloader: + batch_4_input_ids.append(batch["input_ids"]) + batch_4_labels.append(batch["labels"]) + batch_4_input_ids = torch.stack(batch_4_input_ids) + batch_4_labels = torch.stack(batch_4_labels) + self.assertEqual(batch_4_input_ids.shape, torch.Size((5, 2, 1000))) + self.assertEqual(batch_4_labels.shape, torch.Size((5, 2, 1000))) + + self.assertTrue(torch.all(batch_3_input_ids == batch_4_input_ids)) + self.assertTrue(torch.all(batch_3_labels == batch_4_labels)) + + # try with different seed + dataloader = torch.utils.data.DataLoader( + features, + batch_size=2, + num_workers=2, + collate_fn=DataCollatorForLanguageModeling(tokenizer, seed=43), + ) + + batch_5_input_ids = [] + batch_5_labels = [] + for batch in dataloader: + batch_5_input_ids.append(batch["input_ids"]) + batch_5_labels.append(batch["labels"]) + batch_5_input_ids = torch.stack(batch_5_input_ids) + batch_5_labels = torch.stack(batch_5_labels) + self.assertEqual(batch_5_input_ids.shape, torch.Size((5, 2, 1000))) + self.assertEqual(batch_5_labels.shape, torch.Size((5, 2, 1000))) + + self.assertFalse(torch.all(batch_3_input_ids == batch_5_input_ids)) + self.assertFalse(torch.all(batch_3_labels == batch_5_labels)) + + def test_data_collator_for_whole_word_mask(self): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="pt") + + features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + # Features can already be tensors + features = [{"input_ids": np.arange(10)}, {"input_ids": np.arange(10)}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + def test_data_collator_for_whole_word_mask_with_seed(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": list(range(1000))}, {"input_ids": list(range(1000))}] + + # check if seed is respected between two different DataCollatorForWholeWordMask instances + data_collator = DataCollatorForWholeWordMask(tokenizer, seed=42) + batch_1 = data_collator(features) + self.assertEqual(batch_1["input_ids"].shape, torch.Size((2, 1000))) + self.assertEqual(batch_1["labels"].shape, torch.Size((2, 1000))) + + data_collator = DataCollatorForWholeWordMask(tokenizer, seed=42) + batch_2 = data_collator(features) + self.assertEqual(batch_2["input_ids"].shape, torch.Size((2, 1000))) + self.assertEqual(batch_2["labels"].shape, torch.Size((2, 1000))) + + self.assertTrue(torch.all(batch_1["input_ids"] == batch_2["input_ids"])) + self.assertTrue(torch.all(batch_1["labels"] == batch_2["labels"])) + + # check if seed is respected in multiple workers situation + features = [{"input_ids": list(range(1000))} for _ in range(10)] + dataloader = torch.utils.data.DataLoader( + features, + batch_size=2, + num_workers=2, + generator=torch.Generator().manual_seed(42), + collate_fn=DataCollatorForWholeWordMask(tokenizer, seed=42), + ) + + batch_3_input_ids = [] + batch_3_labels = [] + for batch in dataloader: + batch_3_input_ids.append(batch["input_ids"]) + batch_3_labels.append(batch["labels"]) + + batch_3_input_ids = torch.stack(batch_3_input_ids) + batch_3_labels = torch.stack(batch_3_labels) + self.assertEqual(batch_3_input_ids.shape, torch.Size((5, 2, 1000))) + self.assertEqual(batch_3_labels.shape, torch.Size((5, 2, 1000))) + + dataloader = torch.utils.data.DataLoader( + features, + batch_size=2, + num_workers=2, + collate_fn=DataCollatorForWholeWordMask(tokenizer, seed=42), + ) + + batch_4_input_ids = [] + batch_4_labels = [] + for batch in dataloader: + batch_4_input_ids.append(batch["input_ids"]) + batch_4_labels.append(batch["labels"]) + batch_4_input_ids = torch.stack(batch_4_input_ids) + batch_4_labels = torch.stack(batch_4_labels) + self.assertEqual(batch_4_input_ids.shape, torch.Size((5, 2, 1000))) + self.assertEqual(batch_4_labels.shape, torch.Size((5, 2, 1000))) + + self.assertTrue(torch.all(batch_3_input_ids == batch_4_input_ids)) + self.assertTrue(torch.all(batch_3_labels == batch_4_labels)) + + # try with different seed + dataloader = torch.utils.data.DataLoader( + features, + batch_size=2, + num_workers=2, + collate_fn=DataCollatorForWholeWordMask(tokenizer, seed=43), + ) + + batch_5_input_ids = [] + batch_5_labels = [] + for batch in dataloader: + batch_5_input_ids.append(batch["input_ids"]) + batch_5_labels.append(batch["labels"]) + batch_5_input_ids = torch.stack(batch_5_input_ids) + batch_5_labels = torch.stack(batch_5_labels) + self.assertEqual(batch_5_input_ids.shape, torch.Size((5, 2, 1000))) + self.assertEqual(batch_5_labels.shape, torch.Size((5, 2, 1000))) + + self.assertFalse(torch.all(batch_3_input_ids == batch_5_input_ids)) + self.assertFalse(torch.all(batch_3_labels == batch_5_labels)) + + def test_plm(self): + tokenizer = BertTokenizer(self.vocab_file) + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + + data_collator = DataCollatorForPermutationLanguageModeling(tokenizer) + + batch = data_collator(pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["perm_mask"].shape, torch.Size((2, 10, 10))) + self.assertEqual(batch["target_mapping"].shape, torch.Size((2, 10, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + batch = data_collator(no_pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 10))) + self.assertEqual(batch["perm_mask"].shape, torch.Size((2, 10, 10))) + self.assertEqual(batch["target_mapping"].shape, torch.Size((2, 10, 10))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 10))) + + example = [np.random.randint(0, 5, [5])] + with self.assertRaises(ValueError): + # Expect error due to odd sequence length + data_collator(example) + + def test_nsp(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer) + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 5))) + self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 5))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 5))) + self.assertEqual(batch["next_sentence_label"].shape, torch.Size((2,))) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 8))) + self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 8))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 8))) + self.assertEqual(batch["next_sentence_label"].shape, torch.Size((2,))) + + def test_sop(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + { + "input_ids": torch.tensor([0, 1, 2, 3, 4]), + "token_type_ids": torch.tensor([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer) + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 5))) + self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 5))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 5))) + self.assertEqual(batch["sentence_order_label"].shape, torch.Size((2,))) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, torch.Size((2, 8))) + self.assertEqual(batch["token_type_ids"].shape, torch.Size((2, 8))) + self.assertEqual(batch["labels"].shape, torch.Size((2, 8))) + self.assertEqual(batch["sentence_order_label"].shape, torch.Size((2,))) + + +@require_torch +class DataCollatorImmutabilityTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] + self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def _turn_to_none(self, item): + """used to convert `item` to `None` type""" + return None + + def _validate_original_data_against_collated_data(self, collator, original_data, batch_data): + # we only care about side effects, the results are tested elsewhere + collator(batch_data) + + # we go through every item and convert to `primitive` datatypes if necessary + # then compares for equivalence for the original data and the data that has been passed through the collator + for original, batch in zip(original_data, batch_data): + for original_val, batch_val in zip(original.values(), batch.values()): + if isinstance(original_val, (np.ndarray, torch.Tensor)): + self.assertEqual(original_val.tolist(), batch_val.tolist()) + else: + self.assertEqual(original_val, batch_val) + + def _validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + self, collator, base_data, input_key, input_datatype, label_key, label_datatype, ignore_label=False + ): + # using the arguments to recreate the features with their respective (potentially new) datatypes + features_original = [ + {label_key: label_datatype(sample[label_key]), input_key: input_datatype(sample[input_key])} + for sample in base_data + ] + features_batch = [ + {label_key: label_datatype(sample[label_key]), input_key: input_datatype(sample[input_key])} + for sample in base_data + ] + + # some collators do not use labels, or sometimes we want to check if the collator with labels can handle such cases + if ignore_label: + for original, batch in zip(features_original, features_batch): + original.pop(label_key) + batch.pop(label_key) + + self._validate_original_data_against_collated_data( + collator=collator, original_data=features_original, batch_data=features_batch + ) + + def test_default_collator_immutability(self): + features_base_single_label = [{"label": i, "inputs": (0, 1, 2, 3, 4, 5)} for i in range(4)] + features_base_multiple_labels = [{"label": (0, 1, 2), "inputs": (0, 1, 2, 3, 4, 5)} for i in range(4)] + + for datatype_input, datatype_label in [ + (list, int), + (list, float), + (np.array, int), + (np.array, torch.tensor), + (list, self._turn_to_none), + ]: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=default_data_collator, + base_data=features_base_single_label, + input_key="inputs", + input_datatype=datatype_input, + label_key="label", + label_datatype=datatype_label, + ) + + for datatype_input, datatype_label in [(list, list), (list, self._turn_to_none)]: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=default_data_collator, + base_data=features_base_multiple_labels, + input_key="inputs", + input_datatype=datatype_input, + label_key="label", + label_datatype=datatype_label, + ) + + features_base_single_label_alt = [{"input_ids": (0, 1, 2, 3, 4), "label": float(i)} for i in range(4)] + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=default_data_collator, + base_data=features_base_single_label_alt, + input_key="input_ids", + input_datatype=list, + label_key="label", + label_datatype=float, + ) + + def test_with_padding_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_original = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + features_batch = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + + data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10) + self._validate_original_data_against_collated_data( + collator=data_collator, original_data=features_original, batch_data=features_batch + ) + + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8) + self._validate_original_data_against_collated_data( + collator=data_collator, original_data=features_original, batch_data=features_batch + ) + + def test_for_token_classification_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_base = [ + {"input_ids": (0, 1, 2), "labels": (0, 1, 2)}, + {"input_ids": (0, 1, 2, 3, 4, 5), "labels": (0, 1, 2, 3, 4, 5)}, + ] + token_classification_collators = [ + DataCollatorForTokenClassification(tokenizer), + DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10), + DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8), + DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1), + ] + + for datatype_input, datatype_label in [(list, list), (torch.tensor, torch.tensor)]: + for collator in token_classification_collators: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=collator, + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ) + + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=token_classification_collators[-1], + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + def test_seq2seq_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_base = [ + {"input_ids": list(range(3)), "labels": list(range(3))}, + {"input_ids": list(range(6)), "labels": list(range(6))}, + ] + seq2seq_collators = [ + DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST), + DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.MAX_LENGTH, max_length=7), + DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, pad_to_multiple_of=8), + DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, label_pad_token_id=-1), + ] + + for datatype_input, datatype_label in [(list, list), (torch.tensor, torch.tensor)]: + for collator in seq2seq_collators: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=collator, + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ) + + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=seq2seq_collators[-1], + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + features_base_no_pad = [ + {"input_ids": list(range(3)), "labels": list(range(3))}, + {"input_ids": list(range(3)), "labels": list(range(3))}, + ] + seq2seq_no_padding_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.DO_NOT_PAD) + for datatype_input, datatype_label in [(list, list), (torch.tensor, torch.tensor)]: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=seq2seq_no_padding_collator, + base_data=features_base_no_pad, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ) + + def test_language_modelling_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_base_no_pad = [ + {"input_ids": tuple(range(10)), "labels": (1,)}, + {"input_ids": tuple(range(10)), "labels": (1,)}, + ] + features_base_pad = [ + {"input_ids": tuple(range(5)), "labels": (1,)}, + {"input_ids": tuple(range(5)), "labels": (1,)}, + ] + lm_collators = [ + DataCollatorForLanguageModeling(tokenizer, mlm=False), + DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8), + DataCollatorForLanguageModeling(tokenizer), + DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8), + ] + + for datatype_input, datatype_label in [(list, list), (torch.tensor, torch.tensor)]: + for collator in lm_collators: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=collator, + base_data=features_base_no_pad, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=collator, + base_data=features_base_pad, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + def test_whole_world_masking_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_base = [ + {"input_ids": list(range(10)), "labels": (1,)}, + {"input_ids": list(range(10)), "labels": (1,)}, + ] + whole_word_masking_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="pt") + + for datatype_input, datatype_label in [(list, list), (np.array, np.array)]: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=whole_word_masking_collator, + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + def test_permutation_language_modelling_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + plm_collator = DataCollatorForPermutationLanguageModeling(tokenizer) + + no_pad_features_original = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + no_pad_features_batch = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + self._validate_original_data_against_collated_data( + collator=plm_collator, original_data=no_pad_features_original, batch_data=no_pad_features_batch + ) + + pad_features_original = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + pad_features_batch = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + self._validate_original_data_against_collated_data( + collator=plm_collator, original_data=pad_features_original, batch_data=pad_features_batch + ) + + def test_next_sentence_prediction_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_original = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + features_batch = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + + nsp_collator = DataCollatorForLanguageModeling(tokenizer) + self._validate_original_data_against_collated_data( + collator=nsp_collator, original_data=features_original, batch_data=features_batch + ) + + nsp_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) + self._validate_original_data_against_collated_data( + collator=nsp_collator, original_data=features_original, batch_data=features_batch + ) + + def test_sentence_order_prediction_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_original = [ + { + "input_ids": torch.tensor([0, 1, 2, 3, 4]), + "token_type_ids": torch.tensor([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + features_batch = [ + { + "input_ids": torch.tensor([0, 1, 2, 3, 4]), + "token_type_ids": torch.tensor([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + + sop_collator = DataCollatorForLanguageModeling(tokenizer) + self._validate_original_data_against_collated_data( + collator=sop_collator, original_data=features_original, batch_data=features_batch + ) + + sop_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8) + self._validate_original_data_against_collated_data( + collator=sop_collator, original_data=features_original, batch_data=features_batch + ) + + +class NumpyDataCollatorIntegrationTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] + self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def test_default_with_dict(self): + features = [{"label": i, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].tolist(), list(range(8))) + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["inputs"].shape, (8, 6)) + + # With label_ids + features = [{"label_ids": [0, 1, 2], "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].tolist(), [[0, 1, 2]] * 8) + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["inputs"].shape, (8, 6)) + + # Features can already be tensors + features = [{"label": i, "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].tolist(), list(range(8))) + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["inputs"].shape, (8, 10)) + + # Labels can already be tensors + features = [{"label": np.array(i), "inputs": np.random.randint(0, 10, [10])} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["labels"].tolist(), (list(range(8)))) + self.assertEqual(batch["labels"].dtype, np.int64) + self.assertEqual(batch["inputs"].shape, (8, 10)) + + def test_default_classification_and_regression(self): + data_collator = default_data_collator + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": i} for i in range(4)] + batch = data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].dtype, np.int64) + + features = [{"input_ids": [0, 1, 2, 3, 4], "label": float(i)} for i in range(4)] + batch = data_collator(features, return_tensors="np") + self.assertEqual(batch["labels"].dtype, np.float32) + + def test_default_with_no_labels(self): + features = [{"label": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape, (8, 6)) + + # With label_ids + features = [{"label_ids": None, "inputs": [0, 1, 2, 3, 4, 5]} for i in range(8)] + batch = default_data_collator(features, return_tensors="np") + self.assertTrue("labels" not in batch) + self.assertEqual(batch["inputs"].shape, (8, 6)) + + def test_data_collator_with_padding(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + + data_collator = DataCollatorWithPadding(tokenizer, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + + data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 8)) + + def test_data_collator_with_flattening(self): + features = [ + {"input_ids": [10, 11, 12]}, + {"input_ids": [20, 21, 22, 23, 24, 25]}, + {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, + ] + + data_collator = DataCollatorWithFlattening(return_tensors="np") + batch = data_collator(features) + + for unexpected_key in [ + "attention_mask", + "cu_seq_lens_k", + "cu_seq_lens_q", + "max_length_k", + "max_length_q", + "seq_idx", + ]: + self.assertNotIn(unexpected_key, batch) + self.assertIn("position_ids", batch) + + self.assertEqual(batch["input_ids"].shape, (1, 16)) + self.assertEqual( + batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] + ) + self.assertEqual(batch["position_ids"].shape, (1, 16)) + self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) + + def test_data_collator_with_flattening_flash_attn_kwargs(self): + features = [ + {"input_ids": [10, 11, 12]}, + {"input_ids": [20, 21, 22, 23, 24, 25]}, + {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, + ] + + data_collator = DataCollatorWithFlattening(return_tensors="np", return_flash_attn_kwargs=True) + batch = data_collator(features) + + for unexpected_key in [ + "attention_mask", + "seq_idx", + ]: + self.assertNotIn(unexpected_key, batch) + for expected_key in [ + "position_ids", + "cu_seq_lens_k", + "cu_seq_lens_q", + "max_length_k", + "max_length_q", + ]: + self.assertIn(expected_key, batch) + + self.assertEqual(batch["input_ids"].shape, (1, 16)) + self.assertEqual( + batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] + ) + self.assertEqual(batch["position_ids"].shape, (1, 16)) + self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) + + self.assertEqual(batch["cu_seq_lens_k"].shape, (4,)) + self.assertEqual(batch["cu_seq_lens_k"].tolist(), [0, 3, 9, 16]) + self.assertEqual(batch["cu_seq_lens_q"].shape, (4,)) + self.assertEqual(batch["cu_seq_lens_q"].tolist(), [0, 3, 9, 16]) + # The flash attn max_length_{k,q} are simple python ints + self.assertEqual(batch["max_length_k"], 7) + self.assertEqual(batch["max_length_q"], 7) + + def test_data_collator_with_flattening_seq_idx(self): + features = [ + {"input_ids": [10, 11, 12]}, + {"input_ids": [20, 21, 22, 23, 24, 25]}, + {"input_ids": [30, 31, 32, 33, 34, 35, 36]}, + ] + + data_collator = DataCollatorWithFlattening(return_tensors="np", return_seq_idx=True) + batch = data_collator(features) + + for unexpected_key in [ + "attention_mask", + "cu_seq_lens_k", + "cu_seq_lens_q", + "max_length_k", + "max_length_q", + ]: + self.assertNotIn(unexpected_key, batch) + for expected_key in [ + "position_ids", + "seq_idx", + ]: + self.assertIn(expected_key, batch) + + self.assertEqual(batch["input_ids"].shape, (1, 16)) + self.assertEqual( + batch["input_ids"][0].tolist(), [10, 11, 12, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35, 36] + ) + self.assertEqual(batch["position_ids"].shape, (1, 16)) + self.assertEqual(batch["position_ids"][0].tolist(), [0, 1, 2, 0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5, 6]) + self.assertEqual(batch["seq_idx"].shape, batch["input_ids"].shape) + self.assertEqual(batch["seq_idx"][0].tolist(), [0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2]) + + def test_data_collator_for_token_classification(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2], "labels": [0, 1, 2]}, + {"input_ids": [0, 1, 2, 3, 4, 5], "labels": [0, 1, 2, 3, 4, 5]}, + ] + + data_collator = DataCollatorForTokenClassification(tokenizer, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, (2, 6)) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-100] * 3) + + data_collator = DataCollatorForTokenClassification( + tokenizer, padding="max_length", max_length=10, return_tensors="np" + ) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + data_collator = DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 8)) + self.assertEqual(batch["labels"].shape, (2, 8)) + + data_collator = DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), [0, 1, 2] + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["labels"].shape, (2, 6)) + self.assertEqual(batch["labels"][0].tolist(), [0, 1, 2] + [-1] * 3) + + def test_data_collator_for_seq2seq(self): + def create_features(): + return [ + {"input_ids": list(range(3)), "labels": list(range(3))}, + {"input_ids": list(range(6)), "labels": list(range(6))}, + ] + + tokenizer = BertTokenizer(self.vocab_file) + features = create_features() + + data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, return_tensors="np") + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["input_ids"][1].tolist(), list(range(6))) + self.assertEqual(batch["labels"].shape, (2, 6)) + self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-100] * 3) + self.assertEqual(batch["labels"][1].tolist(), list(range(6))) + + data_collator = DataCollatorForSeq2Seq( + tokenizer, padding=PaddingStrategy.MAX_LENGTH, max_length=7, return_tensors="np" + ) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 7)) + self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 4) + self.assertEqual(batch["input_ids"][1].tolist(), list(range(6)) + [tokenizer.pad_token_id] * 1) + self.assertEqual(batch["labels"].shape, (2, 7)) + self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-100] * 4) + self.assertEqual(batch["labels"][1].tolist(), list(range(6)) + [-100] * 1) + + data_collator = DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.DO_NOT_PAD, return_tensors="np") + # numpy doesn't have issues handling unequal shapes via `dtype=object` + # with self.assertRaises(ValueError): + # data_collator(features) + batch = data_collator([features[0], features[0]]) + self.assertEqual(batch["input_ids"][0].tolist(), features[0]["input_ids"]) + self.assertEqual(batch["input_ids"][1].tolist(), features[0]["input_ids"]) + self.assertEqual(batch["labels"][0].tolist(), features[0]["labels"]) + self.assertEqual(batch["labels"][1].tolist(), features[0]["labels"]) + + data_collator = DataCollatorForSeq2Seq( + tokenizer, padding=PaddingStrategy.LONGEST, pad_to_multiple_of=8, return_tensors="np" + ) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 8)) + self.assertEqual(batch["labels"].shape, (2, 8)) + + # side effects on labels cause mismatch on longest strategy + features = create_features() + + data_collator = DataCollatorForSeq2Seq( + tokenizer, padding=PaddingStrategy.LONGEST, label_pad_token_id=-1, return_tensors="np" + ) + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) + self.assertEqual(batch["input_ids"][1].tolist(), list(range(6))) + self.assertEqual(batch["labels"].shape, (2, 6)) + self.assertEqual(batch["labels"][0].tolist(), list(range(3)) + [-1] * 3) + self.assertEqual(batch["labels"][1].tolist(), list(range(6))) + + for feature in features: + feature.pop("labels") + + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 6)) + self.assertEqual(batch["input_ids"][0].tolist(), list(range(3)) + [tokenizer.pad_token_id] * 3) + + def _test_no_pad_and_pad(self, no_pad_features, pad_features): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="np") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + batch = data_collator(pad_features, return_tensors="np") + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + data_collator = DataCollatorForLanguageModeling( + tokenizer, mlm=False, pad_to_multiple_of=8, return_tensors="np" + ) + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 16)) + self.assertEqual(batch["labels"].shape, (2, 16)) + + batch = data_collator(pad_features, return_tensors="np") + self.assertEqual(batch["input_ids"].shape, (2, 16)) + self.assertEqual(batch["labels"].shape, (2, 16)) + + tokenizer.pad_token = None + data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="np") + with self.assertRaises(ValueError): + # Expect error due to padding token missing + data_collator(pad_features) + + set_seed(42) # For reproducibility + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(np.any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(np.any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(no_pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 16)) + self.assertEqual(batch["labels"].shape, (2, 16)) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(np.any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + batch = data_collator(pad_features) + self.assertEqual(batch["input_ids"].shape, (2, 16)) + self.assertEqual(batch["labels"].shape, (2, 16)) + + masked_tokens = batch["input_ids"] == tokenizer.mask_token_id + self.assertTrue(np.any(masked_tokens)) + # self.assertTrue(all(x == -100 for x in batch["labels"][~masked_tokens].tolist())) + + def test_data_collator_for_language_modeling(self): + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + no_pad_features = [list(range(10)), list(range(10))] + pad_features = [list(range(5)), list(range(10))] + self._test_no_pad_and_pad(no_pad_features, pad_features) + + def test_data_collator_for_language_modeling_with_seed(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": list(range(1000))}, {"input_ids": list(range(1000))}] + + # check if seed is respected between two different DataCollatorForLanguageModeling instances + data_collator = DataCollatorForLanguageModeling(tokenizer, seed=42, return_tensors="np") + batch_1 = data_collator(features) + self.assertEqual(batch_1["input_ids"].shape, (2, 1000)) + self.assertEqual(batch_1["labels"].shape, (2, 1000)) + + data_collator = DataCollatorForLanguageModeling(tokenizer, seed=42, return_tensors="np") + batch_2 = data_collator(features) + self.assertEqual(batch_2["input_ids"].shape, (2, 1000)) + self.assertEqual(batch_2["labels"].shape, (2, 1000)) + + self.assertTrue(np.all(batch_1["input_ids"] == batch_2["input_ids"])) + self.assertTrue(np.all(batch_1["labels"] == batch_2["labels"])) + + data_collator = DataCollatorForLanguageModeling(tokenizer, seed=43, return_tensors="np") + batch_3 = data_collator(features) + self.assertEqual(batch_3["input_ids"].shape, (2, 1000)) + self.assertEqual(batch_3["labels"].shape, (2, 1000)) + + self.assertFalse(np.all(batch_1["input_ids"] == batch_3["input_ids"])) + self.assertFalse(np.all(batch_1["labels"] == batch_3["labels"])) + + def test_data_collator_for_whole_word_mask(self): + tokenizer = BertTokenizer(self.vocab_file) + data_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="np") + + features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + # Features can already be tensors + features = [{"input_ids": np.arange(10)}, {"input_ids": np.arange(10)}] + batch = data_collator(features) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + def test_data_collator_for_whole_word_mask_with_seed(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [{"input_ids": list(range(1000))}, {"input_ids": list(range(1000))}] + + # check if seed is respected between two different DataCollatorForWholeWordMask instances + data_collator = DataCollatorForWholeWordMask(tokenizer, seed=42, return_tensors="np") + batch_1 = data_collator(features) + self.assertEqual(batch_1["input_ids"].shape, (2, 1000)) + self.assertEqual(batch_1["labels"].shape, (2, 1000)) + + data_collator = DataCollatorForWholeWordMask(tokenizer, seed=42, return_tensors="np") + batch_2 = data_collator(features) + self.assertEqual(batch_2["input_ids"].shape, (2, 1000)) + self.assertEqual(batch_2["labels"].shape, (2, 1000)) + + self.assertTrue(np.all(batch_1["input_ids"] == batch_2["input_ids"])) + self.assertTrue(np.all(batch_1["labels"] == batch_2["labels"])) + + data_collator = DataCollatorForWholeWordMask(tokenizer, seed=43, return_tensors="np") + batch_3 = data_collator(features) + self.assertEqual(batch_3["input_ids"].shape, (2, 1000)) + self.assertEqual(batch_3["labels"].shape, (2, 1000)) + + self.assertFalse(np.all(batch_1["input_ids"] == batch_3["input_ids"])) + self.assertFalse(np.all(batch_1["labels"] == batch_3["labels"])) + + def test_plm(self): + tokenizer = BertTokenizer(self.vocab_file) + no_pad_features = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + pad_features = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + + data_collator = DataCollatorForPermutationLanguageModeling(tokenizer, return_tensors="np") + + batch = data_collator(pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["perm_mask"].shape, (2, 10, 10)) + self.assertEqual(batch["target_mapping"].shape, (2, 10, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + batch = data_collator(no_pad_features) + self.assertIsInstance(batch, dict) + self.assertEqual(batch["input_ids"].shape, (2, 10)) + self.assertEqual(batch["perm_mask"].shape, (2, 10, 10)) + self.assertEqual(batch["target_mapping"].shape, (2, 10, 10)) + self.assertEqual(batch["labels"].shape, (2, 10)) + + example = [np.random.randint(0, 5, [5])] + with self.assertRaises(ValueError): + # Expect error due to odd sequence length + data_collator(example) + + def test_nsp(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, (2, 5)) + self.assertEqual(batch["token_type_ids"].shape, (2, 5)) + self.assertEqual(batch["labels"].shape, (2, 5)) + self.assertEqual(batch["next_sentence_label"].shape, (2,)) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, (2, 8)) + self.assertEqual(batch["token_type_ids"].shape, (2, 8)) + self.assertEqual(batch["labels"].shape, (2, 8)) + self.assertEqual(batch["next_sentence_label"].shape, (2,)) + + def test_sop(self): + tokenizer = BertTokenizer(self.vocab_file) + features = [ + { + "input_ids": np.array([0, 1, 2, 3, 4]), + "token_type_ids": np.array([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + data_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, (2, 5)) + self.assertEqual(batch["token_type_ids"].shape, (2, 5)) + self.assertEqual(batch["labels"].shape, (2, 5)) + self.assertEqual(batch["sentence_order_label"].shape, (2,)) + + data_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") + batch = data_collator(features) + + self.assertEqual(batch["input_ids"].shape, (2, 8)) + self.assertEqual(batch["token_type_ids"].shape, (2, 8)) + self.assertEqual(batch["labels"].shape, (2, 8)) + self.assertEqual(batch["sentence_order_label"].shape, (2,)) + + +class NumpyDataCollatorImmutabilityTest(unittest.TestCase): + def setUp(self): + self.tmpdirname = tempfile.mkdtemp() + + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]"] + self.vocab_file = os.path.join(self.tmpdirname, "vocab.txt") + with open(self.vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in vocab_tokens])) + + def tearDown(self): + shutil.rmtree(self.tmpdirname) + + def _turn_to_none(self, item): + """used to convert `item` to `None` type""" + return None + + def _validate_original_data_against_collated_data(self, collator, original_data, batch_data): + # we only care about side effects, the results are tested elsewhere + collator(batch_data) + + # we go through every item and convert to `primitive` datatypes if necessary + # then compares for equivalence for the original data and the data that has been passed through the collator + for original, batch in zip(original_data, batch_data): + for original_val, batch_val in zip(original.values(), batch.values()): + if isinstance(original_val, np.ndarray): + self.assertEqual(original_val.tolist(), batch_val.tolist()) + else: + self.assertEqual(original_val, batch_val) + + def _validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + self, collator, base_data, input_key, input_datatype, label_key, label_datatype, ignore_label=False + ): + # using the arguments to recreate the features with their respective (potentially new) datatypes + features_original = [ + {label_key: label_datatype(sample[label_key]), input_key: input_datatype(sample[input_key])} + for sample in base_data + ] + features_batch = [ + {label_key: label_datatype(sample[label_key]), input_key: input_datatype(sample[input_key])} + for sample in base_data + ] + + # some collators do not use labels, or sometimes we want to check if the collator with labels can handle such cases + if ignore_label: + for original, batch in zip(features_original, features_batch): + original.pop(label_key) + batch.pop(label_key) + + self._validate_original_data_against_collated_data( + collator=collator, original_data=features_original, batch_data=features_batch + ) + + def test_default_collator_immutability(self): + features_base_single_label = [{"label": i, "inputs": (0, 1, 2, 3, 4, 5)} for i in range(4)] + features_base_multiple_labels = [{"label": (0, 1, 2), "inputs": (0, 1, 2, 3, 4, 5)} for i in range(4)] + + for datatype_input, datatype_label in [ + (list, int), + (list, float), + (np.array, int), + (np.array, np.array), + (list, self._turn_to_none), + ]: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=lambda x: default_data_collator(x, return_tensors="np"), + base_data=features_base_single_label, + input_key="inputs", + input_datatype=datatype_input, + label_key="label", + label_datatype=datatype_label, + ) + + for datatype_input, datatype_label in [(list, list), (list, self._turn_to_none)]: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=lambda x: default_data_collator(x, return_tensors="np"), + base_data=features_base_multiple_labels, + input_key="inputs", + input_datatype=datatype_input, + label_key="label", + label_datatype=datatype_label, + ) + + features_base_single_label_alt = [{"input_ids": (0, 1, 2, 3, 4), "label": float(i)} for i in range(4)] + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=lambda x: default_data_collator(x, return_tensors="np"), + base_data=features_base_single_label_alt, + input_key="input_ids", + input_datatype=list, + label_key="label", + label_datatype=float, + ) + + def test_with_padding_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_original = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + features_batch = [{"input_ids": [0, 1, 2]}, {"input_ids": [0, 1, 2, 3, 4, 5]}] + + data_collator = DataCollatorWithPadding(tokenizer, padding="max_length", max_length=10, return_tensors="np") + self._validate_original_data_against_collated_data( + collator=data_collator, original_data=features_original, batch_data=features_batch + ) + + data_collator = DataCollatorWithPadding(tokenizer, pad_to_multiple_of=8, return_tensors="np") + self._validate_original_data_against_collated_data( + collator=data_collator, original_data=features_original, batch_data=features_batch + ) + + def test_for_token_classification_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_base = [ + {"input_ids": (0, 1, 2), "labels": (0, 1, 2)}, + {"input_ids": (0, 1, 2, 3, 4, 5), "labels": (0, 1, 2, 3, 4, 5)}, + ] + token_classification_collators = [ + DataCollatorForTokenClassification(tokenizer, return_tensors="np"), + DataCollatorForTokenClassification(tokenizer, padding="max_length", max_length=10, return_tensors="np"), + DataCollatorForTokenClassification(tokenizer, pad_to_multiple_of=8, return_tensors="np"), + DataCollatorForTokenClassification(tokenizer, label_pad_token_id=-1, return_tensors="np"), + ] + + for datatype_input, datatype_label in [(list, list)]: + for collator in token_classification_collators: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=collator, + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ) + + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=token_classification_collators[-1], + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + def test_seq2seq_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_base = [ + {"input_ids": list(range(3)), "labels": list(range(3))}, + {"input_ids": list(range(6)), "labels": list(range(6))}, + ] + seq2seq_collators = [ + DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.LONGEST, return_tensors="np"), + DataCollatorForSeq2Seq(tokenizer, padding=PaddingStrategy.MAX_LENGTH, max_length=7, return_tensors="np"), + DataCollatorForSeq2Seq( + tokenizer, padding=PaddingStrategy.LONGEST, pad_to_multiple_of=8, return_tensors="np" + ), + DataCollatorForSeq2Seq( + tokenizer, padding=PaddingStrategy.LONGEST, label_pad_token_id=-1, return_tensors="np" + ), + ] + + for datatype_input, datatype_label in [(list, list)]: + for collator in seq2seq_collators: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=collator, + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ) + + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=seq2seq_collators[-1], + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + features_base_no_pad = [ + {"input_ids": list(range(3)), "labels": list(range(3))}, + {"input_ids": list(range(3)), "labels": list(range(3))}, + ] + seq2seq_no_padding_collator = DataCollatorForSeq2Seq( + tokenizer, padding=PaddingStrategy.DO_NOT_PAD, return_tensors="np" + ) + for datatype_input, datatype_label in [(list, list)]: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=seq2seq_no_padding_collator, + base_data=features_base_no_pad, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ) + + def test_language_modelling_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_base_no_pad = [ + {"input_ids": tuple(range(10)), "labels": (1,)}, + {"input_ids": tuple(range(10)), "labels": (1,)}, + ] + features_base_pad = [ + {"input_ids": tuple(range(5)), "labels": (1,)}, + {"input_ids": tuple(range(5)), "labels": (1,)}, + ] + lm_collators = [ + DataCollatorForLanguageModeling(tokenizer, mlm=False, return_tensors="np"), + DataCollatorForLanguageModeling(tokenizer, mlm=False, pad_to_multiple_of=8, return_tensors="np"), + DataCollatorForLanguageModeling(tokenizer, return_tensors="np"), + DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np"), + ] + + for datatype_input, datatype_label in [(list, list)]: + for collator in lm_collators: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=collator, + base_data=features_base_no_pad, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=collator, + base_data=features_base_pad, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + def test_whole_world_masking_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_base = [ + {"input_ids": list(range(10)), "labels": (1,)}, + {"input_ids": list(range(10)), "labels": (1,)}, + ] + whole_word_masking_collator = DataCollatorForWholeWordMask(tokenizer, return_tensors="np") + + for datatype_input, datatype_label in [(list, list), (np.array, np.array)]: + self._validate_original_data_against_collated_data_on_specified_keys_and_datatypes( + collator=whole_word_masking_collator, + base_data=features_base, + input_key="input_ids", + input_datatype=datatype_input, + label_key="labels", + label_datatype=datatype_label, + ignore_label=True, + ) + + def test_permutation_language_modelling_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + plm_collator = DataCollatorForPermutationLanguageModeling(tokenizer, return_tensors="np") + + no_pad_features_original = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + no_pad_features_batch = [{"input_ids": list(range(10))}, {"input_ids": list(range(10))}] + self._validate_original_data_against_collated_data( + collator=plm_collator, original_data=no_pad_features_original, batch_data=no_pad_features_batch + ) + + pad_features_original = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + pad_features_batch = [{"input_ids": list(range(5))}, {"input_ids": list(range(10))}] + self._validate_original_data_against_collated_data( + collator=plm_collator, original_data=pad_features_original, batch_data=pad_features_batch + ) + + def test_next_sentence_prediction_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_original = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + features_batch = [ + {"input_ids": [0, 1, 2, 3, 4], "token_type_ids": [0, 1, 2, 3, 4], "next_sentence_label": i} + for i in range(2) + ] + + nsp_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") + self._validate_original_data_against_collated_data( + collator=nsp_collator, original_data=features_original, batch_data=features_batch + ) + + nsp_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") + self._validate_original_data_against_collated_data( + collator=nsp_collator, original_data=features_original, batch_data=features_batch + ) + + def test_sentence_order_prediction_collator_immutability(self): + tokenizer = BertTokenizer(self.vocab_file) + + features_original = [ + { + "input_ids": np.array([0, 1, 2, 3, 4]), + "token_type_ids": np.array([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + features_batch = [ + { + "input_ids": np.array([0, 1, 2, 3, 4]), + "token_type_ids": np.array([0, 1, 2, 3, 4]), + "sentence_order_label": i, + } + for i in range(2) + ] + + sop_collator = DataCollatorForLanguageModeling(tokenizer, return_tensors="np") + self._validate_original_data_against_collated_data( + collator=sop_collator, original_data=features_original, batch_data=features_batch + ) + + sop_collator = DataCollatorForLanguageModeling(tokenizer, pad_to_multiple_of=8, return_tensors="np") + self._validate_original_data_against_collated_data( + collator=sop_collator, original_data=features_original, batch_data=features_batch + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer.py new file mode 100644 index 0000000000000000000000000000000000000000..a609b75ea0c76ea252a979cd19ae24aff3a13b98 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer.py @@ -0,0 +1,6107 @@ +# Copyright 2018 the HuggingFace Inc. team. +# +# 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. + +import dataclasses +import gc +import importlib +import json +import math +import os +import random +import re +import subprocess +import sys +import tempfile +import unittest +from functools import partial +from itertools import product +from pathlib import Path +from typing import Any +from unittest.mock import Mock, patch + +import numpy as np +import pytest +from huggingface_hub import HfFolder, ModelCard, create_branch, list_repo_commits, list_repo_files +from packaging import version +from parameterized import parameterized + +from transformers import ( + AutoFeatureExtractor, + AutoImageProcessor, + AutoProcessor, + AutoTokenizer, + DataCollatorForLanguageModeling, + IntervalStrategy, + PretrainedConfig, + TrainerCallback, + TrainingArguments, + default_data_collator, + enable_full_determinism, + get_polynomial_decay_schedule_with_warmup, + is_datasets_available, + is_torch_available, + logging, + set_seed, +) +from transformers.hyperparameter_search import ALL_HYPERPARAMETER_SEARCH_BACKENDS +from transformers.testing_utils import ( + ENDPOINT_STAGING, + TOKEN, + USER, + CaptureLogger, + LoggingLevel, + TemporaryHubRepo, + TestCasePlus, + backend_device_count, + backend_empty_cache, + backend_max_memory_allocated, + backend_memory_allocated, + backend_reset_max_memory_allocated, + backend_reset_peak_memory_stats, + evaluate_side_effect_factory, + execute_subprocess_async, + get_gpu_count, + get_steps_per_epoch, + get_tests_dir, + is_staging_test, + require_accelerate, + require_apollo_torch, + require_bitsandbytes, + require_deepspeed, + require_galore_torch, + require_grokadamw, + require_liger_kernel, + require_lomo, + require_non_hpu, + require_optuna, + require_peft, + require_ray, + require_safetensors, + require_schedulefree, + require_sentencepiece, + require_sigopt, + require_tensorboard, + require_tokenizers, + require_torch, + require_torch_accelerator, + require_torch_bf16, + require_torch_fp16, + require_torch_gpu, + require_torch_multi_accelerator, + require_torch_non_multi_accelerator, + require_torch_non_multi_gpu, + require_torch_optimi, + require_torch_tensorrt_fx, + require_torch_tf32, + require_torch_up_to_2_accelerators, + require_vision, + require_wandb, + run_first, + run_test_using_subprocess, + slow, + torch_device, +) +from transformers.trainer_utils import PREFIX_CHECKPOINT_DIR, HPSearchBackend, check_target_module_exists +from transformers.training_args import OptimizerNames +from transformers.utils import ( + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + check_torch_load_is_safe, + is_accelerate_available, + is_apex_available, + is_bitsandbytes_available, + is_safetensors_available, + is_torchao_available, + is_torchdistx_available, +) +from transformers.utils.hp_naming import TrialShortNamer + + +if torch_device == "hpu": + RTOL = 1e-3 + ATOL = 1e-3 +else: + RTOL = 1e-5 + ATOL = 1e-5 + +if is_torch_available(): + import torch + from torch import nn + from torch.utils.data import IterableDataset + + import transformers.optimization + from transformers import ( + AutoModelForCausalLM, + AutoModelForSequenceClassification, + EarlyStoppingCallback, + GlueDataset, + GlueDataTrainingArguments, + GPT2Config, + GPT2LMHeadModel, + LineByLineTextDataset, + LlamaConfig, + LlamaForCausalLM, + PreTrainedModel, + Trainer, + TrainerState, + ) + from transformers.trainer_pt_utils import AcceleratorConfig + + if is_safetensors_available(): + import safetensors.torch + +if is_datasets_available(): + import datasets + +# for version specific tests in TrainerIntegrationTest +require_accelerate_version_min_0_28 = partial(require_accelerate, min_version="0.28") +require_accelerate_version_min_0_30 = partial(require_accelerate, min_version="0.30") +GRAD_ACCUM_KWARGS_VERSION_AVAILABLE = is_accelerate_available("0.28") +if is_accelerate_available(): + from accelerate import Accelerator + from accelerate.state import AcceleratorState + + +PATH_SAMPLE_TEXT = f"{get_tests_dir()}/fixtures/sample_text.txt" + + +class StoreLossCallback(TrainerCallback): + """ + Simple callback to store the loss. + """ + + def __init__(self): + self.losses = [] + + def on_log(self, args, state, control, logs=None, **kwargs): + if "loss" in logs: + self.losses.append(logs["loss"]) + + +class MockCudaOOMCallback(TrainerCallback): + """ + Simple callback to simulate CUDA OOM error if + the batch size is >= to `batch_size_limit`. + """ + + def __init__(self, batch_size_limit=16): + self.batch_size_limit = batch_size_limit + + def on_step_end(self, args, state, control, **kwargs): + # simulate OOM on the first step + if state.train_batch_size >= self.batch_size_limit: + raise RuntimeError("CUDA out of memory.") + + +def ForCausalLMLoss(logits, labels, vocab_size, num_items_in_batch, disable_num_items_in_batch=False): + # Upcast to float if we need to compute the loss to avoid potential precision issues + logits = logits.float() + # Shift so that tokens < n predict n + shift_logits = logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + + # Flatten the tokens + shift_logits = shift_logits.view(-1, vocab_size) + shift_labels = shift_labels.view(-1) + # Enable model parallelism + shift_labels = shift_labels.to(shift_logits.device) + if num_items_in_batch is None or disable_num_items_in_batch: + loss = nn.functional.cross_entropy(shift_logits, shift_labels, ignore_index=-100, reduction="mean") + else: + loss = nn.functional.cross_entropy(shift_logits, shift_labels, ignore_index=-100, reduction="sum") + loss = loss / num_items_in_batch + return loss + + +class RegressionDataset: + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + np.random.seed(seed) + self.label_names = ["labels"] if label_names is None else label_names + self.length = length + self.x = np.random.normal(size=(length,)).astype(np.float32) + self.ys = [a * self.x + b + np.random.normal(scale=0.1, size=(length,)) for _ in self.label_names] + self.ys = [y.astype(np.float32) for y in self.ys] + + def __len__(self): + return self.length + + def __getitem__(self, i): + result = {name: y[i] for name, y in zip(self.label_names, self.ys)} + result["input_x"] = self.x[i] + return result + + +# Converting Bytes to Megabytes +def bytes2megabytes(x): + return int(x / 2**20) + + +# Copied from accelerate: https://github.com/huggingface/accelerate/blob/ee163b66fb7848892519e804688cb4ae981aacbe/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py#L40C1-L73C68 +class TorchTracemalloc: + def __enter__(self): + gc.collect() + if torch_device in ["cuda", "xpu"]: + backend_empty_cache(torch_device) + backend_reset_max_memory_allocated(torch_device) # reset the peak gauge to zero + self.begin = backend_memory_allocated(torch_device) + return self + + def __exit__(self, *exc): + gc.collect() + if torch_device in ["cuda", "xpu"]: + backend_empty_cache(torch_device) + self.end = backend_memory_allocated(torch_device) + self.peak = backend_max_memory_allocated(torch_device) + self.used = bytes2megabytes(self.end - self.begin) + self.peaked = bytes2megabytes(self.peak - self.begin) + + +@dataclasses.dataclass +class RegressionTrainingArguments(TrainingArguments): + a: float = 0.0 + b: float = 0.0 + keep_report_to: bool = False + + def __post_init__(self): + super().__post_init__() + # save resources not dealing with reporting unless specified (also avoids the warning when it's not set) + # can be explicitly disabled via `keep_report_to` + if not self.keep_report_to: + self.report_to = [] + + +class RepeatDataset: + def __init__(self, x, length=64): + self.x = x + self.length = length + + def __len__(self): + return self.length + + def __getitem__(self, i): + return {"input_ids": self.x, "labels": self.x} + + +class SequenceClassificationDataset: + def __init__(self, length=64, vocab_size=100, num_labels=5): + self.length = length + self.sequences = [torch.randint(0, vocab_size, (64,)).tolist() for _ in range(length)] + self.labels = torch.randint(0, num_labels, (length,)).tolist() + + def __len__(self): + return self.length + + def __getitem__(self, i): + return {"input_ids": self.sequences[i], "label": self.labels[i]} + + +class DynamicShapesDataset: + def __init__(self, length=64, seed=42, batch_size=8): + self.length = length + np.random.seed(seed) + sizes = np.random.randint(1, 20, (length // batch_size,)) + # For easy batching, we make every batch_size consecutive samples the same size. + self.xs = [np.random.normal(size=(s,)).astype(np.float32) for s in sizes.repeat(batch_size)] + self.ys = [np.random.normal(size=(s,)).astype(np.float32) for s in sizes.repeat(batch_size)] + + def __len__(self): + return self.length + + def __getitem__(self, i): + return {"input_x": self.xs[i], "labels": self.ys[i]} + + +class AlmostAccuracy: + def __init__(self, thresh=0.25): + self.thresh = thresh + + def __call__(self, eval_pred): + predictions, labels = eval_pred + true = np.abs(predictions - labels) <= self.thresh + return {"accuracy": true.astype(np.float32).mean().item()} + + +class AlmostAccuracyBatched: + def __init__(self, thresh=0.25): + self.thresh = thresh + self.batch_acc = [] + + def __call__(self, eval_pred, compute_result): + predictions, labels = eval_pred + if isinstance(predictions, tuple): + predictions = predictions[0] + if isinstance(labels, tuple): + labels = labels[0] + batch_size = len(predictions) + true = torch.abs(predictions - labels) <= self.thresh + acc = true.type(torch.FloatTensor).mean().item() + self.batch_acc.extend([acc] * batch_size) + if compute_result: + result = {"accuracy": np.mean(self.batch_acc).item()} + self.batch_acc = [] + return result + + +class RegressionModelConfig(PretrainedConfig): + def __init__(self, a=0, b=0, double_output=False, random_torch=True, **kwargs): + super().__init__(**kwargs) + self.a = a + self.b = b + self.double_output = double_output + self.random_torch = random_torch + self.hidden_size = 1 + + +if is_torch_available(): + + class SampleIterableDataset(IterableDataset): + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + self.dataset = RegressionDataset(a=a, b=b, length=length, seed=seed, label_names=label_names) + + def __iter__(self): + for i in range(len(self.dataset)): + yield self.dataset[i] + + class FiniteIterableDataset(SampleIterableDataset): + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + super().__init__(a, b, length, seed, label_names) + self.current_sample = 0 + + def __iter__(self): + while self.current_sample < len(self.dataset): + yield self.dataset[self.current_sample] + self.current_sample += 1 + + class MultiLoader: + def __init__(self, loaders): + self.loaders = loaders + + def __len__(self): + return sum(len(loader) for loader in self.loaders) + + def __iter__(self): + for loader in self.loaders: + yield from loader + + class CustomDataloaderTrainer(Trainer): + def get_train_dataloader(self): + dataloaders = [super().get_train_dataloader(), super().get_train_dataloader()] + return MultiLoader(dataloaders) + + def get_eval_dataloader(self, eval_dataset): + dataloaders = [super().get_eval_dataloader(eval_dataset), super().get_eval_dataloader(eval_dataset)] + return MultiLoader(dataloaders) + + class RegressionModel(nn.Module): + def __init__(self, a=0, b=0, double_output=False): + super().__init__() + self.a = nn.Parameter(torch.tensor(a).float()) + self.b = nn.Parameter(torch.tensor(b).float()) + self.double_output = double_output + self.config = None + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + if labels is None: + return (y, y) if self.double_output else (y,) + loss = nn.functional.mse_loss(y, labels) + return (loss, y, y) if self.double_output else (loss, y) + + class RegressionDictModel(nn.Module): + def __init__(self, a=0, b=0): + super().__init__() + self.a = nn.Parameter(torch.tensor(a).float()) + self.b = nn.Parameter(torch.tensor(b).float()) + self.config = None + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + result = {"output": y} + if labels is not None: + result["loss"] = nn.functional.mse_loss(y, labels) + return result + + class RegressionPreTrainedModel(PreTrainedModel): + config_class = RegressionModelConfig + base_model_prefix = "regression" + + def __init__(self, config): + super().__init__(config) + self.a = nn.Parameter(torch.tensor(config.a).float()) + self.b = nn.Parameter(torch.tensor(config.b).float()) + self.double_output = config.double_output + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + if labels is None: + return (y, y) if self.double_output else (y,) + loss = nn.functional.mse_loss(y, labels) + return (loss, y, y) if self.double_output else (loss, y) + + class RegressionPreTrainedModelWithGradientCheckpointing(PreTrainedModel): + config_class = RegressionModelConfig + base_model_prefix = "regression" + supports_gradient_checkpointing = True + + def __init__(self, config): + super().__init__(config) + self.layers = nn.ModuleList([nn.Linear(config.hidden_size, config.hidden_size) for _ in range(4)]) + self.head = nn.Linear(config.hidden_size, 1) + self.gradient_checkpointing = False + self.double_output = config.double_output + + def forward(self, input_x, labels=None, **kwargs): + y = input_x.unsqueeze(0) + + for layer in self.layers: + if self.training and self.gradient_checkpointing: + outputs = self._gradient_checkpointing_func(layer.__call__, y) + else: + outputs = layer(y) + + y = outputs * 3 + + logits = self.head(y) + + if labels is None: + return (logits, logits) if self.double_output else (logits,) + + loss = nn.functional.mse_loss(logits, labels) + + return (loss, y, y) if self.double_output else (loss, y) + + class RegressionRandomPreTrainedModel(PreTrainedModel): + config_class = RegressionModelConfig + base_model_prefix = "regression" + + def __init__(self, config): + super().__init__(config) + self.a = nn.Parameter(torch.tensor(config.a).float()) + self.b = nn.Parameter(torch.tensor(config.b).float()) + self.random_torch = config.random_torch + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + if self.random_torch: + torch_rand = torch.randn(1).squeeze() + np_rand = np.random.rand() + rand_rand = random.random() + + if self.random_torch: + y += 0.05 * torch_rand + y += 0.05 * torch.tensor(np_rand + rand_rand) + + if labels is None: + return (y,) + loss = nn.functional.mse_loss(y, labels) + return (loss, y) + + class BasicTextGenerationModel(nn.Module): + def __init__(self, vocab_size, hidden_size): + super().__init__() + self.embedding = nn.Embedding(vocab_size, hidden_size) + self.lstm = nn.LSTM(hidden_size, hidden_size, batch_first=True) + self.fc = nn.Linear(hidden_size, vocab_size) + + def forward(self, input_ids, **kwargs): + embedded = self.embedding(input_ids) + lstm_out, _ = self.lstm(embedded) + logits = self.fc(lstm_out) + return logits + + def create_dummy_dataset_for_text_generation(vocab_size, seq_length, num_samples): + import numpy as np + + # Create random input sequences + input_ids = np.random.randint(0, vocab_size, (num_samples, seq_length)) + + # Create a datasets.Dataset + dataset = datasets.Dataset.from_dict({"input_ids": input_ids, "labels": input_ids}) + + return dataset + + class TstLayer(nn.Module): + def __init__(self, hidden_size): + super().__init__() + self.linear1 = nn.Linear(hidden_size, hidden_size) + self.ln1 = nn.LayerNorm(hidden_size) + self.linear2 = nn.Linear(hidden_size, hidden_size) + self.ln2 = nn.LayerNorm(hidden_size) + self.bias = nn.Parameter(torch.zeros(hidden_size)) + + def forward(self, x): + h = self.ln1(nn.functional.relu(self.linear1(x))) + h = nn.functional.relu(self.linear2(x)) + return self.ln2(x + h + self.bias) + + def get_regression_trainer( + a=0, + b=0, + double_output=False, + train_len=64, + eval_len=64, + pretrained=True, + keep_report_to=False, + output_dir=None, + **kwargs, + ): + label_names = kwargs.get("label_names") + gradient_checkpointing = kwargs.get("gradient_checkpointing", False) + train_dataset = RegressionDataset(length=train_len, label_names=label_names) + eval_dataset = RegressionDataset(length=eval_len, label_names=label_names) + + model_init = kwargs.pop("model_init", None) + if model_init is not None: + model = None + else: + if pretrained: + config = RegressionModelConfig(a=a, b=b, double_output=double_output) + # We infer the correct model class if one uses gradient_checkpointing or not + target_cls = ( + RegressionPreTrainedModel + if not gradient_checkpointing + else RegressionPreTrainedModelWithGradientCheckpointing + ) + model = target_cls(config) + else: + model = RegressionModel(a=a, b=b, double_output=double_output) + + compute_metrics = kwargs.pop("compute_metrics", None) + data_collator = kwargs.pop("data_collator", None) + optimizers = kwargs.pop("optimizers", (None, None)) + preprocess_logits_for_metrics = kwargs.pop("preprocess_logits_for_metrics", None) + assert output_dir is not None, "output_dir should be specified for testing" + args = RegressionTrainingArguments(output_dir, a=a, b=b, keep_report_to=keep_report_to, **kwargs) + return Trainer( + model, + args, + data_collator=data_collator, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + compute_metrics=compute_metrics, + optimizers=optimizers, + model_init=model_init, + preprocess_logits_for_metrics=preprocess_logits_for_metrics, + ) + + def get_language_model_trainer(**kwargs): + dataset = datasets.load_dataset("fka/awesome-chatgpt-prompts") + model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") + tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") + tokenizer.pad_token = tokenizer.eos_token + + def _tokenize_function(examples): + model_inputs = tokenizer(examples["prompt"], padding="max_length", truncation=True) + model_inputs["labels"] = np.array(model_inputs["input_ids"]).astype(np.int64) + return model_inputs + + tokenized_datasets = dataset.map(_tokenize_function, batched=True) + training_args = TrainingArguments(**kwargs) + + trainer = Trainer( + model=model, + args=training_args, + train_dataset=tokenized_datasets["train"], + ) + + return trainer + + +class TrainerIntegrationCommon: + def check_saved_checkpoints( + self, output_dir, freq, total, is_pretrained=True, safe_weights=True, use_scaler=False + ): + weights_file = WEIGHTS_NAME if not safe_weights else SAFE_WEIGHTS_NAME + file_list = [weights_file, "training_args.bin", "optimizer.pt", "scheduler.pt", "trainer_state.json"] + if is_pretrained: + file_list.append("config.json") + if use_scaler: + file_list.append("scaler.pt") + for step in range(freq, total, freq): + checkpoint = os.path.join(output_dir, f"checkpoint-{step}") + self.assertTrue(os.path.isdir(checkpoint)) + for filename in file_list: + self.assertTrue(os.path.isfile(os.path.join(checkpoint, filename))) + + def check_best_model_has_been_loaded( + self, output_dir, freq, total, trainer, metric, greater_is_better=False, is_pretrained=True, safe_weights=True + ): + checkpoint = os.path.join(output_dir, f"checkpoint-{(total // freq) * freq}") + log_history = TrainerState.load_from_json(os.path.join(checkpoint, "trainer_state.json")).log_history + + values = [d[metric] for d in log_history] + best_value = max(values) if greater_is_better else min(values) + best_checkpoint = (values.index(best_value) + 1) * freq + checkpoint = os.path.join(output_dir, f"checkpoint-{best_checkpoint}") + if is_pretrained: + best_model = RegressionPreTrainedModel.from_pretrained(checkpoint) + best_model.to(trainer.args.device) + else: + best_model = RegressionModel() + if not safe_weights: + check_torch_load_is_safe() + state_dict = torch.load(os.path.join(checkpoint, WEIGHTS_NAME), weights_only=True) + else: + state_dict = safetensors.torch.load_file(os.path.join(checkpoint, SAFE_WEIGHTS_NAME)) + best_model.load_state_dict(state_dict) + best_model.to(trainer.args.device) + torch.testing.assert_close(best_model.a, trainer.model.a) + torch.testing.assert_close(best_model.b, trainer.model.b) + + metrics = trainer.evaluate() + self.assertEqual(metrics[metric], best_value) + + def remove_nan_logs(self, log): + for key in list(log.keys()): + if log[key] != log[key]: # Check if the value is NaN + del log[key] + + def check_trainer_state_are_the_same(self, trainer_state, trainer_state1): + # We'll pop things so operate on copies. + state = trainer_state.copy() + state1 = trainer_state1.copy() + # Log history main contain different logs for the time metrics (after resuming a training). + log_history = state.pop("log_history", None) + log_history1 = state1.pop("log_history", None) + self.assertEqual(state, state1) + skip_log_keys = ["train_runtime", "train_samples_per_second", "train_steps_per_second", "train_loss"] + for log, log1 in zip(log_history, log_history1): + for key in skip_log_keys: + _ = log.pop(key, None) + _ = log1.pop(key, None) + + self.remove_nan_logs(log) + self.remove_nan_logs(log1) + + self.assertEqual(log, log1) + + def convert_to_sharded_checkpoint(self, folder, save_safe=True, load_safe=True): + # Converts a checkpoint of a regression model to a sharded checkpoint. + if load_safe: + loader = safetensors.torch.load_file + weights_file = os.path.join(folder, SAFE_WEIGHTS_NAME) + else: + check_torch_load_is_safe() + loader = torch.load + weights_file = os.path.join(folder, WEIGHTS_NAME) + + if save_safe: + extension = "safetensors" + saver = safetensors.torch.save_file + index_file = os.path.join(folder, SAFE_WEIGHTS_INDEX_NAME) + shard_name = SAFE_WEIGHTS_NAME + else: + extension = "bin" + saver = torch.save + index_file = os.path.join(folder, WEIGHTS_INDEX_NAME) + shard_name = WEIGHTS_NAME + + state_dict = loader(weights_file) + + os.remove(weights_file) + keys = list(state_dict.keys()) + + shard_files = [ + shard_name.replace(f".{extension}", f"-{idx + 1:05d}-of-{len(keys):05d}.{extension}") + for idx in range(len(keys)) + ] + index = {"metadata": {}, "weight_map": {key: shard_files[i] for i, key in enumerate(keys)}} + + with open(index_file, "w", encoding="utf-8") as f: + content = json.dumps(index, indent=2, sort_keys=True) + "\n" + f.write(content) + + for param_name, shard_file in zip(keys, shard_files): + saver({param_name: state_dict[param_name]}, os.path.join(folder, shard_file)) + + +@require_torch +@require_sentencepiece +@require_tokenizers +class TrainerIntegrationPrerunTest(TestCasePlus, TrainerIntegrationCommon): + """ + Only tests that want to tap into the auto-pre-run 2 trainings: + - self.default_trained_model + - self.alternate_trained_model + directly, or via check_trained_model + """ + + def setUp(self): + super().setUp() + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(learning_rate=0.1, output_dir=tmp_dir) + trainer.train() + self.default_trained_model = (trainer.model.a, trainer.model.b) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(learning_rate=0.1, seed=314, output_dir=tmp_dir) + trainer.train() + self.alternate_trained_model = (trainer.model.a, trainer.model.b) + + def check_trained_model(self, model, alternate_seed=False, **kwargs): + # Checks a training seeded with learning_rate = 0.1 + (a, b) = self.alternate_trained_model if alternate_seed else self.default_trained_model + torch.testing.assert_close(model.a, a, **kwargs) + torch.testing.assert_close(model.b, b, **kwargs) + + def test_reproducible_training(self): + # Checks that training worked, model trained and seed made a reproducible training. + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(learning_rate=0.1, output_dir=tmp_dir) + trainer.train() + self.check_trained_model(trainer.model) + + # Checks that a different seed gets different (reproducible) results. + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(learning_rate=0.1, seed=314, output_dir=tmp_dir) + trainer.train() + self.check_trained_model(trainer.model, alternate_seed=True) + + def test_trainer_with_datasets(self): + np.random.seed(42) + x = np.random.normal(size=(64,)).astype(np.float32) + y = 2.0 * x + 3.0 + np.random.normal(scale=0.1, size=(64,)).astype(np.float32) + train_dataset = datasets.Dataset.from_dict({"input_x": x, "label": y}) + + # Base training. Should have the same results as test_reproducible_training + model = RegressionModel() + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(tmp_dir, learning_rate=0.1, report_to="none") + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.train() + self.check_trained_model(trainer.model) + + # Can return tensors. + train_dataset.set_format(type="torch", dtype=torch.float32) + model = RegressionModel() + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.train() + self.check_trained_model(trainer.model) + + # Adding one column not used by the model should have no impact + z = np.random.normal(size=(64,)).astype(np.float32) + train_dataset = datasets.Dataset.from_dict({"input_x": x, "label": y, "extra": z}) + model = RegressionModel() + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.train() + self.check_trained_model(trainer.model) + + def test_model_init(self): + train_dataset = RegressionDataset() + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(tmp_dir, learning_rate=0.1, report_to="none") + trainer = Trainer(args=args, train_dataset=train_dataset, model_init=lambda: RegressionModel()) + trainer.train() + self.check_trained_model(trainer.model) + + # Re-training should restart from scratch, thus lead the same results. + trainer.train() + self.check_trained_model(trainer.model) + + # Re-training should restart from scratch, thus lead the same results and new seed should be used. + trainer.args.seed = 314 + trainer.train() + self.check_trained_model(trainer.model, alternate_seed=True) + + @slow + def test_gradient_accumulation_loss_alignment_with_model_loss(self): + set_seed(42) + + model_name = "nickypro/tinyllama-15M" + dataset_name = "wikitext" + dataset_config = "wikitext-2-raw-v1" + dataset = datasets.load_dataset(dataset_name, dataset_config, split="train[:40]") + tokenizer = AutoTokenizer.from_pretrained(model_name) + + tokenizer.pad_token = tokenizer.eos_token + + def tokenize_function(examples): + return tokenizer(examples["text"], max_length=16, padding="max_length", truncation=True) + + tokenized_dataset = dataset.map(tokenize_function, batched=True, remove_columns=dataset.column_names) + + data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) + + args_kwargs = { + "report_to": "none", + "logging_steps": 1, + "max_steps": 5, + "learning_rate": 3e-4, + "disable_tqdm": True, + } + + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + tmp_dir, + **args_kwargs, + ) + # train with base loss + set_seed(42) + model = AutoModelForCausalLM.from_pretrained(model_name) + base_loss_callback = StoreLossCallback() + trainer = Trainer( + model, + args, + train_dataset=tokenized_dataset, + callbacks=[base_loss_callback], + data_collator=data_collator, + ) + assert trainer.model_accepts_loss_kwargs + trainer.train() + + args = TrainingArguments( + tmp_dir, + **args_kwargs, + gradient_accumulation_steps=2, + per_device_train_batch_size=4, + ) + + # train with gradient accumulation + set_seed(42) + model = AutoModelForCausalLM.from_pretrained(model_name) + grad_accum_loss_callback = StoreLossCallback() + trainer = Trainer( + model, + args, + train_dataset=tokenized_dataset, + callbacks=[grad_accum_loss_callback], + data_collator=data_collator, + ) + assert trainer.model_accepts_loss_kwargs + trainer.train() + + # train with broken loss + set_seed(42) + model = AutoModelForCausalLM.from_pretrained(model_name) + broken_loss_callback = StoreLossCallback() + trainer = Trainer( + model, + args, + train_dataset=tokenized_dataset, + callbacks=[broken_loss_callback], + data_collator=data_collator, + ) + # disable model_accepts_loss_kwargs so that "num_items_in_batch" is not passed to the model + trainer.model_accepts_loss_kwargs = False + trainer.train() + + # Calculate the difference between the base loss and the grad_accum loss + diff_truth = [ + abs(base - grad) for base, grad in zip(base_loss_callback.losses, grad_accum_loss_callback.losses) + ] + diff_broken = [abs(base - grad) for base, grad in zip(base_loss_callback.losses, broken_loss_callback.losses)] + + # all diff truth should be quite close + self.assertLess(max(diff_truth), 0.01, f"Difference {max(diff_truth)} is not within 0.01") + # max diff broken should be very off ("very off" is arbitrary, but as long as it's bigger than 0.1, it's fine) + self.assertGreater(max(diff_broken), 0.7, f"Difference {max(diff_broken)} is not greater than 0.7") + + loss_base = sum(base_loss_callback.losses) + loss_broken = sum(broken_loss_callback.losses) + + # mean/sum loss should not vary too much. + relative_diff = abs(loss_base - loss_broken) / max(loss_base, loss_broken) + self.assertLess(relative_diff, 0.2, f"Relative difference {relative_diff} is not within 0.2") + + def test_gradient_accumulation_loss_alignment_with_loss_func(self): + set_seed(42) + + model_name = "roneneldan/TinyStories-33M" + dataset_name = "wikitext" + dataset_config = "wikitext-2-raw-v1" + dataset = datasets.load_dataset(dataset_name, dataset_config, split="train[:40]") + tokenizer = AutoTokenizer.from_pretrained(model_name) + + tokenizer.pad_token = tokenizer.eos_token + + def tokenize_function(examples): + return tokenizer(examples["text"], max_length=16, padding="max_length", truncation=True) + + tokenized_dataset = dataset.map(tokenize_function, batched=True) + + tokenizer.pad_token = tokenizer.eos_token + data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) + + model = AutoModelForCausalLM.from_pretrained(model_name) + + def compute_loss(logits, labels, vocab_size, num_items_in_batch, disable_num_items_in_batch=False): + return ForCausalLMLoss( + logits["logits"], labels, vocab_size, num_items_in_batch, disable_num_items_in_batch + ) + + loss_fn = partial(compute_loss, vocab_size=model.config.vocab_size, disable_num_items_in_batch=False) + + base_loss_callback = StoreLossCallback() + + args_kwargs = { + "report_to": "none", + "logging_steps": 1, + "max_steps": 5, + "learning_rate": 3e-4, + "disable_tqdm": True, + } + + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + tmp_dir, + **args_kwargs, + ) + trainer = Trainer( + model, + args, + train_dataset=tokenized_dataset, + callbacks=[base_loss_callback], + compute_loss_func=loss_fn, + data_collator=data_collator, + ) + trainer.train() + + grad_accum_loss_callback = StoreLossCallback() + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + tmp_dir, + **args_kwargs, + gradient_accumulation_steps=2, + per_device_train_batch_size=4, + ) + set_seed(42) + model = AutoModelForCausalLM.from_pretrained(model_name) + trainer = Trainer( + model, + args, + train_dataset=tokenized_dataset, + callbacks=[grad_accum_loss_callback], + compute_loss_func=loss_fn, + data_collator=data_collator, + ) + trainer.train() + + set_seed(42) + model = AutoModelForCausalLM.from_pretrained(model_name) + broken_loss_callback = StoreLossCallback() + loss_fn = partial(compute_loss, vocab_size=model.config.vocab_size, disable_num_items_in_batch=True) + trainer = Trainer( + model, + args, + train_dataset=tokenized_dataset, + callbacks=[broken_loss_callback], + compute_loss_func=loss_fn, + data_collator=data_collator, + ) + trainer.train() + + # Calculate the difference between the base loss and the grad_accum loss + diff_truth = [ + abs(base - grad) for base, grad in zip(base_loss_callback.losses, grad_accum_loss_callback.losses) + ] + diff_broken = [ + abs(base - grad) for base, grad in zip(base_loss_callback.losses, broken_loss_callback.losses) + ] + + # all diff truth should be quite close + self.assertLess(max(diff_truth), 0.01, f"Difference {max(diff_truth)} is not within 0.01") + + # max diff broken should be very off + self.assertGreater(max(diff_broken), 3, f"Difference {max(diff_broken)} is not greater than 3") + + def test_gradient_accumulation(self): + # Training with half the batch size but accumulation steps as 2 should give the same training losses. + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + gradient_accumulation_steps=2, per_device_train_batch_size=4, learning_rate=0.1, output_dir=tmp_dir + ) + trainer.train() + self.check_trained_model(trainer.model) + + def test_gradient_checkpointing(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + per_device_train_batch_size=1, + learning_rate=0.1, + gradient_checkpointing=True, + gradient_checkpointing_kwargs={"use_reentrant": False}, + output_dir=tmp_dir, + ) + previous_params = {k: v.detach().clone() for k, v in trainer.model.named_parameters()} + + trainer.train() + + # Check if model weights have been updated + for k, v in trainer.model.named_parameters(): + self.assertFalse( + torch.allclose(previous_params[k], v, rtol=1e-4, atol=1e-4), + f"Model weights for {k} have not been updated", + ) + + def test_training_loss(self): + n_gpus = max(1, backend_device_count(torch_device)) + + # With even logs + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(logging_steps=64 / (8 * n_gpus), output_dir=tmp_dir) + trainer.train() + log_history = trainer.state.log_history + + losses = [log["loss"] for log in log_history if "loss" in log] + train_loss = log_history[-1]["train_loss"] + self.assertAlmostEqual(sum(losses) / len(losses), train_loss, places=4) + + # With uneven logs + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(logging_steps=5, output_dir=tmp_dir) + trainer.train() + log_history = trainer.state.log_history + + # Training loss should be the same as before + new_train_loss = log_history[-1]["train_loss"] + self.assertAlmostEqual(train_loss, new_train_loss, places=4) + + def test_custom_optimizer(self): + train_dataset = RegressionDataset() + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(tmp_dir, report_to="none") + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=1.0) + lr_scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda x: 1.0) + trainer = Trainer(model, args, train_dataset=train_dataset, optimizers=(optimizer, lr_scheduler)) + trainer.train() + + (a, b) = self.default_trained_model + self.assertFalse(torch.allclose(trainer.model.a, a)) + self.assertFalse(torch.allclose(trainer.model.b, b)) + self.assertEqual(trainer.optimizer.state_dict()["param_groups"][0]["lr"], 1.0) + + def test_lr_scheduler_kwargs(self): + # test scheduler kwargs passed via TrainingArguments + train_dataset = RegressionDataset() + model = RegressionModel() + num_steps, num_warmup_steps = 10, 2 + extra_kwargs = {"power": 5.0, "lr_end": 1e-5} # Non-default arguments + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + tmp_dir, + lr_scheduler_type="polynomial", + lr_scheduler_kwargs=extra_kwargs, + learning_rate=0.2, + warmup_steps=num_warmup_steps, + report_to="none", + ) + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.create_optimizer_and_scheduler(num_training_steps=num_steps) + + # Checking that the scheduler was created + self.assertIsNotNone(trainer.lr_scheduler) + + # Checking that the correct args were passed + sched1 = trainer.lr_scheduler + sched2 = get_polynomial_decay_schedule_with_warmup( + trainer.optimizer, num_warmup_steps=num_warmup_steps, num_training_steps=num_steps, **extra_kwargs + ) + self.assertEqual(sched1.lr_lambdas[0].args, sched2.lr_lambdas[0].args) + self.assertEqual(sched1.lr_lambdas[0].keywords, sched2.lr_lambdas[0].keywords) + + def test_cosine_with_min_lr_scheduler(self): + train_dataset = RegressionDataset() + model = RegressionModel() + num_steps, num_warmup_steps = 10, 2 + extra_kwargs = {"min_lr": 1e-5} # Non-default arguments + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + tmp_dir, + lr_scheduler_type="cosine_with_min_lr", + lr_scheduler_kwargs=extra_kwargs, + learning_rate=0.2, + warmup_steps=num_warmup_steps, + report_to="none", + ) + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.create_optimizer_and_scheduler(num_training_steps=num_steps) + + # Checking that the scheduler was created + self.assertIsNotNone(trainer.lr_scheduler) + + # Check the last learning rate + for _ in range(num_steps): + trainer.lr_scheduler.step() + self.assertEqual(trainer.lr_scheduler.get_last_lr()[0], 1e-5) + + def test_cosine_with_min_lr_schedule_with_warmup_lr_rate(self): + train_dataset = RegressionDataset() + model = RegressionModel() + num_steps, num_warmup_steps = 10, 2 + extra_kwargs = {"min_lr": 1e-5} # Non-default arguments + args = TrainingArguments( + "./regression", + lr_scheduler_type="cosine_warmup_with_min_lr", + lr_scheduler_kwargs=extra_kwargs, + learning_rate=0.2, + warmup_steps=num_warmup_steps, + report_to="none", + ) + trainer = Trainer(model, args, train_dataset=train_dataset) + trainer.create_optimizer_and_scheduler(num_training_steps=num_steps) + + # Checking that the scheduler was created + self.assertIsNotNone(trainer.lr_scheduler) + + # Check the last learning rate + step_lrs = [] + for _ in range(num_steps): + step_lrs.append(trainer.optimizer.param_groups[0]["lr"]) + trainer.lr_scheduler.step() + self.assertEqual(step_lrs[0], 0.1) + self.assertEqual(step_lrs[1], 0.2) + self.assertEqual(step_lrs[-1], 1e-05) + + def test_reduce_lr_on_plateau_args(self): + # test passed arguments for a custom ReduceLROnPlateau scheduler + train_dataset = RegressionDataset(length=64) + eval_dataset = RegressionDataset(length=64) + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + tmp_dir, + eval_strategy="epoch", + metric_for_best_model="eval_loss", + report_to="none", + ) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=1.0) + lr_scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, factor=0.2, patience=5, cooldown=2) + trainer = Trainer( + model, + args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + optimizers=(optimizer, lr_scheduler), + ) + trainer.train() + + self.assertIsInstance(trainer.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau) + self.assertEqual(trainer.lr_scheduler.factor, 0.2) + self.assertEqual(trainer.lr_scheduler.patience, 5) + self.assertEqual(trainer.lr_scheduler.cooldown, 2) + + def test_reduce_lr_on_plateau(self): + # test the ReduceLROnPlateau scheduler + + class TrainerWithLRLogs(Trainer): + def log(self, logs): + # the LR is computed after metrics and does not exist for the first epoch + if hasattr(self.lr_scheduler, "_last_lr"): + logs["learning_rate"] = self.lr_scheduler._last_lr[0] + super().log(logs) + + train_dataset = RegressionDataset(length=64) + eval_dataset = RegressionDataset(length=64) + + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + tmp_dir, + lr_scheduler_type="reduce_lr_on_plateau", + eval_strategy="epoch", + metric_for_best_model="eval_loss", + num_train_epochs=10, + learning_rate=0.2, + report_to="none", + ) + model = RegressionModel() + trainer = TrainerWithLRLogs(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + trainer.train() + + self.assertIsInstance(trainer.lr_scheduler, torch.optim.lr_scheduler.ReduceLROnPlateau) + patience = trainer.lr_scheduler.patience + + logs = trainer.state.log_history[1:] + best_loss = logs[0]["eval_loss"] + bad_epochs = 0 + for i, log in enumerate(logs[:-1]): # Compare learning rate to next epoch's + loss = log["eval_loss"] + just_decreased = False + if loss > best_loss: + bad_epochs += 1 + if bad_epochs > patience: + self.assertLess(logs[i + 1]["learning_rate"], log["learning_rate"]) + just_decreased = True + bad_epochs = 0 + else: + best_loss = loss + bad_epochs = 0 + if not just_decreased: + self.assertEqual(logs[i + 1]["learning_rate"], log["learning_rate"]) + + def test_adafactor_lr_none(self): + # test the special case where lr=None, since Trainer can't not have lr_scheduler + + from transformers.optimization import Adafactor, AdafactorSchedule + + train_dataset = RegressionDataset() + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(tmp_dir, report_to="none") + model = RegressionModel() + optimizer = Adafactor( + model.parameters(), scale_parameter=True, relative_step=True, warmup_init=True, lr=None + ) + lr_scheduler = AdafactorSchedule(optimizer) + trainer = Trainer(model, args, train_dataset=train_dataset, optimizers=(optimizer, lr_scheduler)) + trainer.train() + + (a, b) = self.default_trained_model + self.assertFalse(torch.allclose(trainer.model.a, a)) + self.assertFalse(torch.allclose(trainer.model.b, b)) + self.assertGreater(trainer.optimizer.state_dict()["param_groups"][0]["lr"], 0) + + @require_torch_bf16 + @require_torch_accelerator + def test_mixed_bf16(self): + # very basic test + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(learning_rate=0.1, bf16=True, output_dir=tmp_dir) + trainer.train() + self.check_trained_model(trainer.model, atol=ATOL, rtol=RTOL) + + # --bf16 --half_precision_backend apex can't be used together + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(ValueError): + trainer = get_regression_trainer( + learning_rate=0.1, bf16=True, half_precision_backend="apex", output_dir=tmp_dir + ) + + # will add more specific tests once there are some bugs to fix + + @require_torch_gpu + @require_torch_tf32 + def test_tf32(self): + # very basic test + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(learning_rate=0.1, tf32=True, output_dir=tmp_dir) + trainer.train() + self.check_trained_model(trainer.model) + + +@require_torch +@require_sentencepiece +@require_tokenizers +class TrainerIntegrationTest(TestCasePlus, TrainerIntegrationCommon): + def setUp(self): + super().setUp() + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_trainer_works_with_dict(self): + # Edge case because Apex with mode O2 will change our models to return dicts. This test checks it doesn't break + # anything. + train_dataset = RegressionDataset() + eval_dataset = RegressionDataset() + model = RegressionDictModel() + args = TrainingArguments(self.get_auto_remove_tmp_dir(), report_to="none") + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + trainer.train() + _ = trainer.evaluate() + _ = trainer.predict(eval_dataset) + + def test_training_arguments_are_left_untouched(self): + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(output_dir=tmp_dir) + trainer.train() + args = TrainingArguments(tmp_dir, report_to=[]) + dict1, dict2 = args.to_dict(), trainer.args.to_dict() + for key in dict1: + # Logging dir can be slightly different as they default to something with the time. + if key != "logging_dir": + self.assertEqual(dict1[key], dict2[key]) + + def test_number_of_steps_in_training(self): + # Regular training has n_epochs * len(train_dl) steps + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(learning_rate=0.1, output_dir=tmp_dir) + train_output = trainer.train() + self.assertEqual(train_output.global_step, self.n_epochs * 64 / self.batch_size) + + # Check passing num_train_epochs works (and a float version too): + trainer = get_regression_trainer(learning_rate=0.1, num_train_epochs=1.5, output_dir=tmp_dir) + train_output = trainer.train() + self.assertEqual(train_output.global_step, int(1.5 * 64 / self.batch_size)) + + # If we pass a max_steps, num_train_epochs is ignored + trainer = get_regression_trainer(learning_rate=0.1, max_steps=10, output_dir=tmp_dir) + train_output = trainer.train() + self.assertEqual(train_output.global_step, 10) + + @pytest.mark.torch_compile_test + def test_torch_compile_loss_func_compatibility(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + per_device_train_batch_size=2, + torch_compile=True, + max_steps=1, # compile happens on the first step + report_to="none", + ) + trainer = Trainer(model=tiny_llama, args=args, train_dataset=train_dataset) # noqa + trainer.train() + + @require_peft + @require_bitsandbytes + @pytest.mark.torch_compile_test + def test_bnb_compile(self): + from peft import LoraConfig, get_peft_model + + # Simply tests if initializing a Trainer with a PEFT + compiled model works out of the box + # QLoRA + torch compile is not really supported yet, but we should at least support the model + # loading and let torch throw the + tiny_model = AutoModelForCausalLM.from_pretrained( + "hf-internal-testing/tiny-random-LlamaForCausalLM", load_in_4bit=True + ) + + peft_config = LoraConfig( + r=8, + lora_alpha=32, + target_modules=["q_proj", "k_proj", "v_proj"], + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", + ) + tiny_model = get_peft_model(tiny_model, peft_config) + + tiny_model = torch.compile(tiny_model) + + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + ) + with self.assertRaises(ValueError): + _ = Trainer(tiny_model, args, train_dataset=train_dataset) # noqa + + @require_peft + def test_multiple_peft_adapters(self): + from peft import LoraConfig, get_peft_model + + # Tests if resuming from checkpoint works if the model has multiple adapters + + MODEL_ID = "hf-internal-testing/tiny-random-LlamaForCausalLM" + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) + tiny_model = AutoModelForCausalLM.from_pretrained(MODEL_ID) + + peft_config = LoraConfig( + r=4, + lora_alpha=16, + lora_dropout=0.05, + bias="none", + task_type="CAUSAL_LM", + ) + tiny_model = get_peft_model(tiny_model, peft_config, "adapter1") + tiny_model.add_adapter("adapter2", peft_config) + + train_dataset = LineByLineTextDataset( + tokenizer=tokenizer, + file_path=PATH_SAMPLE_TEXT, + block_size=tokenizer.max_len_single_sentence, + ) + for example in train_dataset.examples: + example["labels"] = example["input_ids"] + + tokenizer.pad_token = tokenizer.eos_token + + tmp_dir = self.get_auto_remove_tmp_dir() + args = TrainingArguments( + tmp_dir, + per_device_train_batch_size=1, + learning_rate=1e-9, + save_steps=5, + logging_steps=5, + max_steps=10, + use_cpu=True, + ) + trainer = Trainer(tiny_model, args, processing_class=tokenizer, train_dataset=train_dataset) + + trainer.train() + parameters = dict(tiny_model.named_parameters()) + state = dataclasses.asdict(trainer.state) + + # Reinitialize trainer + trainer = Trainer(tiny_model, args, processing_class=tokenizer, train_dataset=train_dataset) + + checkpoint = os.path.join(tmp_dir, "checkpoint-5") + + trainer.train(resume_from_checkpoint=checkpoint) + parameters1 = dict(tiny_model.named_parameters()) + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(parameters, parameters1) + self.check_trainer_state_are_the_same(state, state1) + + @require_bitsandbytes + def test_rmsprop_bnb(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + logging_nan_inf_filter=False, + optim="rmsprop_bnb", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + # Check that it trains without errors + trainer.train() + + @require_bitsandbytes + def test_ademamix_bnb(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + logging_nan_inf_filter=False, + optim="ademamix", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + # Check that it trains without errors + trainer.train() + + @require_bitsandbytes + def test_ademamix_bnb_8bit(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + logging_nan_inf_filter=False, + optim="ademamix_8bit", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + # Check that it trains without errors + trainer.train() + + @require_bitsandbytes + def test_rmsprop_bnb_8bit(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + logging_nan_inf_filter=False, + optim="rmsprop_bnb_8bit", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + # Check that it trains without errors + trainer.train() + + @require_bitsandbytes + def test_rmsprop_bnb_32bit(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + logging_nan_inf_filter=False, + optim="rmsprop_bnb_32bit", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + # Check that it trains without errors + trainer.train() + + def test_neftune(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + logging_nan_inf_filter=False, + neftune_noise_alpha=0.4, + report_to="none", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + trainer.model = trainer._activate_neftune(trainer.model) + + dummy_input = torch.LongTensor([[1, 0, 1]]).to(torch_device) + + emb1 = trainer.model.get_input_embeddings()(dummy_input) + emb2 = trainer.model.get_input_embeddings()(dummy_input) + + self.assertFalse(torch.allclose(emb1, emb2), "Neftune noise is not applied!") + + # redefine the model + tiny_gpt2 = GPT2LMHeadModel(config) + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + logging_nan_inf_filter=False, + neftune_noise_alpha=0.4, + report_to="none", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + + # Check that it trains without errors + trainer.train() + + # Make sure forward pass works fine + _ = trainer.model(dummy_input) + self.assertTrue(len(trainer.model.get_input_embeddings()._forward_hooks) == 0) + + trainer.model.eval() + + # Check that we get identical embeddings just in case + emb1 = trainer.model.get_input_embeddings()(dummy_input) + emb2 = trainer.model.get_input_embeddings()(dummy_input) + torch.testing.assert_close(emb1, emb2) + + def test_logging_inf_nan_filter(self): + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e9, + logging_steps=5, + logging_nan_inf_filter=False, + report_to="none", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + trainer.train() + log_history_no_filter = trainer.state.log_history + + # Trainer with inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e9, + logging_steps=5, + logging_nan_inf_filter=True, + report_to="none", + ) + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset) + trainer.train() + log_history_filter = trainer.state.log_history + + def is_any_loss_nan_or_inf(log_history): + losses = [l["loss"] for l in log_history[:-1]] + return any(math.isnan(x) for x in losses) or any(math.isinf(x) for x in losses) + + self.assertTrue(is_any_loss_nan_or_inf(log_history_no_filter)) + self.assertFalse(is_any_loss_nan_or_inf(log_history_filter)) + + def test_train_and_eval_dataloaders(self): + if torch_device in ["cuda"]: + n_gpu = max(1, backend_device_count(torch_device)) + else: + # DP is decprecated by PyTorch, accelerators like XPU doesn't support DP + n_gpu = 1 + + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(learning_rate=0.1, per_device_train_batch_size=16, output_dir=tmp_dir) + self.assertEqual(trainer.get_train_dataloader().total_batch_size, 16 * n_gpu) + trainer = get_regression_trainer(learning_rate=0.1, per_device_eval_batch_size=16, output_dir=tmp_dir) + self.assertEqual(trainer.get_eval_dataloader().total_batch_size, 16 * n_gpu) + + # Check drop_last works + trainer = get_regression_trainer( + train_len=66, + eval_len=74, + learning_rate=0.1, + per_device_train_batch_size=16, + per_device_eval_batch_size=32, + output_dir=tmp_dir, + ) + self.assertEqual(len(trainer.get_train_dataloader()), 66 // (16 * n_gpu) + 1) + self.assertEqual(len(trainer.get_eval_dataloader()), 74 // (32 * n_gpu) + 1) + + trainer = get_regression_trainer( + train_len=66, + eval_len=74, + learning_rate=0.1, + per_device_train_batch_size=16, + per_device_eval_batch_size=32, + dataloader_drop_last=True, + output_dir=tmp_dir, + ) + self.assertEqual(len(trainer.get_train_dataloader()), 66 // (16 * n_gpu)) + self.assertEqual(len(trainer.get_eval_dataloader()), 74 // (32 * n_gpu)) + + # Check passing a new dataset for evaluation works + new_eval_dataset = RegressionDataset(length=128) + self.assertEqual(len(trainer.get_eval_dataloader(new_eval_dataset)), 128 // (32 * n_gpu)) + + # tests that we do not require dataloader to have a .dataset attribute + def test_dataloader_without_dataset(self): + train_dataset = RegressionDataset(length=128) + trainer = CustomDataloaderTrainer( + model=RegressionModel(), + train_dataset=train_dataset, + eval_dataset=train_dataset, + args=TrainingArguments(output_dir=self.get_auto_remove_tmp_dir(), report_to="none"), + ) + + trainer.train() + trainer.evaluate() + + def test_get_eval_dataloader_without_persistent_workers(self): + train_dataset = RegressionDataset() + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + args = TrainingArguments(self.get_auto_remove_tmp_dir(), report_to="none", dataloader_persistent_workers=False) + + # Single evaluation dataset + eval_dataset = RegressionDataset() + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + # Mocking the prepare method to avoid the dataloader changing with each call to get_eval_dataloader + trainer.accelerator.prepare = lambda x: x + + default_dataloader = trainer.get_eval_dataloader() + dataloader_with_dataset = trainer.get_eval_dataloader(eval_dataset) + + self.assertEqual(default_dataloader.dataset, eval_dataset) + self.assertEqual(dataloader_with_dataset.dataset, eval_dataset) + self.assertNotEqual(default_dataloader, dataloader_with_dataset) + + # Multiple evaluation datasets + first_dataset = RegressionDataset() + second_dataset = RegressionDataset() + trainer = Trainer( + tiny_gpt2, + args, + train_dataset=train_dataset, + eval_dataset={"first": first_dataset, "second": second_dataset}, + ) + # Mocking the prepare method to avoid the dataloader changing with each call to get_eval_dataloader + trainer.accelerator.prepare = lambda x: x + + first_dataloader = trainer.get_eval_dataloader("first") + first_dataloader_repeated = trainer.get_eval_dataloader("first") + second_dataloader = trainer.get_eval_dataloader("second") + second_dataloader_repeated = trainer.get_eval_dataloader("second") + + self.assertEqual(first_dataset, first_dataloader.dataset) + self.assertEqual(first_dataloader.dataset, first_dataloader_repeated.dataset) + self.assertEqual(second_dataset, second_dataloader.dataset) + self.assertEqual(second_dataloader.dataset, second_dataloader_repeated.dataset) + self.assertNotEqual(first_dataloader, first_dataloader_repeated) + self.assertNotEqual(second_dataloader, second_dataloader_repeated) + + def test_get_eval_dataloader_with_persistent_workers(self): + train_dataset = RegressionDataset() + config = GPT2Config(vocab_size=100, n_positions=128, n_embd=32, n_layer=3, n_head=4) + tiny_gpt2 = GPT2LMHeadModel(config) + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + report_to="none", + dataloader_persistent_workers=True, + dataloader_num_workers=2, + ) + + # Single evaluation dataset + eval_dataset = RegressionDataset() + trainer = Trainer(tiny_gpt2, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + # Mocking the prepare method to avoid the dataloader changing with each call to get_eval_dataloader + trainer.accelerator.prepare = lambda x: x + + default_dataloader = trainer.get_eval_dataloader() + dataloader_with_dataset = trainer.get_eval_dataloader(eval_dataset) + + self.assertEqual(default_dataloader.dataset, eval_dataset) + self.assertEqual(dataloader_with_dataset.dataset, eval_dataset) + self.assertEqual(default_dataloader, dataloader_with_dataset) + + # Multiple evaluation datasets + first_dataset = RegressionDataset() + second_dataset = RegressionDataset() + trainer = Trainer( + tiny_gpt2, + args, + train_dataset=train_dataset, + eval_dataset={"first": first_dataset, "second": second_dataset}, + ) + # Mocking the prepare method to avoid the dataloader changing with each call to get_eval_dataloader + trainer.accelerator.prepare = lambda x: x + + first_dataloader = trainer.get_eval_dataloader("first") + first_dataloader_repeated = trainer.get_eval_dataloader("first") + second_dataloader = trainer.get_eval_dataloader("second") + second_dataloader_repeated = trainer.get_eval_dataloader("second") + + self.assertEqual(first_dataset, first_dataloader.dataset) + self.assertEqual(first_dataloader.dataset, first_dataloader_repeated.dataset) + self.assertEqual(second_dataset, second_dataloader.dataset) + self.assertEqual(second_dataloader.dataset, second_dataloader_repeated.dataset) + self.assertEqual(first_dataloader, first_dataloader_repeated) + self.assertEqual(second_dataloader, second_dataloader_repeated) + + @require_liger_kernel + def test_use_liger_kernel_patching(self): + # Ensure any monkey patching is cleaned up for subsequent tests + with patch("transformers.models.llama.modeling_llama"): + from liger_kernel.transformers import LigerRMSNorm, liger_rotary_pos_emb + + from transformers.models.llama import modeling_llama + + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + + # Spot check that modeling code and model instance variables are not yet patched + self.assertNotEqual(modeling_llama.apply_rotary_pos_emb, liger_rotary_pos_emb) + self.assertFalse(isinstance(tiny_llama.model.norm, LigerRMSNorm)) + + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + use_liger_kernel=True, + ) + Trainer(tiny_llama, args) + + # Spot check that modeling code and model instance variables are patched + self.assertEqual(modeling_llama.apply_rotary_pos_emb, liger_rotary_pos_emb) + self.assertTrue(isinstance(tiny_llama.model.norm, LigerRMSNorm)) + + @require_liger_kernel + def test_use_liger_kernel_custom_config_patching(self): + # Ensure any monkey patching is cleaned up for subsequent tests + with patch("transformers.models.llama.modeling_llama"): + from liger_kernel.transformers import LigerRMSNorm + + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + use_liger_kernel=True, + liger_kernel_config={"rms_norm": False}, # Don't apply Liger's RMSNorm + ) + Trainer(tiny_llama, args) + + # Check that the RMSNorm kernel is not applied as specified in the config + self.assertFalse(isinstance(tiny_llama.model.norm, LigerRMSNorm)) + + @require_liger_kernel + @require_torch_accelerator + def test_use_liger_kernel_trainer(self): + # Check that trainer still works with liger kernel applied + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), learning_rate=1e-2, logging_steps=5, max_steps=20, use_liger_kernel=True + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_liger_kernel + @require_torch_accelerator + def test_use_liger_kernel_custom_config_trainer(self): + # Check that trainer still works with liger kernel applied when using a custom config + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-2, + logging_steps=5, + max_steps=20, + use_liger_kernel=True, + liger_kernel_config={"rms_norm": False, "cross_entropy": True, "fused_linear_cross_entropy": False}, + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_lomo + @require_torch_accelerator + def test_lomo(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + + previous_params = {n: p.clone() for n, p in tiny_llama.named_parameters()} + + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), learning_rate=1e-2, logging_steps=5, optim="lomo", max_steps=20 + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + for name, param in tiny_llama.named_parameters(): + self.assertFalse(torch.allclose(param, previous_params[name].to(param.device), rtol=1e-12, atol=1e-12)) + + @require_lomo + @require_torch_accelerator + def test_adalomo(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="adalomo", + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_grokadamw + @require_torch_accelerator + def test_grokadamw(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=2e-5, + logging_steps=5, + optim="grokadamw", + max_steps=20, + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_schedulefree + @require_torch_accelerator + def test_schedulefree_adam(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + with tempfile.TemporaryDirectory() as tmpdir: + # Trainer without inf/nan filter + args = TrainingArguments( + tmpdir, + learning_rate=1e-9, + logging_steps=5, + optim="schedule_free_adamw", + lr_scheduler_type="constant", + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_schedulefree + @require_torch_accelerator + def test_schedulefree_radam(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + with tempfile.TemporaryDirectory() as tmpdir: + # Trainer without inf/nan filter + args = TrainingArguments( + tmpdir, + learning_rate=1e-9, + logging_steps=5, + lr_scheduler_type="constant", + optim="schedule_free_radam", + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + def test_galore_matched_modules(self): + regex_patterns = [r".*.attn.*", r".*.mlp.*"] + + module_names = [ + "model.transformer.h.0.ln_1", + "model.transformer.h.0.attn.q_proj", + "model.lm_head", + "model.transformer.h.0.mlp.up_proj", + ] + expected_values = [False, True, False, True] + + for expected_value, module_name in zip(expected_values, module_names): + is_module_matched, is_regex = check_target_module_exists(regex_patterns, module_name, return_is_regex=True) + self.assertTrue(is_module_matched == expected_value) + if is_module_matched: + self.assertTrue(is_regex) + + exact_patterns = ["q_proj", "up_proj"] + + module_names = [ + "model.transformer.h.0.ln_1", + "model.transformer.h.0.attn.q_proj", + "model.lm_head", + "model.transformer.h.0.mlp.up_proj", + ] + expected_values = [False, True, False, True] + + for expected_value, module_name in zip(expected_values, module_names): + is_module_matched, is_regex = check_target_module_exists(exact_patterns, module_name, return_is_regex=True) + self.assertTrue(is_module_matched == expected_value) + if is_module_matched: + self.assertFalse(is_regex) + + simple_regex = r".*.attn.*" + + module_names = [ + "model.transformer.h.0.ln_1", + "model.transformer.h.0.attn.q_proj", + "model.lm_head", + "model.transformer.h.0.mlp.up_proj", + ] + expected_values = [False, True, False, False] + + for expected_value, module_name in zip(expected_values, module_names): + is_module_matched, is_regex = check_target_module_exists(simple_regex, module_name, return_is_regex=True) + self.assertTrue(is_module_matched == expected_value) + if is_module_matched: + self.assertTrue(is_regex) + + simple_regex = "model.transformer.h.0.attn.q_proj" + + module_names = [ + "model.transformer.h.0.ln_1", + "model.transformer.h.0.attn.q_proj", + "model.lm_head", + "model.transformer.h.0.mlp.up_proj", + ] + expected_values = [False, True, False, False] + + for expected_value, module_name in zip(expected_values, module_names): + is_module_matched, is_regex = check_target_module_exists(simple_regex, module_name, return_is_regex=True) + self.assertTrue(is_module_matched == expected_value) + if is_module_matched: + self.assertFalse(is_regex) + + target_modules = ["attn", "mlp"] + + module_names = [ + "model.transformer.h.0.ln_1", + "model.transformer.h.0.attn.q_proj", + "model.lm_head", + "model.transformer.h.0.mlp.up_proj", + ] + expected_values = [False, True, False, True] + + for expected_value, module_name in zip(expected_values, module_names): + is_module_matched, is_regex = check_target_module_exists(target_modules, module_name, return_is_regex=True) + self.assertTrue(is_module_matched == expected_value) + if is_module_matched: + self.assertFalse(is_regex) + + @require_galore_torch + @require_torch_accelerator + def test_galore(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="galore_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_galore_torch + @require_torch_accelerator + def test_galore_extra_args(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="galore_adamw", + optim_args="rank=64, update_proj_gap=100, scale=0.10", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_galore_torch + @require_torch_accelerator + def test_galore_layerwise(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="galore_adamw_layerwise", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_galore_torch + @require_torch_accelerator + def test_galore_layerwise_with_scheduler(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="galore_adamw_layerwise", + lr_scheduler_type="cosine", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_galore_torch + @require_torch_accelerator + def test_galore_adamw_8bit(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="galore_adamw_8bit", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_galore_torch + @require_torch_accelerator + def test_galore_adafactor(self): + # These are the intervals of the peak memory usage of training such a tiny model + # if the peak memory goes outside that range, then we know there might be a bug somewhere + upper_bound_pm = 700 + lower_bound_pm = 650 + + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + with tempfile.TemporaryDirectory() as tmpdir, TorchTracemalloc() as tracemalloc: + # Trainer without inf/nan filter + args = TrainingArguments( + tmpdir, + learning_rate=1e-9, + logging_steps=5, + optim="galore_adafactor", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + galore_peak_memory = tracemalloc.peaked + bytes2megabytes(tracemalloc.begin) + + self.assertTrue(galore_peak_memory < upper_bound_pm) + self.assertTrue(lower_bound_pm < galore_peak_memory) + + @require_galore_torch + @require_torch_accelerator + def test_galore_adafactor_attention_only(self): + # These are the intervals of the peak memory usage of training such a tiny model + # if the peak memory goes outside that range, then we know there might be a bug somewhere + upper_bound_pm = 700 + lower_bound_pm = 650 + + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + with tempfile.TemporaryDirectory() as tmpdir, TorchTracemalloc() as tracemalloc: + # Trainer without inf/nan filter + args = TrainingArguments( + tmpdir, + learning_rate=1e-9, + logging_steps=5, + optim="galore_adafactor", + optim_target_modules=["q_proj", "k_proj", "v_proj"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + galore_peak_memory = tracemalloc.peaked + bytes2megabytes(tracemalloc.begin) + self.assertTrue(galore_peak_memory < upper_bound_pm) + self.assertTrue(lower_bound_pm < galore_peak_memory) + + @require_galore_torch + @require_torch_accelerator + def test_galore_adafactor_all_linear(self): + # These are the intervals of the peak memory usage of training such a tiny model + # if the peak memory goes outside that range, then we know there might be a bug somewhere + upper_bound_pm = 700 + lower_bound_pm = 650 + + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + with tempfile.TemporaryDirectory() as tmpdir, TorchTracemalloc() as tracemalloc: + # Trainer without inf/nan filter + args = TrainingArguments( + tmpdir, + learning_rate=1e-9, + logging_steps=5, + optim="galore_adafactor", + optim_target_modules="all-linear", + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + galore_peak_memory = tracemalloc.peaked + bytes2megabytes(tracemalloc.begin) + self.assertTrue(galore_peak_memory < upper_bound_pm) + self.assertTrue(lower_bound_pm < galore_peak_memory) + + @require_galore_torch + @require_torch_accelerator + def test_galore_lr_display_without_scheduler(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + learning_rate = 1e-9 + num_steps = 10 + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=learning_rate, + logging_steps=5, + optim="galore_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + trainer.create_optimizer_and_scheduler(num_training_steps=num_steps) + + # reflects displayed lr in trainer + self.assertEqual(trainer.get_learning_rates(), [learning_rate, learning_rate]) + + @require_galore_torch + @require_torch_accelerator + def test_galore_lr_display_with_scheduler(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + learning_rate = 2e-4 + num_train_epochs = 2 + num_warmup_steps = 5 + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + num_train_epochs=num_train_epochs, + learning_rate=learning_rate, + warmup_steps=num_warmup_steps, + lr_scheduler_type="cosine", + logging_steps=1, + optim="galore_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # creating log history of trainer, results don't matter + trainer.train() + logs = trainer.state.log_history[1:-1] + + # reach given learning rate peak and end with 0 lr + self.assertTrue(logs[num_warmup_steps - 1]["learning_rate"] == learning_rate) + # self.assertTrue(logs[-1]["learning_rate"] == 0) + self.assertTrue(np.allclose(logs[-1]["learning_rate"], 0, atol=5e-6)) + + # increasing and decreasing pattern of lrs + increasing_lrs = [ + logs[i]["learning_rate"] < logs[i + 1]["learning_rate"] + for i in range(len(logs)) + if i < num_warmup_steps - 1 + ] + decreasing_lrs = [ + logs[i]["learning_rate"] > logs[i + 1]["learning_rate"] + for i in range(len(logs) - 1) + if i >= num_warmup_steps - 1 + ] + + self.assertTrue(all(increasing_lrs)) + self.assertTrue(all(decreasing_lrs)) + + # warm up steps << total steps + self.assertTrue(len(decreasing_lrs) > len(increasing_lrs)) + + @require_apollo_torch + @require_torch_accelerator + def test_apollo(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="apollo_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_apollo_torch + @require_torch_accelerator + def test_apollo_extra_args(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="apollo_adamw", + optim_args="proj=random,scale_type=tensor,rank=1,update_proj_gap=100,scale=128.0", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_apollo_torch + @require_torch_accelerator + def test_apollo_layerwise(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="apollo_adamw_layerwise", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_apollo_torch + @require_torch_accelerator + def test_apollo_layerwise_with_scheduler(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="apollo_adamw_layerwise", + lr_scheduler_type="cosine", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_apollo_torch + @require_torch_accelerator + def test_apollo_lr_display_without_scheduler(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + learning_rate = 1e-9 + num_steps = 10 + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=learning_rate, + logging_steps=5, + optim="apollo_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + trainer.create_optimizer_and_scheduler(num_training_steps=num_steps) + + # reflects displayed lr in trainer + self.assertEqual(trainer.get_learning_rates(), [learning_rate, learning_rate]) + + @require_apollo_torch + @require_torch_accelerator + def test_apollo_lr_display_with_scheduler(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + learning_rate = 2e-4 + num_train_epochs = 10 + num_warmup_steps = 5 + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + num_train_epochs=num_train_epochs, + learning_rate=learning_rate, + warmup_steps=num_warmup_steps, + lr_scheduler_type="cosine", + logging_steps=1, + optim="apollo_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # creating log history of trainer, results don't matter + trainer.train() + logs = trainer.state.log_history[1:][:-1] + + # reach given learning rate peak and end with 0 lr + self.assertTrue(logs[num_warmup_steps - 2]["learning_rate"] == learning_rate) + self.assertTrue(logs[-1]["learning_rate"] == 0) + + # increasing and decreasing pattern of lrs + increasing_lrs = [ + logs[i]["learning_rate"] < logs[i + 1]["learning_rate"] + for i in range(len(logs)) + if i < num_warmup_steps - 2 + ] + decreasing_lrs = [ + logs[i]["learning_rate"] > logs[i + 1]["learning_rate"] + for i in range(len(logs) - 1) + if i >= num_warmup_steps - 2 + ] + + self.assertTrue(all(increasing_lrs)) + self.assertTrue(all(decreasing_lrs)) + + # warm up steps << total steps + self.assertTrue(len(decreasing_lrs) > len(increasing_lrs)) + + @require_torch_optimi + @require_torch_accelerator + def test_stable_adamw(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="stable_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + _ = trainer.train() + + @require_torch_optimi + @require_torch_accelerator + def test_stable_adamw_extra_args(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=1e-9, + logging_steps=5, + optim="stable_adamw", + optim_args="decouple_lr=True,max_lr=1e-3,kahan_sum=True", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # Check this works + _ = trainer.train() + + @require_torch_optimi + @require_torch_accelerator + def test_stable_adamw_lr_display_without_scheduler(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + learning_rate = 1e-9 + num_steps = 10 + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + learning_rate=learning_rate, + logging_steps=5, + optim="stable_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + trainer.create_optimizer_and_scheduler(num_training_steps=num_steps) + + # reflects displayed lr in trainer + self.assertEqual(trainer.get_learning_rates(), [learning_rate, learning_rate]) + + @require_torch_optimi + @require_torch_accelerator + def test_stable_adamw_lr_display_with_scheduler(self): + config = LlamaConfig(vocab_size=100, hidden_size=32, num_hidden_layers=3, num_attention_heads=4) + tiny_llama = LlamaForCausalLM(config) + x = torch.randint(0, 100, (128,)) + train_dataset = RepeatDataset(x) + + learning_rate = 2e-4 + num_train_epochs = 10 + num_warmup_steps = 5 + + # Trainer without inf/nan filter + args = TrainingArguments( + self.get_auto_remove_tmp_dir(), + num_train_epochs=num_train_epochs, + learning_rate=learning_rate, + warmup_steps=num_warmup_steps, + lr_scheduler_type="cosine", + logging_steps=1, + optim="stable_adamw", + optim_target_modules=[r".*attn.*", r".*mlp.*"], + ) + trainer = Trainer(tiny_llama, args, train_dataset=train_dataset) + + # creating log history of trainer, results don't matter + trainer.train() + logs = trainer.state.log_history[1:][:-1] + + # reach given learning rate peak and end with 0 lr + self.assertTrue(logs[num_warmup_steps - 1]["learning_rate"] == learning_rate) + self.assertTrue(np.allclose(logs[-1]["learning_rate"], 0, atol=5e-6)) + + # increasing and decreasing pattern of lrs + increasing_lrs = [ + logs[i]["learning_rate"] < logs[i + 1]["learning_rate"] + for i in range(len(logs)) + if i < num_warmup_steps - 1 + ] + decreasing_lrs = [ + logs[i]["learning_rate"] > logs[i + 1]["learning_rate"] + for i in range(len(logs) - 1) + if i >= num_warmup_steps - 1 + ] + + self.assertTrue(all(increasing_lrs)) + self.assertTrue(all(decreasing_lrs)) + + # warm up steps << total steps + self.assertTrue(len(decreasing_lrs) > len(increasing_lrs)) + + @require_torch_multi_accelerator + def test_data_is_not_parallelized_when_model_is_parallel(self): + model = RegressionModel() + # Make the Trainer believe it's a parallelized model + model.is_parallelizable = True + model.model_parallel = True + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + tmp_dir, per_device_train_batch_size=16, per_device_eval_batch_size=16, report_to="none" + ) + trainer = Trainer(model, args, train_dataset=RegressionDataset(), eval_dataset=RegressionDataset()) + # Check the Trainer was fooled + self.assertTrue(trainer.is_model_parallel) + self.assertEqual(trainer.args.n_gpu, 1) + + # The batch size of the training and evaluation dataloaders should be 16, not 16 * n_gpu + self.assertEqual(trainer.get_train_dataloader().total_batch_size, 16) + self.assertEqual(len(trainer.get_train_dataloader()), 64 // 16) + self.assertEqual(trainer.get_eval_dataloader().total_batch_size, 16) + self.assertEqual(len(trainer.get_eval_dataloader()), 64 // 16) + + def test_evaluate(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(a=1.5, b=2.5, compute_metrics=AlmostAccuracy(), output_dir=tmp_dir) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer( + a=1.5, b=2.5, eval_len=66, compute_metrics=AlmostAccuracy(), output_dir=tmp_dir + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With logits preprocess + trainer = get_regression_trainer( + a=1.5, + b=2.5, + compute_metrics=AlmostAccuracy(), + preprocess_logits_for_metrics=lambda logits, labels: logits + 1, + output_dir=tmp_dir, + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred + 1, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + def test_evaluate_with_batch_eval_metrics(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + a=1.5, b=2.5, compute_metrics=AlmostAccuracyBatched(), batch_eval_metrics=True, output_dir=tmp_dir + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer( + a=1.5, + b=2.5, + eval_len=66, + compute_metrics=AlmostAccuracyBatched(), + batch_eval_metrics=True, + output_dir=tmp_dir, + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With logits preprocess + trainer = get_regression_trainer( + a=1.5, + b=2.5, + compute_metrics=AlmostAccuracyBatched(), + batch_eval_metrics=True, + preprocess_logits_for_metrics=lambda logits, labels: logits + 1, + output_dir=tmp_dir, + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred + 1, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + def test_evaluate_with_jit(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + a=1.5, b=2.5, compute_metrics=AlmostAccuracy(), jit_mode_eval=True, output_dir=tmp_dir + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer( + a=1.5, b=2.5, eval_len=66, compute_metrics=AlmostAccuracy(), jit_mode_eval=True, output_dir=tmp_dir + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With logits preprocess + trainer = get_regression_trainer( + a=1.5, + b=2.5, + compute_metrics=AlmostAccuracy(), + preprocess_logits_for_metrics=lambda logits, labels: logits + 1, + jit_mode_eval=True, + output_dir=tmp_dir, + ) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred + 1, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + def test_predict(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(a=1.5, b=2.5, output_dir=tmp_dir) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer(a=1.5, b=2.5, eval_len=66, output_dir=tmp_dir) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With more than one output of the model + trainer = get_regression_trainer(a=1.5, b=2.5, double_output=True, output_dir=tmp_dir) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + + # With more than one output/label of the model + trainer = get_regression_trainer( + a=1.5, b=2.5, double_output=True, label_names=["labels", "labels_2"], output_dir=tmp_dir + ) + outputs = trainer.predict(trainer.eval_dataset) + preds = outputs.predictions + labels = outputs.label_ids + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + self.assertTrue(np.array_equal(labels[0], trainer.eval_dataset.ys[0])) + self.assertTrue(np.array_equal(labels[1], trainer.eval_dataset.ys[1])) + + def test_predict_with_batch_eval_metrics(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + a=1.5, b=2.5, compute_metrics=AlmostAccuracyBatched(), batch_eval_metrics=True, output_dir=tmp_dir + ) + results = trainer.predict(trainer.eval_dataset) + preds = results.predictions + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + gt = 1.5 * x + 2.5 + self.assertTrue(np.allclose(preds, gt)) + expected_acc = AlmostAccuracy()((preds, y))["accuracy"] + self.assertAlmostEqual(results.metrics["test_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer( + a=1.5, + b=2.5, + eval_len=66, + compute_metrics=AlmostAccuracyBatched(), + batch_eval_metrics=True, + output_dir=tmp_dir, + ) + results = trainer.predict(trainer.eval_dataset) + preds = results.predictions + x, y = trainer.eval_dataset.x, trainer.eval_dataset.ys[0] + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + expected_acc = AlmostAccuracy()((preds, y))["accuracy"] + self.assertAlmostEqual(results.metrics["test_accuracy"], expected_acc) + + # With more than one output of the model + trainer = get_regression_trainer( + a=1.5, + b=2.5, + double_output=True, + compute_metrics=AlmostAccuracyBatched(), + batch_eval_metrics=True, + output_dir=tmp_dir, + ) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + + # With more than one output/label of the model + trainer = get_regression_trainer( + a=1.5, + b=2.5, + double_output=True, + label_names=["labels", "labels_2"], + compute_metrics=AlmostAccuracyBatched(), + batch_eval_metrics=True, + output_dir=tmp_dir, + ) + outputs = trainer.predict(trainer.eval_dataset) + preds = outputs.predictions + labels = outputs.label_ids + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + self.assertTrue(np.array_equal(labels[0], trainer.eval_dataset.ys[0])) + self.assertTrue(np.array_equal(labels[1], trainer.eval_dataset.ys[1])) + + def test_predict_with_jit(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(a=1.5, b=2.5, jit_mode_eval=True, output_dir=tmp_dir) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With a number of elements not a round multiple of the batch size + trainer = get_regression_trainer(a=1.5, b=2.5, eval_len=66, jit_mode_eval=True, output_dir=tmp_dir) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With more than one output of the model + trainer = get_regression_trainer(a=1.5, b=2.5, double_output=True, jit_mode_eval=True, output_dir=tmp_dir) + preds = trainer.predict(trainer.eval_dataset).predictions + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + + # With more than one output/label of the model + trainer = get_regression_trainer( + a=1.5, + b=2.5, + double_output=True, + label_names=["labels", "labels_2"], + jit_mode_eval=True, + output_dir=tmp_dir, + ) + outputs = trainer.predict(trainer.eval_dataset) + preds = outputs.predictions + labels = outputs.label_ids + x = trainer.eval_dataset.x + self.assertEqual(len(preds), 2) + self.assertTrue(np.allclose(preds[0], 1.5 * x + 2.5)) + self.assertTrue(np.allclose(preds[1], 1.5 * x + 2.5)) + self.assertTrue(np.array_equal(labels[0], trainer.eval_dataset.ys[0])) + self.assertTrue(np.array_equal(labels[1], trainer.eval_dataset.ys[1])) + + def test_dynamic_shapes(self): + eval_dataset = DynamicShapesDataset(batch_size=self.batch_size) + model = RegressionModel(a=2, b=1) + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(tmp_dir, report_to="none") + trainer = Trainer(model, args, eval_dataset=eval_dataset) + + # Check evaluation can run to completion + _ = trainer.evaluate() + + # Check predictions + preds = trainer.predict(eval_dataset) + for expected, seen in zip(eval_dataset.ys, preds.label_ids): + self.assertTrue(np.array_equal(expected, seen[: expected.shape[0]])) + self.assertTrue(np.all(seen[expected.shape[0] :] == -100)) + + for expected, seen in zip(eval_dataset.xs, preds.predictions): + self.assertTrue(np.array_equal(2 * expected + 1, seen[: expected.shape[0]])) + self.assertTrue(np.all(seen[expected.shape[0] :] == -100)) + + # Same tests with eval accumulation + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(tmp_dir, eval_accumulation_steps=2, report_to="none") + trainer = Trainer(model, args, eval_dataset=eval_dataset) + + # Check evaluation can run to completion + _ = trainer.evaluate() + + # Check predictions + preds = trainer.predict(eval_dataset) + for expected, seen in zip(eval_dataset.ys, preds.label_ids): + self.assertTrue(np.array_equal(expected, seen[: expected.shape[0]])) + self.assertTrue(np.all(seen[expected.shape[0] :] == -100)) + + for expected, seen in zip(eval_dataset.xs, preds.predictions): + self.assertTrue(np.array_equal(2 * expected + 1, seen[: expected.shape[0]])) + self.assertTrue(np.all(seen[expected.shape[0] :] == -100)) + + def test_log_level(self): + # testing only --log_level (--log_level_replica requires multiple gpus and DDP and is tested elsewhere) + logger = logging.get_logger() + log_info_string = "Running training" + + # test with the default log_level - should be the same as before and thus we test depending on is_info + is_info = logging.get_verbosity() <= 20 + + with tempfile.TemporaryDirectory() as tmp_dir: + with CaptureLogger(logger) as cl: + trainer = get_regression_trainer(output_dir=tmp_dir) + trainer.train() + if is_info: + self.assertIn(log_info_string, cl.out) + else: + self.assertNotIn(log_info_string, cl.out) + + with LoggingLevel(logging.INFO): + # test with low log_level - lower than info + with CaptureLogger(logger) as cl: + trainer = get_regression_trainer(log_level="debug", output_dir=tmp_dir) + trainer.train() + self.assertIn(log_info_string, cl.out) + + with LoggingLevel(logging.INFO): + # test with high log_level - should be quiet + with CaptureLogger(logger) as cl: + trainer = get_regression_trainer(log_level="error", output_dir=tmp_dir) + trainer.train() + self.assertNotIn(log_info_string, cl.out) + + def test_save_checkpoints(self): + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(output_dir=tmp_dir, save_steps=5) + trainer.train() + self.check_saved_checkpoints(tmp_dir, 5, int(self.n_epochs * 64 / self.batch_size)) + + # With a regular model that is not a PreTrainedModel + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(output_dir=tmp_dir, save_steps=5, pretrained=False) + trainer.train() + self.check_saved_checkpoints(tmp_dir, 5, int(self.n_epochs * 64 / self.batch_size), False) + + @require_safetensors + def test_safe_checkpoints(self): + for save_safetensors in [True, False]: + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(output_dir=tmp_dir, save_steps=5, save_safetensors=save_safetensors) + trainer.train() + self.check_saved_checkpoints( + tmp_dir, 5, int(self.n_epochs * 64 / self.batch_size), safe_weights=save_safetensors + ) + + # With a regular model that is not a PreTrainedModel + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer( + output_dir=tmp_dir, save_steps=5, pretrained=False, save_safetensors=save_safetensors + ) + trainer.train() + self.check_saved_checkpoints( + tmp_dir, 5, int(self.n_epochs * 64 / self.batch_size), False, safe_weights=save_safetensors + ) + + def test_save_collator_tokenizer_by_default(self): + class FakeCollator: + def __init__(self): + self.tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased") + self.tokenizer.add_tokens(["", ""]) + + def __call__(self, features: list[Any], return_tensors="pt") -> dict[str, Any]: + return default_data_collator(features, return_tensors) + + data_collator = FakeCollator() + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer( + output_dir=tmp_dir, save_steps=5, save_safetensors=True, data_collator=data_collator + ) + trainer.train() + loaded_tokenizer = AutoTokenizer.from_pretrained(os.path.join(tmp_dir, os.listdir(tmp_dir)[0])) + assert len(loaded_tokenizer) == len(trainer.data_collator.tokenizer), "Failed to load updated tokenizer" + + def test_load_best_model_with_save(self): + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer( + output_dir=tmp_dir, + save_steps=5, + eval_strategy="steps", + eval_steps=5, + max_steps=9, + ) + trainer.train() + # Check that we have the last known step: + assert os.path.exists(os.path.join(tmp_dir, f"checkpoint-{trainer.state.max_steps}")), ( + f"Could not find checkpoint-{trainer.state.max_steps}" + ) + # And then check the last step + assert os.path.exists(os.path.join(tmp_dir, "checkpoint-9")), "Could not find checkpoint-9" + + # Now test that using a limit works + # Should result in: + # - save at step 5 (but is deleted) + # - save at step 10 (loaded in at the end when `load_best_model=True`) + # - save at step 11 + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer( + output_dir=tmp_dir, + save_steps=5, + eval_strategy="steps", + eval_steps=5, + load_best_model_at_end=True, + save_total_limit=2, + max_steps=11, + ) + trainer.train() + # Check that we have the last known step: + assert os.path.exists(os.path.join(tmp_dir, "checkpoint-11")), "Could not find checkpoint-11" + # And then check the last multiple + assert os.path.exists(os.path.join(tmp_dir, "checkpoint-10")), "Could not find checkpoint-10" + # Finally check that we don't have an old one + assert not os.path.exists(os.path.join(tmp_dir, "checkpoint-5")), "Found checkpoint-5, limit not respected" + + # Finally check that the right model was loaded in, checkpoint-10 + # this goes by the last `eval` step check to do so, so it won't be + # the last model *saved* + model_state = trainer.model.state_dict() + final_model_weights = safetensors.torch.load_file(os.path.join(tmp_dir, "checkpoint-10", "model.safetensors")) + for k, v in model_state.items(): + assert torch.allclose(v, final_model_weights[k]), f"{k} is not the same" + + @require_torch_multi_accelerator + def test_run_seq2seq_double_train_wrap_once(self): + # test that we don't wrap the model more than once + # since wrapping primarily happens on multi-gpu setup we want multiple gpus to test for + # example DataParallel(DataParallel(model)) + + trainer = get_regression_trainer(output_dir=self.get_auto_remove_tmp_dir()) + trainer.train() + model_wrapped_before = trainer.model_wrapped + trainer.train() + model_wrapped_after = trainer.model_wrapped + self.assertIs(model_wrapped_before, model_wrapped_after, "should be not wrapped twice") + + @require_torch_up_to_2_accelerators + def test_can_resume_training(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + tmp_dir = self.get_auto_remove_tmp_dir() + kwargs = { + "output_dir": tmp_dir, + "train_len": 128, + "save_steps": 5, + "learning_rate": 0.1, + "logging_steps": 5, + } + trainer = get_regression_trainer(**kwargs) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmp_dir, "checkpoint-5") + + # Reinitialize trainer + trainer = get_regression_trainer(**kwargs) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + # Now check with a later checkpoint that it also works when we span over one epoch + checkpoint = os.path.join(tmp_dir, "checkpoint-15") + + # Reinitialize trainer and load model + trainer = get_regression_trainer(**kwargs) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + # With a regular model that is not a PreTrainedModel + tmp_dir = self.get_auto_remove_tmp_dir() + kwargs = { + "output_dir": tmp_dir, + "train_len": 128, + "save_steps": 5, + "learning_rate": 0.1, + "pretrained": False, + } + + trainer = get_regression_trainer(**kwargs) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmp_dir, "checkpoint-5") + + # Reinitialize trainer and load model + trainer = get_regression_trainer(**kwargs) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + # Now check with a later checkpoint that it also works when we span over one epoch + checkpoint = os.path.join(tmp_dir, "checkpoint-15") + + # Reinitialize trainer and load model + trainer = get_regression_trainer(**kwargs) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + # Now check failures + + # 1. fail to find a bogus checkpoint + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(output_dir=tmp_dir) + with self.assertRaises(Exception) as context: + trainer.train(resume_from_checkpoint=f"{checkpoint}-bogus") + self.assertTrue("Can't find a valid checkpoint at" in str(context.exception)) + + # 2. fail to find any checkpoint - due a fresh output_dir + tmp_dir = self.get_auto_remove_tmp_dir() + trainer = get_regression_trainer(output_dir=tmp_dir) + with self.assertRaises(Exception) as context: + trainer.train(resume_from_checkpoint=True) + self.assertTrue("No valid checkpoint found in output directory" in str(context.exception)) + + # require_torch_non_multi_accelerator is necessary because this worker blocks runs when using multiple GPUs, making + # the test slower. + @require_torch_non_multi_accelerator + @run_test_using_subprocess + @run_first + @slow + def test_can_resume_training_lm(self): + # Check if it works for a simple language modeling example + training_steps = 10 + resume_from_step = 8 + with tempfile.TemporaryDirectory() as tmpdir: + enable_full_determinism(0) + kwargs = { + "output_dir": tmpdir, + "fp16": True, + "max_steps": training_steps, + "per_device_train_batch_size": 1, + "learning_rate": 1e-5, + "lr_scheduler_type": "cosine", + "save_strategy": "steps", + "save_steps": 1, + "logging_strategy": "steps", + "logging_steps": 1, + "report_to": "none", + } + + trainer = get_language_model_trainer(**kwargs) + trainer.train(resume_from_checkpoint=False) + # Get the parameter length of the model + model_params = torch.cat([p.cpu().flatten() for p in trainer.model.parameters()]) + model_param_len = len(model_params) + # Sample uniform indexes and save the values of the parameters (considering an unrolled vector with + # all of them) + indices = torch.randint(0, model_param_len, (1000,)) + # Save the values of the parameters for later comparison + model_params_sample = model_params[indices].detach().clone() + state1 = dataclasses.asdict(trainer.state) + # Delete the reference + del model_params, trainer + # Checks if all checkpoints are there, +1 is necessary because range is 1-indexed + self.check_saved_checkpoints( + tmpdir, freq=1, total=training_steps + 1, is_pretrained=True, safe_weights=True, use_scaler=True + ) + + # Checkpoint at intermediate step + enable_full_determinism(0) + checkpoint = os.path.join(tmpdir, f"checkpoint-{resume_from_step + 1}") + trainer = get_language_model_trainer(**kwargs) + trainer.train(resume_from_checkpoint=checkpoint) + model_params = torch.cat([p.cpu().flatten() for p in trainer.model.parameters()]) + + # Check that the parameters are the same + self.assertTrue(torch.allclose(model_params[indices], model_params_sample)) + state2 = dataclasses.asdict(trainer.state) + self.check_trainer_state_are_the_same(state1, state2) + del model_params, trainer + + @unittest.skip( + reason="@muellerzr: Fix once Trainer can take an accelerate configuration. Need to set `seedable_sampler=True`." + ) + def test_resume_training_with_randomness(self): + # For more than 1 GPUs, since the randomness is introduced in the model and with DataParallel (which is used + # in this test for more than 2 GPUs), the calls to the torch RNG will happen in a random order (sometimes + # GPU 0 will call first and sometimes GPU 1). + random_torch = not torch.cuda.is_available() or backend_device_count(torch_device) <= 1 + + if torch.cuda.is_available(): + torch.backends.cudnn.deterministic = True + train_dataset = RegressionDataset(length=128) + eval_dataset = RegressionDataset() + + with self.subTest("Test every step"): + config = RegressionModelConfig(a=0, b=2, random_torch=random_torch) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + args = RegressionTrainingArguments(tmp_dir, save_steps=5, learning_rate=0.1) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + + model = RegressionRandomPreTrainedModel(config) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + trainer.train(resume_from_checkpoint=os.path.join(tmp_dir, "checkpoint-15")) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + + self.assertAlmostEqual(a, a1, delta=1e-5) + self.assertAlmostEqual(b, b1, delta=1e-5) + + with self.subTest("Test every epoch"): + config = RegressionModelConfig(a=0, b=2, random_torch=random_torch) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + args = RegressionTrainingArguments(tmp_dir, save_strategy="epoch", learning_rate=0.1) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + + model = RegressionRandomPreTrainedModel(config) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + + checkpoints = [d for d in os.listdir(tmp_dir) if d.startswith("checkpoint-")] + # There should be one checkpoint per epoch. + self.assertEqual(len(checkpoints), 3) + checkpoint_dir = sorted(checkpoints, key=lambda x: int(x.replace("checkpoint-", "")))[0] + + trainer.train(resume_from_checkpoint=os.path.join(tmp_dir, checkpoint_dir)) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + + self.assertAlmostEqual(a, a1, delta=1e-5) + self.assertAlmostEqual(b, b1, delta=1e-5) + + @slow + @require_non_hpu + @require_accelerate + @require_torch_non_multi_accelerator + def test_auto_batch_size_finder(self): + if torch.cuda.is_available(): + torch.backends.cudnn.deterministic = True + + SRC_DIR = os.path.abspath( + os.path.join(os.path.dirname(__file__), "..", "..", "examples", "pytorch", "text-classification") + ) + sys.path.append(SRC_DIR) + import run_glue + + with tempfile.TemporaryDirectory() as tmpdir: + testargs = f""" + run_glue.py + --model_name_or_path distilbert/distilbert-base-uncased + --task_name mrpc + --do_train + --do_eval + --max_seq_len 128 + --per_device_train_batch_size 4096 + --learning_rate 2e-5 + --num_train_epochs 1 + --output_dir {tmpdir} + --report_to none + --auto_find_batch_size 0 + """.split() + with self.assertRaises(RuntimeError): + with patch.object(sys, "argv", testargs): + run_glue.main() + + testargs[-1] = "1" + with patch.object(sys, "argv", testargs): + run_glue.main() + + @require_deepspeed + def test_auto_batch_size_with_deepspeed(self): + train_dataset = RegressionDataset(length=128) + + config = RegressionModelConfig(a=0, b=2) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + + for stage in [1, 2]: + deepspeed = { + "zero_optimization": { + "stage": stage, + }, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + } + + args = RegressionTrainingArguments( + tmp_dir, + do_train=True, + max_steps=2, + save_strategy="no", + per_device_train_batch_size=16, + auto_find_batch_size=True, + deepspeed=deepspeed, + ) + trainer = Trainer(model, args, train_dataset=train_dataset, callbacks=[MockCudaOOMCallback()]) + trainer.train() + self.assertEqual(trainer._train_batch_size, 14) + + def test_auto_batch_size_with_resume_from_checkpoint(self): + train_dataset = RegressionDataset(length=128) + + config = RegressionModelConfig(a=0, b=2) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + + args = RegressionTrainingArguments( + tmp_dir, + do_train=True, + max_steps=2, + save_steps=1, + per_device_train_batch_size=16, + auto_find_batch_size=True, + ) + trainer = Trainer(model, args, train_dataset=train_dataset, callbacks=[MockCudaOOMCallback()]) + trainer.train() + # After `auto_find_batch_size` is ran we should now be at 16*0.9=14 + self.assertEqual(trainer._train_batch_size, 14) + + # We can then make a new Trainer + trainer = Trainer(model, args, train_dataset=train_dataset) + # Check we are at 16 to start + self.assertEqual(trainer._train_batch_size, 16 * max(trainer.args.n_gpu, 1)) + trainer.train(resume_from_checkpoint=True) + # We should be back to 14 again, picking up based upon the last ran Trainer + self.assertEqual(trainer._train_batch_size, 14) + + # regression for this issue: https://github.com/huggingface/transformers/issues/12970 + def test_training_with_resume_from_checkpoint_false(self): + train_dataset = RegressionDataset(length=128) + eval_dataset = RegressionDataset() + + config = RegressionModelConfig(a=0, b=2) + model = RegressionRandomPreTrainedModel(config) + + tmp_dir = self.get_auto_remove_tmp_dir() + args = RegressionTrainingArguments(tmp_dir, save_steps=5, learning_rate=0.1) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + + trainer.train(resume_from_checkpoint=False) + + @require_torch_up_to_2_accelerators + def test_resume_training_with_shard_checkpoint(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer(output_dir=tmpdir, train_len=128, save_steps=5, learning_rate=0.1) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + self.convert_to_sharded_checkpoint(checkpoint) + + # Reinitialize trainer + trainer = get_regression_trainer(output_dir=tmpdir, train_len=128, save_steps=5, learning_rate=0.1) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + @require_safetensors + @require_torch_up_to_2_accelerators + def test_resume_training_with_safe_checkpoint(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + for initial_safe in [False, True]: + for loaded_safe in [False, True]: + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + save_steps=5, + learning_rate=0.1, + save_safetensors=initial_safe, + ) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + self.convert_to_sharded_checkpoint(checkpoint, load_safe=initial_safe, save_safe=loaded_safe) + + # Reinitialize trainer + trainer = get_regression_trainer( + output_dir=tmpdir, train_len=128, save_steps=5, learning_rate=0.1, save_safetensors=loaded_safe + ) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + @require_torch_up_to_2_accelerators + def test_resume_training_with_gradient_accumulation(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + gradient_accumulation_steps=2, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + + # Reinitialize trainer + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + gradient_accumulation_steps=2, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + + trainer.train(resume_from_checkpoint=checkpoint) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + @require_torch_up_to_2_accelerators + def test_resume_training_with_frozen_params(self): + # This test will fail for more than 2 GPUs since the batch size will get bigger and with the number of + # save_steps, the checkpoint will resume training at epoch 2 or more (so the data seen by the model + # won't be the same since the training dataloader is shuffled). + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + trainer.model.a.requires_grad_(False) + trainer.train() + (a, b) = trainer.model.a.item(), trainer.model.b.item() + state = dataclasses.asdict(trainer.state) + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + + # Reinitialize trainer + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + trainer.model.a.requires_grad_(False) + + trainer.train(resume_from_checkpoint=checkpoint) + + self.assertFalse(trainer.model.a.requires_grad) + (a1, b1) = trainer.model.a.item(), trainer.model.b.item() + state1 = dataclasses.asdict(trainer.state) + self.assertEqual(a, a1) + self.assertEqual(b, b1) + self.check_trainer_state_are_the_same(state, state1) + + def test_load_best_model_at_end(self): + total = int(self.n_epochs * 64 / self.batch_size) + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_steps=5, + eval_strategy="steps", + save_steps=5, + load_best_model_at_end=True, + ) + self.assertFalse(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, total) + self.check_best_model_has_been_loaded(tmpdir, 5, total, trainer, "eval_loss") + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_steps=5, + eval_strategy="steps", + save_steps=5, + load_best_model_at_end=True, + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + ) + self.assertTrue(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, total) + self.check_best_model_has_been_loaded(tmpdir, 5, total, trainer, "eval_accuracy", greater_is_better=True) + + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_strategy="epoch", + save_strategy="epoch", + load_best_model_at_end=True, + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + ) + self.assertTrue(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 64 // self.batch_size, total) + self.check_best_model_has_been_loaded( + tmpdir, 64 // self.batch_size, total, trainer, "eval_accuracy", greater_is_better=True + ) + + # Test this works with a non PreTrainedModel + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + learning_rate=0.1, + eval_steps=5, + eval_strategy="steps", + save_steps=5, + load_best_model_at_end=True, + pretrained=False, + ) + self.assertFalse(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, total, is_pretrained=False) + self.check_best_model_has_been_loaded(tmpdir, 5, total, trainer, "eval_loss", is_pretrained=False) + + @require_safetensors + def test_load_best_model_from_safetensors(self): + total = int(self.n_epochs * 64 / self.batch_size) + for save_safetensors, pretrained in product([False, True], [False, True]): + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_steps=5, + eval_strategy="steps", + save_steps=5, + load_best_model_at_end=True, + save_safetensors=save_safetensors, + pretrained=pretrained, + ) + self.assertFalse(trainer.args.greater_is_better) + trainer.train() + self.check_saved_checkpoints(tmpdir, 5, total, is_pretrained=pretrained, safe_weights=save_safetensors) + self.check_best_model_has_been_loaded( + tmpdir, 5, total, trainer, "eval_loss", is_pretrained=pretrained, safe_weights=save_safetensors + ) + + @slow + def test_trainer_eval_mrpc(self): + MODEL_ID = "google-bert/bert-base-cased-finetuned-mrpc" + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) + model = AutoModelForSequenceClassification.from_pretrained(MODEL_ID) + data_args = GlueDataTrainingArguments( + task_name="mrpc", data_dir=f"{get_tests_dir()}/fixtures/tests_samples/MRPC", overwrite_cache=True + ) + eval_dataset = GlueDataset(data_args, tokenizer=tokenizer, mode="dev") + + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = TrainingArguments(output_dir=tmp_dir, use_cpu=True, report_to="none") + trainer = Trainer(model=model, args=training_args, eval_dataset=eval_dataset) + result = trainer.evaluate() + self.assertLess(result["eval_loss"], 0.2) + + @slow + def test_trainer_eval_multiple(self): + MODEL_ID = "openai-community/gpt2" + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) + model = AutoModelForCausalLM.from_pretrained(MODEL_ID) + dataset = LineByLineTextDataset( + tokenizer=tokenizer, + file_path=PATH_SAMPLE_TEXT, + block_size=tokenizer.max_len_single_sentence, + ) + for example in dataset.examples: + example["labels"] = example["input_ids"] + with tempfile.TemporaryDirectory() as tmp_dir: + training_args = TrainingArguments( + output_dir=tmp_dir, + use_cpu=True, + per_device_eval_batch_size=1, + report_to="none", + ) + trainer = Trainer( + model=model, + args=training_args, + eval_dataset={ + "data1": dataset, + "data2": dataset, + }, + ) + result = trainer.evaluate() + self.assertIn("eval_data1_loss", result) + self.assertIn("eval_data2_loss", result) + + @slow + def test_trainer_eval_lm(self): + MODEL_ID = "distilbert/distilroberta-base" + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) + dataset = LineByLineTextDataset( + tokenizer=tokenizer, + file_path=PATH_SAMPLE_TEXT, + block_size=tokenizer.max_len_single_sentence, + ) + self.assertEqual(len(dataset), 31) + + def test_training_iterable_dataset(self): + config = RegressionModelConfig() + model = RegressionPreTrainedModel(config) + # Adding one column not used by the model should have no impact + train_dataset = SampleIterableDataset(label_names=["labels", "extra"]) + + with tempfile.TemporaryDirectory() as tmp_dir: + args = RegressionTrainingArguments(output_dir=tmp_dir, max_steps=4) + trainer = Trainer(model=model, args=args, train_dataset=train_dataset) + trainer.train() + self.assertEqual(trainer.state.global_step, 4) + + loader = trainer.get_train_dataloader() + self.assertIsInstance(loader, torch.utils.data.DataLoader) + self.assertIsInstance(loader.sampler, torch.utils.data.dataloader._InfiniteConstantSampler) + + def test_evaluation_iterable_dataset(self): + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + # Adding one column not used by the model should have no impact + eval_dataset = SampleIterableDataset(label_names=["labels", "extra"]) + + with tempfile.TemporaryDirectory() as tmp_dir: + args = RegressionTrainingArguments(output_dir=tmp_dir) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset, compute_metrics=AlmostAccuracy()) + results = trainer.evaluate() + + x, y = trainer.eval_dataset.dataset.x, trainer.eval_dataset.dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + # With a number of elements not a round multiple of the batch size + eval_dataset = SampleIterableDataset(length=66) + results = trainer.evaluate(eval_dataset) + + x, y = eval_dataset.dataset.x, eval_dataset.dataset.ys[0] + pred = 1.5 * x + 2.5 + expected_loss = ((pred - y) ** 2).mean() + self.assertAlmostEqual(results["eval_loss"], expected_loss) + expected_acc = AlmostAccuracy()((pred, y))["accuracy"] + self.assertAlmostEqual(results["eval_accuracy"], expected_acc) + + def test_predict_iterable_dataset(self): + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + + with tempfile.TemporaryDirectory() as tmp_dir: + args = RegressionTrainingArguments(output_dir=tmp_dir) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset, compute_metrics=AlmostAccuracy()) + + preds = trainer.predict(trainer.eval_dataset).predictions + x = eval_dataset.dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + # With a number of elements not a round multiple of the batch size + # Adding one column not used by the model should have no impact + test_dataset = SampleIterableDataset(length=66, label_names=["labels", "extra"]) + preds = trainer.predict(test_dataset).predictions + x = test_dataset.dataset.x + self.assertTrue(np.allclose(preds, 1.5 * x + 2.5)) + + def test_num_train_epochs_in_training(self): + # len(train_dl) < gradient_accumulation_steps shouldn't give ``ZeroDivisionError`` when ``max_steps`` is given. + # It should give 1 update step for each epoch. + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + max_steps=3, + train_len=64, + per_device_train_batch_size=16, + gradient_accumulation_steps=5, + output_dir=tmp_dir, + ) + train_output = trainer.train() + self.assertEqual(train_output.global_step, 3) + + # Even ``max_steps`` is not specified, we still expect 1 update step for each epoch if + # len(train_dl) < gradient_accumulation_steps. + trainer = get_regression_trainer( + train_len=64, per_device_train_batch_size=16, gradient_accumulation_steps=5, output_dir=tmp_dir + ) + train_output = trainer.train() + self.assertEqual(train_output.global_step, int(self.n_epochs)) + + @require_torch_multi_accelerator + def test_num_batches_in_training_with_gradient_accumulation(self): + with tempfile.TemporaryDirectory() as tmp_dir: + for num_train_epochs in [1, 2]: + for train_len in [123, 120]: + trainer = get_regression_trainer( + train_len=train_len, + per_device_train_batch_size=4, + gradient_accumulation_steps=5, + num_train_epochs=num_train_epochs, + output_dir=tmp_dir, + ) + + total_batch_samples = [] + + def wrap_get_batch_samples(fn): + def wrapped_fn(epoch_iterator, num_batches, device): + self.assertGreater(num_batches, 0) + batch_samples, num_items_in_batch = fn(epoch_iterator, num_batches, device) + self.assertEqual(len(batch_samples), num_batches) + total_batch_samples.append(num_batches) + return batch_samples, num_items_in_batch + + return wrapped_fn + + trainer.get_batch_samples = wrap_get_batch_samples(trainer.get_batch_samples) + + trainer.train() + + self.assertEqual(len(trainer.get_train_dataloader()) * num_train_epochs, sum(total_batch_samples)) + + def test_early_stopping_callback(self): + # early stopping stops training before num_training_epochs + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + num_train_epochs=20, + gradient_accumulation_steps=1, + per_device_train_batch_size=16, + load_best_model_at_end=True, + eval_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + compute_metrics=AlmostAccuracy(), + metric_for_best_model="accuracy", + ) + trainer.add_callback(EarlyStoppingCallback(1, 0.0001)) + train_output = trainer.train() + self.assertLess(train_output.global_step, 20 * 64 / 16) + + # Invalid inputs to trainer with early stopping callback result in assertion error + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + num_train_epochs=20, + gradient_accumulation_steps=1, + per_device_train_batch_size=16, + eval_strategy=IntervalStrategy.EPOCH, + compute_metrics=AlmostAccuracy(), + metric_for_best_model="accuracy", + ) + trainer.add_callback(EarlyStoppingCallback(1)) + self.assertEqual(trainer.state.global_step, 0) + try: + trainer.train() + except AssertionError: + self.assertEqual(trainer.state.global_step, 0) + + # even if load_best_model_at_end is False, `best_model_checkpoint` should be set + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + num_train_epochs=20, + gradient_accumulation_steps=1, + per_device_train_batch_size=16, + load_best_model_at_end=False, + eval_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + compute_metrics=AlmostAccuracy(), + metric_for_best_model="accuracy", + ) + trainer.add_callback(EarlyStoppingCallback(1, 0.0001)) + train_output = trainer.train() + self.assertIsNotNone(trainer.state.best_model_checkpoint) + + def test_flos_extraction(self): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(learning_rate=0.1, output_dir=tmp_dir) + + def assert_flos_extraction(trainer, wrapped_model_to_check): + self.assertEqual(trainer.model, trainer.accelerator.unwrap_model(wrapped_model_to_check)) + self.assertGreaterEqual( + getattr(trainer.accelerator.unwrap_model(wrapped_model_to_check).config, "total_flos", 0), 0 + ) + + # with plain model + assert_flos_extraction(trainer, trainer.model) + + # with enforced DataParallel + assert_flos_extraction(trainer, nn.DataParallel(trainer.model)) + + trainer.train() + self.assertTrue(isinstance(trainer.state.total_flos, float)) + + def check_checkpoint_deletion(self, trainer, output_dir, expected): + # Make fake checkpoints + for n in [5, 10, 15, 20, 25]: + os.makedirs(os.path.join(output_dir, f"{PREFIX_CHECKPOINT_DIR}-{n}"), exist_ok=True) + trainer._rotate_checkpoints(output_dir=output_dir) + glob_checkpoints = [str(x) for x in Path(output_dir).glob(f"{PREFIX_CHECKPOINT_DIR}-*")] + values = [int(re.match(f".*{PREFIX_CHECKPOINT_DIR}-([0-9]+)", d).groups()[0]) for d in glob_checkpoints] + self.assertSetEqual(set(values), set(expected)) + + def test_checkpoint_rotation(self): + with tempfile.TemporaryDirectory() as tmp_dir: + # Without best model at end + trainer = get_regression_trainer(output_dir=tmp_dir, save_total_limit=2) + self.check_checkpoint_deletion(trainer, tmp_dir, [20, 25]) + + # With best model at end + trainer = get_regression_trainer( + output_dir=tmp_dir, eval_strategy="steps", load_best_model_at_end=True, save_total_limit=2 + ) + trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-5") + self.check_checkpoint_deletion(trainer, tmp_dir, [5, 25]) + + # Edge case: we don't always honor save_total_limit=1 if load_best_model_at_end=True to be able to resume + # from checkpoint + trainer = get_regression_trainer( + output_dir=tmp_dir, eval_strategy="steps", load_best_model_at_end=True, save_total_limit=1 + ) + trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-25") + self.check_checkpoint_deletion(trainer, tmp_dir, [25]) + + trainer.state.best_model_checkpoint = os.path.join(tmp_dir, "checkpoint-5") + self.check_checkpoint_deletion(trainer, tmp_dir, [5, 25]) + + def test_compare_trainer_and_checkpoint_args_logging(self): + logger = logging.get_logger() + + with tempfile.TemporaryDirectory() as tmpdir, CaptureLogger(logger) as cl: + trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=128, + eval_steps=5, + gradient_accumulation_steps=2, + per_device_train_batch_size=4, + save_steps=5, + learning_rate=0.1, + ) + trainer.train() + + checkpoint = os.path.join(tmpdir, "checkpoint-5") + checkpoint_trainer = get_regression_trainer( + output_dir=tmpdir, + train_len=256, + eval_steps=10, + gradient_accumulation_steps=4, + per_device_train_batch_size=8, + save_steps=10, + learning_rate=0.1, + ) + checkpoint_trainer.train(resume_from_checkpoint=checkpoint) + + self.assertIn("save_steps: 10 (from args) != 5 (from trainer_state.json)", cl.out) + + self.assertIn( + "per_device_train_batch_size: 8 (from args) != 4 (from trainer_state.json)", + cl.out, + ) + self.assertIn( + "eval_steps: 10 (from args) != 5 (from trainer_state.json)", + cl.out, + ) + + def check_mem_metrics(self, trainer, check_func): + metrics = trainer.train().metrics + check_func("init_mem_cpu_alloc_delta", metrics) + check_func("train_mem_cpu_alloc_delta", metrics) + if backend_device_count(torch_device) > 0: + check_func("init_mem_gpu_alloc_delta", metrics) + check_func("train_mem_gpu_alloc_delta", metrics) + + metrics = trainer.evaluate() + check_func("eval_mem_cpu_alloc_delta", metrics) + if backend_device_count(torch_device) > 0: + check_func("eval_mem_gpu_alloc_delta", metrics) + + metrics = trainer.predict(RegressionDataset()).metrics + check_func("test_mem_cpu_alloc_delta", metrics) + if backend_device_count(torch_device) > 0: + check_func("test_mem_gpu_alloc_delta", metrics) + + def test_mem_metrics(self): + with tempfile.TemporaryDirectory() as tmp_dir: + # with mem metrics enabled + trainer = get_regression_trainer(skip_memory_metrics=False, output_dir=tmp_dir) + self.check_mem_metrics(trainer, self.assertIn) + + # with mem metrics disabled + trainer = get_regression_trainer(skip_memory_metrics=True, output_dir=tmp_dir) + self.check_mem_metrics(trainer, self.assertNotIn) + + @require_torch_fp16 + @require_torch_accelerator + def test_fp16_full_eval(self): + # this is a sensitive test so let's keep debugging printouts in place for quick diagnosis. + # it's using pretty large safety margins, but small enough to detect broken functionality. + debug = 0 + n_gpus = backend_device_count(torch_device) + + with tempfile.TemporaryDirectory() as tmp_dir: + bs = 8 + eval_len = 16 * n_gpus + # make the params somewhat big so that there will be enough RAM consumed to be able to + # measure things. We should get about 64KB for a+b in fp32 + a = torch.ones(1000, bs) + 0.001 + b = torch.ones(1000, bs) - 0.001 + + # 1. with fp16_full_eval disabled + trainer = get_regression_trainer( + a=a, b=b, eval_len=eval_len, skip_memory_metrics=False, output_dir=tmp_dir + ) + metrics = trainer.evaluate() + del trainer + gc.collect() + + fp32_init = metrics["init_mem_gpu_alloc_delta"] + fp32_eval = metrics["eval_mem_gpu_alloc_delta"] + + if debug: + print(f"fp32_init {fp32_init}") + print(f"fp32_eval {fp32_eval}") + + # here we expect the model to be preloaded in trainer.__init__ and consume around 64K gpu ram. + # perfect world: fp32_init == 64<<10 + self.assertGreater(fp32_init, 59_000) + # after eval should be no extra memory allocated - with a small margin (other than the peak + # memory consumption for the forward calculation that gets recovered) + # perfect world: fp32_eval == close to zero + self.assertLess(fp32_eval, 5_000) + + # 2. with fp16_full_eval enabled + trainer = get_regression_trainer( + a=a, b=b, eval_len=eval_len, fp16_full_eval=True, skip_memory_metrics=False, output_dir=tmp_dir + ) + metrics = trainer.evaluate() + fp16_init = metrics["init_mem_gpu_alloc_delta"] + fp16_eval = metrics["eval_mem_gpu_alloc_delta"] + + if debug: + print(f"fp16_init {fp16_init}") + print(f"fp16_eval {fp16_eval}") + + # here we expect the model to not be preloaded in trainer.__init__, so with a small margin it should be close to 0 + # perfect world: fp16_init == close to zero + self.assertLess(fp16_init, 5_000) + # here we put the model on device in eval and only `half()` of it, i.e. about 32K,(again we ignore the peak margin which gets returned back) + # perfect world: fp32_init == 32<<10 + self.assertGreater(fp16_eval, 27_000) + + # 3. relative comparison fp32 vs full fp16 + # should be about half of fp16_init + # perfect world: fp32_init/2 == fp16_eval + self.assertAlmostEqual(fp16_eval, fp32_init / 2, delta=5_000) + + @require_torch_gpu + @require_torch_non_multi_gpu + @require_torch_tensorrt_fx + def test_torchdynamo_full_eval(self): + from torch import _dynamo as torchdynamo + + # torchdynamo at the moment doesn't support DP/DDP, therefore require a single gpu + n_gpus = get_gpu_count() + + bs = 8 + eval_len = 16 * n_gpus + # make the params are somewhat big so that there will be enough RAM consumed to be able to + # measure things. We should get about 64KB for a+b in fp32 + a = torch.ones(1000, bs) + 0.001 + b = torch.ones(1000, bs) - 0.001 + + with tempfile.TemporaryDirectory() as tmp_dir: + # 1. Default - without TorchDynamo + trainer = get_regression_trainer(a=a, b=b, eval_len=eval_len, output_dir=tmp_dir) + metrics = trainer.evaluate() + original_eval_loss = metrics["eval_loss"] + del trainer + + # 2. TorchDynamo eager + trainer = get_regression_trainer( + a=a, b=b, eval_len=eval_len, torch_compile_backend="eager", output_dir=tmp_dir + ) + metrics = trainer.evaluate() + self.assertAlmostEqual(metrics["eval_loss"], original_eval_loss) + del trainer + torchdynamo.reset() + + # 3. TorchDynamo nvfuser + trainer = get_regression_trainer( + a=a, b=b, eval_len=eval_len, torch_compile_backend="nvfuser", output_dir=tmp_dir + ) + metrics = trainer.evaluate() + self.assertAlmostEqual(metrics["eval_loss"], original_eval_loss) + torchdynamo.reset() + + # 4. TorchDynamo fx2trt + trainer = get_regression_trainer( + a=a, b=b, eval_len=eval_len, torch_compile_backend="fx2trt", output_dir=tmp_dir + ) + metrics = trainer.evaluate() + self.assertAlmostEqual(metrics["eval_loss"], original_eval_loss) + torchdynamo.reset() + + @require_torch_non_multi_gpu + @require_torch_gpu + def test_torchdynamo_memory(self): + # torchdynamo at the moment doesn't support DP/DDP, therefore require a single gpu + from torch import _dynamo as torchdynamo + + class CustomTrainer(Trainer): + def compute_loss(self, model, inputs, num_items_in_batch=None, return_outputs=False): + x = inputs["x"] + output = model(x) + if self.args.n_gpu == 1: + return output.mean() + return output + + class MyModule(torch.nn.Module): + """Simple module that does aggressive fusion""" + + def __init__(self): + super().__init__() + + def forward(self, x): + for _ in range(20): + x = torch.cos(x) + return x + + mod = MyModule() + + # 1. without TorchDynamo (eager baseline) + a = torch.ones(1024, 1024, device=torch_device, requires_grad=True) + a.grad = None + trainer = CustomTrainer(model=mod) + # warmup + for _ in range(10): + orig_loss = trainer.training_step(mod, {"x": a}) + + # resets + gc.collect() + backend_empty_cache(torch_device) + backend_reset_peak_memory_stats(torch_device) + + orig_loss = trainer.training_step(mod, {"x": a}) + orig_peak_mem = backend_max_memory_allocated(torch_device) + torchdynamo.reset() + del trainer + + # 2. TorchDynamo nvfuser + with tempfile.TemporaryDirectory() as tmp_dir: + a = torch.ones(1024, 1024, device=torch_device, requires_grad=True) + a.grad = None + args = TrainingArguments(output_dir=tmp_dir, torch_compile_backend="nvfuser") + trainer = CustomTrainer(model=mod, args=args) + # warmup + for _ in range(10): + loss = trainer.training_step(mod, {"x": a}) + + # resets + gc.collect() + backend_empty_cache(torch_device) + backend_reset_peak_memory_stats(torch_device) + + loss = trainer.training_step(mod, {"x": a}) + peak_mem = backend_max_memory_allocated(torch_device) + torchdynamo.reset() + del trainer + + # Functional check + self.assertAlmostEqual(loss, orig_loss) + + # AOT Autograd recomputation and nvfuser recomputation optimization + # aggressively fuses the operations and reduce the memory footprint. + self.assertGreater(orig_peak_mem, peak_mem * 2) + + @require_torch_accelerator + @require_torch_bf16 + def test_bf16_full_eval(self): + # note: most of the logic is the same as test_fp16_full_eval + + # this is a sensitive test so let's keep debugging printouts in place for quick diagnosis. + # it's using pretty large safety margins, but small enough to detect broken functionality. + debug = 0 + n_gpus = backend_device_count(torch_device) + + bs = 8 + eval_len = 16 * n_gpus + # make the params somewhat big so that there will be enough RAM consumed to be able to + # measure things. We should get about 64KB for a+b in fp32 + a = torch.ones(1000, bs) + 0.001 + b = torch.ones(1000, bs) - 0.001 + + with tempfile.TemporaryDirectory() as tmp_dir: + # 1. with bf16_full_eval disabled + trainer = get_regression_trainer( + a=a, b=b, eval_len=eval_len, skip_memory_metrics=False, output_dir=tmp_dir + ) + metrics = trainer.evaluate() + del trainer + gc.collect() + + fp32_init = metrics["init_mem_gpu_alloc_delta"] + fp32_eval = metrics["eval_mem_gpu_alloc_delta"] + + if debug: + print(f"fp32_init {fp32_init}") + print(f"fp32_eval {fp32_eval}") + + # here we expect the model to be preloaded in trainer.__init__ and consume around 64K gpu ram. + # perfect world: fp32_init == 64<<10 + self.assertGreater(fp32_init, 59_000) + # after eval should be no extra memory allocated - with a small margin (other than the peak + # memory consumption for the forward calculation that gets recovered) + # perfect world: fp32_eval == close to zero + self.assertLess(fp32_eval, 5_000) + + # 2. with bf16_full_eval enabled + trainer = get_regression_trainer( + a=a, b=b, eval_len=eval_len, bf16_full_eval=True, skip_memory_metrics=False, output_dir=tmp_dir + ) + metrics = trainer.evaluate() + bf16_init = metrics["init_mem_gpu_alloc_delta"] + bf16_eval = metrics["eval_mem_gpu_alloc_delta"] + + if debug: + print(f"bf16_init {bf16_init}") + print(f"bf16_eval {bf16_eval}") + + # here we expect the model to not be preloaded in trainer.__init__, so with a small margin it should be close to 0 + # perfect world: bf16_init == close to zero + self.assertLess(bf16_init, 5_000) + # here we put the model on device in eval and only `half()` of it, i.e. about 32K,(again we ignore the peak margin which gets returned back) + # perfect world: fp32_init == 32<<10 + self.assertGreater(bf16_eval, 27_000) + + # 3. relative comparison fp32 vs full bf16 + # should be about half of bf16_init + # perfect world: fp32_init/2 == bf16_eval + self.assertAlmostEqual(bf16_eval, fp32_init / 2, delta=5_000) + + def test_no_wd_param_group(self): + model = nn.Sequential(TstLayer(128), nn.ModuleList([TstLayer(128), TstLayer(128)])) + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = Trainer(model=model, args=TrainingArguments(output_dir=tmp_dir, report_to="none")) + trainer.create_optimizer_and_scheduler(10) + wd_names = ['0.linear1.weight', '0.linear2.weight', '1.0.linear1.weight', '1.0.linear2.weight', '1.1.linear1.weight', '1.1.linear2.weight'] # fmt: skip + wd_params = [p for n, p in model.named_parameters() if n in wd_names] + no_wd_params = [p for n, p in model.named_parameters() if n not in wd_names] + self.assertListEqual(trainer.optimizer.param_groups[0]["params"], wd_params) + self.assertListEqual(trainer.optimizer.param_groups[1]["params"], no_wd_params) + + @slow + @run_first + @require_non_hpu + @require_torch_multi_accelerator + def test_end_to_end_example(self): + # Tests that `translation.py` will run without issues + script_path = os.path.abspath( + os.path.join( + os.path.dirname(__file__), "..", "..", "examples", "pytorch", "translation", "run_translation.py" + ) + ) + + with tempfile.TemporaryDirectory() as tmpdir: + command = [ + "accelerate", + "launch", + script_path, + "--model_name_or_path", + "google-t5/t5-small", + "--per_device_train_batch_size", + "1", + "--output_dir", + tmpdir, + "--overwrite_output_dir", + "--do_train", + "--max_train_samples", + "64", + "--num_train_epochs", + "1", + "--dataset_name", + "wmt16", + "--dataset_config", + "ro-en", + "--source_lang", + "en", + "--target_lang", + "ro", + "--do_predict", + "--max_predict_samples", + "64", + "--predict_with_generate", + "--ddp_timeout", + "60", + "--report_to", + "none", + ] + execute_subprocess_async(command) + # successful return here == success - any errors would have caused an error or a timeout in the sub-call + + def test_accelerator_config_empty(self): + # Checks that a config can be made with the defaults if not passed + with tempfile.TemporaryDirectory() as tmp_dir: + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + + # Leaves one option as something *not* basic + args = RegressionTrainingArguments(output_dir=tmp_dir) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset) + self.assertEqual(trainer.accelerator.split_batches, False) + self.assertEqual(trainer.accelerator.dispatch_batches, None) + self.assertEqual(trainer.accelerator.even_batches, True) + self.assertEqual(trainer.accelerator.use_seedable_sampler, True) + + if GRAD_ACCUM_KWARGS_VERSION_AVAILABLE: + # gradient accumulation kwargs configures gradient_state + self.assertNotIn("sync_each_batch", trainer.accelerator.gradient_state.plugin_kwargs) + + def test_accelerator_config_from_dict(self): + # Checks that accelerator kwargs can be passed through + # and the accelerator is initialized respectively + with tempfile.TemporaryDirectory() as tmp_dir: + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + + accelerator_config: dict[str, Any] = { + "split_batches": True, + "dispatch_batches": True, + "even_batches": False, + "use_seedable_sampler": True, + } + if GRAD_ACCUM_KWARGS_VERSION_AVAILABLE: + accelerator_config["gradient_accumulation_kwargs"] = {"sync_each_batch": True} + + # Leaves all options as something *not* basic + args = RegressionTrainingArguments(output_dir=tmp_dir, accelerator_config=accelerator_config) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset) + self.assertEqual(trainer.accelerator.split_batches, True) + self.assertEqual(trainer.accelerator.dispatch_batches, True) + self.assertEqual(trainer.accelerator.even_batches, False) + self.assertEqual(trainer.accelerator.use_seedable_sampler, True) + + def test_accelerator_config_from_yaml(self): + # Checks that accelerator kwargs can be passed through + # and the accelerator is initialized respectively + with tempfile.TemporaryDirectory() as tmp_dir: + path_file = Path(tmp_dir) / "accelerator_config.json" + with open(path_file, "w") as f: + accelerator_config = { + "split_batches": True, + "dispatch_batches": True, + "even_batches": False, + "use_seedable_sampler": False, + } + json.dump(accelerator_config, f) + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + + # Leaves all options as something *not* basic + args = RegressionTrainingArguments(output_dir=tmp_dir, accelerator_config=path_file) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset) + self.assertEqual(trainer.accelerator.split_batches, True) + self.assertEqual(trainer.accelerator.dispatch_batches, True) + self.assertEqual(trainer.accelerator.even_batches, False) + self.assertEqual(trainer.accelerator.use_seedable_sampler, False) + + def test_accelerator_config_from_dataclass(self): + # Checks that accelerator kwargs can be passed through + # and the accelerator is initialized respectively + + accelerator_config = AcceleratorConfig( + split_batches=True, + dispatch_batches=True, + even_batches=False, + use_seedable_sampler=False, + ) + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + with tempfile.TemporaryDirectory() as tmp_dir: + args = RegressionTrainingArguments(output_dir=tmp_dir, accelerator_config=accelerator_config) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset) + self.assertEqual(trainer.accelerator.split_batches, True) + self.assertEqual(trainer.accelerator.dispatch_batches, True) + self.assertEqual(trainer.accelerator.even_batches, False) + self.assertEqual(trainer.accelerator.use_seedable_sampler, False) + + @require_accelerate_version_min_0_28 + def test_accelerate_config_from_dataclass_grad_accum(self): + # Checks that accelerator kwargs can be passed through + # and the accelerator is initialized respectively + + grad_acc_kwargs = { + "num_steps": 10, + "adjust_scheduler": False, + "sync_with_dataloader": False, + "sync_each_batch": True, + } + accelerator_config = AcceleratorConfig( + split_batches=True, + dispatch_batches=True, + even_batches=False, + use_seedable_sampler=False, + gradient_accumulation_kwargs=grad_acc_kwargs, + ) + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + with tempfile.TemporaryDirectory() as tmp_dir: + args = RegressionTrainingArguments(output_dir=tmp_dir, accelerator_config=accelerator_config) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset) + self.assertEqual(trainer.args.gradient_accumulation_steps, 10) + + def test_accelerator_config_from_partial(self): + # Checks that accelerator kwargs can be passed through + # and the accelerator is initialized respectively + with tempfile.TemporaryDirectory() as tmp_dir: + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + + # Leaves one option as something *not* basic + args = RegressionTrainingArguments( + output_dir=tmp_dir, + accelerator_config={ + "split_batches": True, + }, + ) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset) + self.assertEqual(trainer.accelerator.split_batches, True) + self.assertEqual(trainer.accelerator.dispatch_batches, None) + self.assertEqual(trainer.accelerator.even_batches, True) + self.assertEqual(trainer.accelerator.use_seedable_sampler, True) + + def test_accelerator_custom_state(self): + AcceleratorState._reset_state(reset_partial_state=True) + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(ValueError) as cm: + _ = RegressionTrainingArguments(output_dir=tmp_dir, accelerator_config={"use_configured_state": True}) + self.assertIn("Please define this beforehand", str(cm.warnings[0].message)) + _ = Accelerator() + _ = RegressionTrainingArguments(output_dir=tmp_dir, accelerator_config={"use_configured_state": True}) + AcceleratorState._reset_state(reset_partial_state=True) + + @require_accelerate_version_min_0_28 + def test_accelerator_config_from_dict_grad_accum_num_steps(self): + with tempfile.TemporaryDirectory() as tmp_dir: + config = RegressionModelConfig(a=1.5, b=2.5) + model = RegressionPreTrainedModel(config) + eval_dataset = SampleIterableDataset() + + # case - TrainingArguments.gradient_accumulation_steps == 1 + # - gradient_accumulation_kwargs['num_steps] == 1 + # results in grad accum set to 1 + args = RegressionTrainingArguments( + output_dir=tmp_dir, + gradient_accumulation_steps=1, + accelerator_config={ + "gradient_accumulation_kwargs": { + "num_steps": 1, + } + }, + ) + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset) + self.assertEqual(trainer.accelerator.gradient_state.plugin_kwargs["num_steps"], 1) + + # case - TrainingArguments.gradient_accumulation_steps > 1 + # - gradient_accumulation_kwargs['num_steps] specified + # results in exception raised + args = RegressionTrainingArguments( + output_dir=tmp_dir, + gradient_accumulation_steps=2, + accelerator_config={ + "gradient_accumulation_kwargs": { + "num_steps": 10, + } + }, + ) + with self.assertRaises(Exception) as context: + trainer = Trainer(model=model, args=args, eval_dataset=eval_dataset) + self.assertTrue("The `AcceleratorConfig`'s `num_steps` is set but" in str(context.exception)) + + def test_accelerator_config_not_instantiated(self): + # Checks that accelerator kwargs can be passed through + # and the accelerator is initialized respectively + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(NotImplementedError) as context: + _ = RegressionTrainingArguments( + output_dir=tmp_dir, + accelerator_config=AcceleratorConfig, + ) + self.assertTrue("Tried passing in a callable to `accelerator_config`" in str(context.exception)) + + # Now test with a custom subclass + @dataclasses.dataclass + class CustomAcceleratorConfig(AcceleratorConfig): + pass + + @dataclasses.dataclass + class CustomTrainingArguments(TrainingArguments): + accelerator_config: dict = dataclasses.field( + default=CustomAcceleratorConfig, + ) + + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(NotImplementedError) as context: + _ = CustomTrainingArguments( + output_dir=tmp_dir, + ) + self.assertTrue("Tried passing in a callable to `accelerator_config`" in str(context.exception)) + + def test_torch_dtype_to_json(self): + @dataclasses.dataclass + class TorchDtypeTrainingArguments(TrainingArguments): + torch_dtype: torch.dtype = dataclasses.field( + default=torch.float32, + ) + + for dtype in [ + "float32", + "float64", + "complex64", + "complex128", + "float16", + "bfloat16", + "uint8", + "int8", + "int16", + "int32", + "int64", + "bool", + ]: + torch_dtype = getattr(torch, dtype) + with tempfile.TemporaryDirectory() as tmp_dir: + args = TorchDtypeTrainingArguments(output_dir=tmp_dir, torch_dtype=torch_dtype) + + args_dict = args.to_dict() + self.assertIn("torch_dtype", args_dict) + self.assertEqual(args_dict["torch_dtype"], dtype) + + @require_accelerate_version_min_0_30 + def test_eval_use_gather_object(self): + train_dataset = RegressionDataset() + eval_dataset = RegressionDataset() + model = RegressionDictModel() + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(tmp_dir, report_to="none", eval_use_gather_object=True) + trainer = Trainer(model, args, train_dataset=train_dataset, eval_dataset=eval_dataset) + trainer.train() + _ = trainer.evaluate() + _ = trainer.predict(eval_dataset) + + def test_trainer_saves_tokenizer(self): + MODEL_ID = "google-bert/bert-base-uncased" + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=False) + + with tempfile.TemporaryDirectory() as tmp_dir: + config = RegressionModelConfig(a=1.5, b=2.5) + trainer = Trainer( + model=RegressionPreTrainedModel(config), + args=TrainingArguments(output_dir=tmp_dir), + processing_class=tokenizer, + ) + trainer.save_model() + + reloaded_tokenizer = AutoTokenizer.from_pretrained(tmp_dir) + + # For tokenizers, there isn't a direct to_dict method and the properties stored in the configs e.g. + # saved tokens change overtime, so we check that two tokenizers are equal by comparing their encoded outputs + test_sentence = "This is a test sentence" + self.assertListEqual( + tokenizer(test_sentence, padding="max_length").input_ids, + reloaded_tokenizer(test_sentence, padding="max_length").input_ids, + ) + + @require_vision + def test_trainer_saves_image_processor(self): + MODEL_ID = "openai/clip-vit-base-patch32" + image_processor = AutoImageProcessor.from_pretrained(MODEL_ID) + + with tempfile.TemporaryDirectory() as tmp_dir: + config = RegressionModelConfig(a=1.5, b=2.5) + trainer = Trainer( + model=RegressionPreTrainedModel(config), + args=TrainingArguments(output_dir=tmp_dir, report_to="none"), + processing_class=image_processor, + ) + trainer.save_model() + reloaded_image_processor = AutoImageProcessor.from_pretrained(tmp_dir) + + self.assertDictEqual(image_processor.to_dict(), reloaded_image_processor.to_dict()) + + def test_trainer_saves_feature_extractor(self): + MODEL_ID = "facebook/wav2vec2-base-960h" + feature_extractor = AutoFeatureExtractor.from_pretrained(MODEL_ID) + + with tempfile.TemporaryDirectory() as tmp_dir: + config = RegressionModelConfig(a=1.5, b=2.5) + trainer = Trainer( + model=RegressionPreTrainedModel(config), + args=TrainingArguments(output_dir=tmp_dir, report_to="none"), + processing_class=feature_extractor, + ) + trainer.save_model() + + reloaded_feature_extractor = AutoFeatureExtractor.from_pretrained(tmp_dir) + + self.assertDictEqual(feature_extractor.to_dict(), reloaded_feature_extractor.to_dict()) + + @require_vision + def test_trainer_saves_processor(self): + MODEL_ID = "openai/clip-vit-base-patch32" + image_processor = AutoImageProcessor.from_pretrained(MODEL_ID) + tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, use_fast=False) + processor = AutoProcessor.from_pretrained(MODEL_ID) + + with tempfile.TemporaryDirectory() as tmp_dir: + config = RegressionModelConfig(a=1.5, b=2.5) + trainer = Trainer( + model=RegressionPreTrainedModel(config), + args=TrainingArguments(output_dir=tmp_dir, report_to="none"), + processing_class=processor, + ) + trainer.save_model() + + reloaded_processor = AutoProcessor.from_pretrained(tmp_dir) + reloaded_image_processor = AutoImageProcessor.from_pretrained(tmp_dir) + reloaded_tokenizer = AutoTokenizer.from_pretrained(tmp_dir) + + self.assertDictEqual(reloaded_processor.to_dict(), processor.to_dict()) + + image_processor_dict = image_processor.to_dict() + reloaded_image_processor_dict = reloaded_image_processor.to_dict() + # When the processor is saved in the trainer, the _processor_class gets set in the reload_image_processor dict + image_processor_dict.pop("_processor_class") + reloaded_image_processor_dict.pop("_processor_class") + self.assertDictEqual(image_processor_dict, reloaded_image_processor_dict) + + # For tokenizers, there isn't a direct to_dict method and the properties stored in the configs e.g. + # saved tokens change overtime, so we check that two tokenizers are equal by comparing their encoded outputs + test_sentence = "This is a test sentence" + self.assertListEqual( + tokenizer(test_sentence, padding="max_length").input_ids, + reloaded_tokenizer(test_sentence, padding="max_length").input_ids, + ) + + def test_save_best_checkpoint(self): + freq = int(64 / self.batch_size) + total = int(self.n_epochs * 64 / self.batch_size) + + # Case 1: args.metric_for_best_model == "accuracy". + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_strategy="epoch", + save_strategy="best", + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + ) + self.assertTrue(trainer.args.metric_for_best_model == "accuracy") + + with patch.object( + trainer, + "_evaluate", + side_effect=[ + {"eval_loss": 0.03, "eval_accuracy": 0.60, "epoch": 1.0}, + {"eval_loss": 0.02, "eval_accuracy": 0.65, "epoch": 2.0}, + {"eval_loss": 0.01, "eval_accuracy": 0.64, "epoch": 3.0}, + ], + ): + trainer.train() + + self.assertEqual(len(os.listdir(tmpdir)), 2) + self.check_saved_checkpoints( + output_dir=tmpdir, + freq=freq, + total=total, + ) + + # Case 2: args.metric_for_best_model == "loss". + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_strategy="epoch", + save_strategy="best", + metric_for_best_model="loss", + compute_metrics=AlmostAccuracy(), + ) + self.assertTrue(trainer.args.metric_for_best_model == "loss") + + with patch.object( + trainer, + "_evaluate", + side_effect=[ + {"eval_loss": 0.03, "eval_accuracy": 0.60, "epoch": 1.0}, + {"eval_loss": 0.02, "eval_accuracy": 0.65, "epoch": 2.0}, + {"eval_loss": 0.03, "eval_accuracy": 0.66, "epoch": 3.0}, + ], + ): + trainer.train() + + self.assertEqual(len(os.listdir(tmpdir)), 2) + self.check_saved_checkpoints( + output_dir=tmpdir, + freq=freq, + total=total, + ) + + def test_metric_for_best_model_behavior(self): + # Case 1: Metric name not provided when `save_strategy == "best"`. + # Should raise ValueError. + with tempfile.TemporaryDirectory() as tmpdir: + with self.assertRaises(ValueError) as context: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_strategy="epoch", + save_strategy="best", + compute_metrics=AlmostAccuracy(), + ) + self.assertIn("`args.metric_for_best_model` must be provided", str(context.exception)) + + # Case 2: Metric name not provided when `load_best_model_at_end == True`. + # `metric_for_best_model` should be set to `"loss"` by default. + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + a=1.5, + b=2.5, + output_dir=tmpdir, + learning_rate=0.1, + eval_strategy="steps", + save_strategy="steps", + load_best_model_at_end=True, + ) + self.assertTrue(trainer.args.metric_for_best_model == "loss") + + def test_best_model_checkpoint_behavior(self): + # Case 1. Never evaluated, save_total_limit > 1 and save_steps == 1. + # Both best_metric and best_model_checkpoint should be None. + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + eval_strategy="steps", + save_strategy="steps", + save_steps=1, + metric_for_best_model="accuracy", + greater_is_better=True, + ) + trainer.train() + + assert trainer.state.best_metric is None + assert trainer.state.best_model_checkpoint is None + assert len(os.listdir(tmpdir)) == trainer.state.global_step + + # Case 2. Never evaluated and save_total_limit == 1. + # Both best_metric and best_model_checkpoint should be None. + # Only the last checkpoint should remain. + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + eval_strategy="steps", + save_strategy="steps", + save_steps=1, + metric_for_best_model="accuracy", + greater_is_better=True, + save_total_limit=1, + ) + trainer.train() + + num_steps = trainer.state.global_step + + assert trainer.state.best_metric is None + assert trainer.state.best_model_checkpoint is None + assert len(os.listdir(tmpdir)) == 1 + + ckpt = os.path.join(tmpdir, f"{PREFIX_CHECKPOINT_DIR}-{num_steps}") + assert os.path.isdir(ckpt) + assert os.listdir(tmpdir)[0] == f"{PREFIX_CHECKPOINT_DIR}-{num_steps}" + + # Case 3. eval_strategy == save_strategy. + # best_model_checkpoint should be at epoch 1. + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + eval_strategy="epoch", + save_strategy="epoch", + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + greater_is_better=True, + load_best_model_at_end=False, + ) + + with patch.object( + trainer, + "_evaluate", + side_effect=evaluate_side_effect_factory( + [ + {"eval_accuracy": 0.59}, + {"eval_accuracy": 0.57}, + {"eval_accuracy": 0.55}, + ] + ), + ): + trainer.train() + + steps_per_epoch = get_steps_per_epoch(trainer) + + assert trainer.state.best_metric == 0.59 + assert trainer.state.best_global_step == steps_per_epoch + + best_ckpt = os.path.join(tmpdir, f"{PREFIX_CHECKPOINT_DIR}-{trainer.state.best_global_step}") + assert trainer.state.best_model_checkpoint == best_ckpt + + assert len(os.listdir(tmpdir)) == trainer.state.num_train_epochs + + # Case 4. eval_strategy != save_strategy. + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + eval_strategy="epoch", + save_strategy="steps", + save_steps=1, + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + greater_is_better=True, + load_best_model_at_end=False, + ) + + with patch.object( + trainer, + "_evaluate", + side_effect=evaluate_side_effect_factory( + [ + {"eval_accuracy": 0.59}, + {"eval_accuracy": 0.57}, + {"eval_accuracy": 0.55}, + ] + ), + ): + trainer.train() + + steps_per_epoch = get_steps_per_epoch(trainer) + + assert trainer.state.best_metric == 0.59 + assert trainer.state.best_global_step == steps_per_epoch + + best_ckpt = os.path.join(tmpdir, f"{PREFIX_CHECKPOINT_DIR}-{trainer.state.best_global_step}") + assert trainer.state.best_model_checkpoint == best_ckpt + + assert len(os.listdir(tmpdir)) == trainer.state.global_step + + # Case 5. Multiple checkpoints, save_total_limit == 1. + # Best metric is found at step 1 and that checkpoint should be saved. + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + eval_strategy="steps", + eval_steps=1, + save_strategy="steps", + save_steps=1, + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + greater_is_better=True, + save_total_limit=1, + ) + + with patch.object( + trainer, + "_evaluate", + side_effect=evaluate_side_effect_factory( + [ + {"eval_accuracy": 0.90}, + {"eval_accuracy": 0.80}, + {"eval_accuracy": 0.70}, + ] + ), + ): + trainer.train() + + assert trainer.state.best_metric == 0.90 + assert trainer.state.best_global_step == 1 + + best_ckpt = os.path.join(tmpdir, f"{PREFIX_CHECKPOINT_DIR}-{trainer.state.best_global_step}") + assert trainer.state.best_model_checkpoint == best_ckpt + + assert len(os.listdir(tmpdir)) == 1 + + # Case 6. Saving happens more often and eval/save mismatch. + # `best_model_checkpoint` should be None due to a step mismatch. + with tempfile.TemporaryDirectory() as tmpdir: + trainer = get_regression_trainer( + output_dir=tmpdir, + eval_strategy="steps", + eval_steps=3, + save_strategy="steps", + save_steps=2, + metric_for_best_model="accuracy", + compute_metrics=AlmostAccuracy(), + greater_is_better=True, + ) + + with patch.object( + trainer, + "_evaluate", + side_effect=evaluate_side_effect_factory( + [ + {"eval_accuracy": 0.90}, + {"eval_accuracy": 0.80}, + {"eval_accuracy": 0.70}, + ] + ), + ): + trainer.train() + + assert trainer.state.best_metric == 0.90 + assert trainer.state.best_global_step == 3 + + assert trainer.state.best_model_checkpoint is None + + assert len(os.listdir(tmpdir)) == trainer.state.global_step // 2 + + def test_special_token_aligment(self): + """ + Tests that special token changes in the tokenizer result in model configs updates when using the trainer, to + ensure special tokens are aligned across configs + """ + + model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM") + tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM") + + # add new special tokens to tokenizer, so we can test that trainer aligns the model configs with the tokenizer + tokenizer.eos_token = "<|im_end|>" + tokenizer.pad_token = "<|im_end|>" + tokenizer.bos_token = "<|im_start|>" + tokenizer.add_special_tokens({"additional_special_tokens": ["<|im_end|>", "<|im_start|>"]}) + + # the model needs to have its embedding layer resized accordingly + model.resize_token_embeddings(len(tokenizer), pad_to_multiple_of=64) + + # create a random dataset from the **new** vocab size + x = torch.randint(0, len(tokenizer), (64,)) + dataset = RepeatDataset(x, length=2) + + with tempfile.TemporaryDirectory() as tmpdir: + training_args = TrainingArguments( + output_dir=tmpdir, report_to="none", max_steps=1, per_device_train_batch_size=1 + ) + trainer = Trainer( + model=model, + args=training_args, + processing_class=tokenizer, + train_dataset=dataset, + ) + + # We haven't started training -> not yet aligned + self.assertNotEqual(trainer.model.config.eos_token_id, tokenizer.eos_token_id) + self.assertNotEqual(trainer.model.config.pad_token_id, tokenizer.pad_token_id) + self.assertNotEqual(trainer.model.config.bos_token_id, tokenizer.bos_token_id) + + trainer.train() + + # Must be aligned as soon as we start training + self.assertEqual(trainer.model.config.eos_token_id, tokenizer.eos_token_id) + self.assertEqual(trainer.model.config.pad_token_id, tokenizer.pad_token_id) + self.assertEqual(trainer.model.config.bos_token_id, tokenizer.bos_token_id) + + +@require_torch +@is_staging_test +class TrainerIntegrationWithHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + def test_push_to_hub(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + output_dir_name = tmp_repo.repo_name + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, output_dir_name), + push_to_hub=True, + hub_token=self._token, + ) + url = trainer.push_to_hub() + + # Extract repo_name from the url + re_search = re.search(ENDPOINT_STAGING + r"/([^/]+/[^/]+)/", url) + self.assertTrue(re_search is not None) + repo_name = re_search.groups()[0] + + self.assertEqual(repo_name, f"{USER}/{output_dir_name}") + + model = RegressionPreTrainedModel.from_pretrained(repo_name) + self.assertEqual(model.a.item(), trainer.model.a.item()) + self.assertEqual(model.b.item(), trainer.model.b.item()) + + def test_push_to_hub_in_organization(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(output_dir=tmp_dir) + trainer.save_model() + output_dir_name = tmp_repo.repo_name + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, output_dir_name), + push_to_hub=True, + hub_model_id=f"valid_org/{output_dir_name}", + hub_token=self._token, + ) + url = trainer.push_to_hub() + + # Extract repo_name from the url + re_search = re.search(ENDPOINT_STAGING + r"/([^/]+/[^/]+)/", url) + self.assertTrue(re_search is not None) + repo_name = re_search.groups()[0] + self.assertEqual(repo_name, f"valid_org/{output_dir_name}") + + model = RegressionPreTrainedModel.from_pretrained(f"valid_org/{output_dir_name}") + self.assertEqual(model.a.item(), trainer.model.a.item()) + self.assertEqual(model.b.item(), trainer.model.b.item()) + + def get_commit_history(self, repo): + commit_logs = subprocess.run( + ["git", "log"], + capture_output=True, + check=True, + encoding="utf-8", + cwd=repo, + ).stdout + commits = commit_logs.split("\n\n")[1::2] + return [commit.strip() for commit in commits] + + # TODO: @ydshieh or @SunMarc + @unittest.skip("unknown failure reason, possibly staging hub issue") + def test_push_to_hub_with_saves_each_epoch(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertLogs(level="WARNING") as logs: + output_dir_name = tmp_repo.repo_name + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, output_dir_name), + push_to_hub=True, + hub_token=self._token, + # To avoid any flakiness if the training goes faster than the uploads. + hub_always_push=True, + save_strategy="epoch", + ) + trainer.train() + + commits = list_repo_commits(f"{USER}/{output_dir_name}", token=self._token) + commits = [c.title for c in commits] + self.assertIn("initial commit", commits) + self.assertIn("Training in progress, epoch 1", commits) + self.assertIn("Training in progress, epoch 2", commits) + # Epochs 3 and 4 are not guaranteed to be present (empty commits) + self.assertTrue(any("Skipping to prevent empty commit." in record.message for record in logs.records)) + + def test_push_to_hub_with_saves_each_n_steps(self): + num_gpus = max(1, backend_device_count(torch_device)) + if num_gpus > 2: + self.skipTest(reason="More than 2 GPUs available") + + with TemporaryHubRepo(token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertLogs(level="WARNING") as logs: + output_dir_name = tmp_repo.repo_name + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, output_dir_name), + push_to_hub=True, + hub_token=self._token, + # To avoid any flakiness if the training goes faster than the uploads. + hub_always_push=True, + save_strategy="steps", + save_steps=5, + ) + trainer.train() + + commits = list_repo_commits(f"{USER}/{output_dir_name}", token=self._token) + commits = [c.title for c in commits] + self.assertIn("initial commit", commits) + + # Some commits are skipped if nothing has changed + # We expect 1 commit per 5 epochs + 1 commit at the end + nb_empty_commits = len( + [record for record in logs.records if "Skipping to prevent empty commit." in record.message] + ) + nb_epoch_commits = len([commit for commit in commits if "Training in progress, step" in commit]) + + # max_steps depend on the number of available GPUs + max_steps = math.ceil(trainer.args.num_train_epochs * len(trainer.get_train_dataloader())) + nb_expected_commits = len(range(5, max_steps, 5)) + + # '>=' since final commit might be an empty commit as well (not deterministic) + self.assertGreaterEqual(nb_empty_commits + nb_epoch_commits, nb_expected_commits) + + @require_tensorboard + def test_push_to_hub_with_tensorboard_logs(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + output_dir_name = tmp_repo.repo_name + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, output_dir_name), + hub_token=self._token, + save_strategy="epoch", + report_to=["tensorboard"], + keep_report_to=True, + ) + trainer.train() + # Push the runs via `push_to_hub()` + trainer.push_to_hub() + + files = list_repo_files(f"{USER}/{output_dir_name}", token=self._token) + found_log = False + for f in files: + if len(f.split("runs")) > 1 and "events.out.tfevents" in f: + found_log = True + + assert found_log is True, "No tensorboard log found in repo" + + def test_push_to_hub_tags(self): + # Checks if `trainer.push_to_hub()` works correctly by adding the desired + # tag without having to pass `tags` in `push_to_hub` + # see: + with TemporaryHubRepo(token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + output_dir_name = tmp_repo.repo_name + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, output_dir_name), + push_to_hub=True, + hub_token=self._token, + ) + + trainer.model.add_model_tags(["test-trainer-tags"]) + + url = trainer.push_to_hub() + + # Extract repo_name from the url + re_search = re.search(ENDPOINT_STAGING + r"/([^/]+/[^/]+)/", url) + self.assertTrue(re_search is not None) + repo_name = re_search.groups()[0] + + self.assertEqual(repo_name, f"{USER}/{output_dir_name}") + + model_card = ModelCard.load(repo_name) + self.assertTrue("test-trainer-tags" in model_card.data.tags) + + def test_push_to_hub_with_revision(self): + # Checks if `trainer.push_to_hub()` works correctly by adding revision + with TemporaryHubRepo(token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + output_dir_name = tmp_repo.repo_name + trainer = get_regression_trainer( + output_dir=os.path.join(tmp_dir, output_dir_name), + push_to_hub=True, + hub_token=self._token, + ) + branch = "v1.0" + create_branch(repo_id=trainer.hub_model_id, branch=branch, token=self._token, exist_ok=True) + url = trainer.push_to_hub(revision=branch) + + # Extract branch from the url + re_search = re.search(r"tree/([^/]+)/", url) + self.assertIsNotNone(re_search) + + branch_name = re_search.groups()[0] + self.assertEqual(branch_name, branch) + + +@require_torch +@require_optuna +class TrainerHyperParameterOptunaIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + return {} + + def model_init(trial): + if trial is not None: + a = trial.suggest_int("a", -4, 4) + b = trial.suggest_int("b", -4, 4) + else: + a = 0 + b = 0 + config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(config) + + def hp_name(trial): + return MyTrialShortNamer.shortname(trial.params) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + eval_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=4, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + ) + trainer.hyperparameter_search(direction="minimize", hp_space=hp_space, hp_name=hp_name, n_trials=4) + + +@require_torch +@require_optuna +class TrainerHyperParameterMultiObjectOptunaIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + return {} + + def model_init(trial): + if trial is not None: + a = trial.suggest_int("a", -4, 4) + b = trial.suggest_int("b", -4, 4) + else: + a = 0 + b = 0 + config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(config) + + def hp_name(trial): + return MyTrialShortNamer.shortname(trial.params) + + def compute_objective(metrics: dict[str, float]) -> list[float]: + return metrics["eval_loss"], metrics["eval_accuracy"] + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + eval_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=10, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + compute_metrics=AlmostAccuracy(), + ) + trainer.hyperparameter_search( + direction=["minimize", "maximize"], + hp_space=hp_space, + hp_name=hp_name, + n_trials=4, + compute_objective=compute_objective, + ) + + +@require_torch +@require_optuna +class TrainerHyperParameterOptunaIntegrationTestWithFullEval(unittest.TestCase): + def test_hyperparameter_search(self): + def hp_space(trial): + return {} + + def model_init(trial): + if trial is not None: + a = trial.suggest_int("a", -4, 4) + b = trial.suggest_int("b", -4, 4) + else: + a = 0 + b = 0 + config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(config) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + disable_tqdm=True, + model_init=model_init, + fp16_full_eval=True, + ) + trainer.hyperparameter_search( + direction="minimize", + hp_space=hp_space, + n_trials=2, + ) + + +@require_torch +@require_ray +class TrainerHyperParameterRayIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def ray_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + from ray import tune + + return { + "a": tune.randint(-4, 4), + "b": tune.randint(-4, 4), + } + + def model_init(config): + if config is None: + a = 0 + b = 0 + else: + a = config["a"] + b = config["b"] + model_config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(model_config) + + def hp_name(params): + return MyTrialShortNamer.shortname(params) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + eval_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=4, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + ) + trainer.hyperparameter_search( + direction="minimize", hp_space=hp_space, hp_name=hp_name, backend="ray", n_trials=4 + ) + + def test_hyperparameter_search(self): + self.ray_hyperparameter_search() + + def test_hyperparameter_search_ray_client(self): + import ray + from ray.util.client.ray_client_helpers import ray_start_client_server + + with ray_start_client_server(): + assert ray.util.client.ray.is_connected() + self.ray_hyperparameter_search() + + +@slow +@require_torch +@require_sigopt +class TrainerHyperParameterSigOptIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_hyperparameter_search(self): + class MyTrialShortNamer(TrialShortNamer): + DEFAULTS = {"a": 0, "b": 0} + + def hp_space(trial): + return [ + {"bounds": {"min": -4, "max": 4}, "name": "a", "type": "int"}, + {"bounds": {"min": -4, "max": 4}, "name": "b", "type": "int"}, + ] + + def model_init(trial): + if trial is not None: + a = trial.assignments["a"] + b = trial.assignments["b"] + else: + a = 0 + b = 0 + config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(config) + + def hp_name(trial): + return MyTrialShortNamer.shortname(trial.assignments) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + eval_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=4, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + ) + trainer.hyperparameter_search( + direction="minimize", hp_space=hp_space, hp_name=hp_name, backend="sigopt", n_trials=4 + ) + + +optim_test_params = [] +if is_torch_available(): + default_adam_kwargs = { + "betas": (TrainingArguments.adam_beta1, TrainingArguments.adam_beta2), + "eps": TrainingArguments.adam_epsilon, + "lr": TrainingArguments.learning_rate, + } + + default_lion_kwargs = { + "betas": (TrainingArguments.adam_beta1, TrainingArguments.adam_beta2), + "lr": TrainingArguments.learning_rate, + } + + default_ademamix_kwargs = { + "betas": (TrainingArguments.adam_beta1, TrainingArguments.adam_beta2, 0.9999), + "alpha": 5.0, + "eps": TrainingArguments.adam_epsilon, + "lr": TrainingArguments.learning_rate, + } + + default_anyprecision_kwargs = { + "use_kahan_summation": False, + "momentum_dtype": torch.float32, + "variance_dtype": torch.float32, + "compensation_buffer_dtype": torch.bfloat16, + } + + optim_test_params = [ + ( + OptimizerNames.ADAMW_TORCH, + torch.optim.AdamW, + default_adam_kwargs, + ), + ( + OptimizerNames.ADAFACTOR, + transformers.optimization.Adafactor, + { + "scale_parameter": False, + "relative_step": False, + "lr": TrainingArguments.learning_rate, + }, + ), + ] + + if is_apex_available(): + import apex + + optim_test_params.append( + ( + OptimizerNames.ADAMW_APEX_FUSED, + apex.optimizers.FusedAdam, + default_adam_kwargs, + ) + ) + + if is_bitsandbytes_available(): + import bitsandbytes as bnb + + optim_test_params.append( + ( + OptimizerNames.ADAMW_BNB, + bnb.optim.AdamW, + default_adam_kwargs, + ) + ) + + optim_test_params.append( + ( + OptimizerNames.ADAMW_8BIT, + bnb.optim.AdamW, + default_adam_kwargs, + ) + ) + + optim_test_params.append( + ( + OptimizerNames.PAGED_ADAMW, + bnb.optim.AdamW, + default_adam_kwargs, + ) + ) + + optim_test_params.append( + ( + OptimizerNames.PAGED_ADAMW_8BIT, + bnb.optim.AdamW, + default_adam_kwargs, + ) + ) + + optim_test_params.append( + ( + OptimizerNames.LION, + bnb.optim.Lion, + default_lion_kwargs, + ) + ) + + optim_test_params.append( + ( + OptimizerNames.LION_8BIT, + bnb.optim.Lion, + default_lion_kwargs, + ) + ) + + optim_test_params.append( + ( + OptimizerNames.PAGED_LION_8BIT, + bnb.optim.Lion, + default_lion_kwargs, + ) + ) + + if version.parse(importlib.metadata.version("bitsandbytes")) >= version.parse("0.44.0"): + optim_test_params.append( + ( + OptimizerNames.ADEMAMIX, + bnb.optim.AdEMAMix, + default_ademamix_kwargs, + ) + ) + optim_test_params.append( + ( + OptimizerNames.ADEMAMIX_8BIT, + bnb.optim.AdEMAMix, + default_ademamix_kwargs, + ) + ) + optim_test_params.append( + ( + OptimizerNames.PAGED_ADEMAMIX_8BIT, + bnb.optim.AdEMAMix, + default_ademamix_kwargs, + ) + ) + optim_test_params.append( + ( + OptimizerNames.PAGED_ADEMAMIX, + bnb.optim.AdEMAMix, + default_ademamix_kwargs, + ) + ) + + if is_torchdistx_available(): + import torchdistx + + optim_test_params.append( + ( + OptimizerNames.ADAMW_ANYPRECISION, + torchdistx.optimizers.AnyPrecisionAdamW, + dict(default_adam_kwargs, **default_anyprecision_kwargs), + ) + ) + if is_torchao_available(): + from torchao.optim import AdamW4bit, AdamW8bit + + optim_test_params.append( + ( + OptimizerNames.ADAMW_TORCH_4BIT, + AdamW4bit, + default_adam_kwargs, + ) + ) + optim_test_params.append( + ( + TrainingArguments(optim=OptimizerNames.ADAMW_TORCH_8BIT, output_dir="None"), + AdamW8bit, + default_adam_kwargs, + ) + ) + + +@require_torch +class TrainerOptimizerChoiceTest(unittest.TestCase): + def check_optim_and_kwargs(self, training_args: TrainingArguments, expected_cls, expected_kwargs): + actual_cls, optim_kwargs = Trainer.get_optimizer_cls_and_kwargs(training_args) + self.assertEqual(expected_cls, actual_cls) + self.assertIsNotNone(optim_kwargs) + + for p, v in expected_kwargs.items(): + self.assertTrue(p in optim_kwargs) + actual_v = optim_kwargs[p] + self.assertTrue(actual_v == v, f"Failed check for {p}. Expected {v}, but got {actual_v}.") + + @parameterized.expand(optim_test_params, skip_on_empty=True) + def test_optim_supported(self, optim: str, expected_cls, expected_kwargs): + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer(output_dir=tmp_dir, optim=optim) + + # exercises all the valid --optim options + self.check_optim_and_kwargs(trainer.args, expected_cls, expected_kwargs) + trainer.train() + + def test_fused_adam(self): + # Pretend that apex is installed and mock apex.optimizers.FusedAdam exists. + # Trainer.get_optimizer_cls_and_kwargs does not use FusedAdam. It only has to return the + # class given, so mocking apex.optimizers.FusedAdam should be fine for testing and allow + # the test to run without requiring an apex installation. + mock = Mock() + modules = { + "apex": mock, + "apex.optimizers": mock.optimizers, + "apex.optimizers.FusedAdam": mock.optimizers.FusedAdam, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADAMW_APEX_FUSED, output_dir=tmp_dir), + mock.optimizers.FusedAdam, + default_adam_kwargs, + ) + + def test_fused_adam_no_apex(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.ADAMW_APEX_FUSED, output_dir=tmp_dir) + + # Pretend that apex does not exist, even if installed. By setting apex to None, importing + # apex will fail even if apex is installed. + with patch.dict("sys.modules", {"apex.optimizers": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_adam8bit(self): + # Pretend that Bits and Bytes is installed and mock bnb.optim.Adam8bit exists. + # Trainer.get_optimizer_cls_and_kwargs does not use Adam8bit. It only has to return the + # class given, so mocking bnb.optim.Adam8bit should be fine for testing and allow + # the test to run without requiring a bnb installation. + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdamW": mock.optim.AdamW, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADAMW_BNB, output_dir=tmp_dir), + mock.optim.AdamW, + default_adam_kwargs, + ) + + def test_bnb_paged_adam8bit_alias(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdamW": mock.optim.AdamW, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADAMW_8BIT, output_dir=tmp_dir), + mock.optim.AdamW, + default_adam_kwargs, + ) + + def test_bnb_paged_adam(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdamW": mock.optim.AdamW, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_ADAMW, output_dir=tmp_dir), + mock.optim.AdamW, + default_adam_kwargs, + ) + + def test_bnb_paged_adam8bit(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdamW": mock.optim.AdamW, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_ADAMW_8BIT, output_dir=tmp_dir), + mock.optim.AdamW, + default_adam_kwargs, + ) + + def test_bnb_ademamix(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdEMAMix": mock.optim.AdEMAMix, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADEMAMIX, output_dir=tmp_dir), + mock.optim.AdEMAMix, + default_ademamix_kwargs, + ) + + def test_bnb_ademamix8bit(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdEMAMix": mock.optim.AdEMAMix, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADEMAMIX_8BIT, output_dir=tmp_dir), + mock.optim.AdEMAMix, + default_ademamix_kwargs, + ) + + def test_bnb_paged_ademamix(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdEMAMix": mock.optim.AdEMAMix, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_ADEMAMIX, output_dir=tmp_dir), + mock.optim.AdEMAMix, + default_ademamix_kwargs, + ) + + def test_bnb_paged_ademamix8bit(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.AdEMAMix": mock.optim.AdEMAMix, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_ADEMAMIX_8BIT, output_dir=tmp_dir), + mock.optim.AdEMAMix, + default_ademamix_kwargs, + ) + + def test_bnb_lion(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.Lion": mock.optim.Lion, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.LION, output_dir=tmp_dir), + mock.optim.Lion, + default_lion_kwargs, + ) + + def test_bnb_lion8bit(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.Lion": mock.optim.Lion, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.LION_8BIT, output_dir=tmp_dir), + mock.optim.Lion, + default_lion_kwargs, + ) + + def test_bnb_paged_lion8bit(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.Lion": mock.optim.Lion, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_LION_8BIT, output_dir=tmp_dir), + mock.optim.Lion, + default_lion_kwargs, + ) + + def test_bnb_paged_lion(self): + mock = Mock() + modules = { + "bitsandbytes": mock, + "bitsandbytes.optim": mock.optim, + "bitsandbytes.optim.Lion": mock.optim.Lion, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.PAGED_LION, output_dir=tmp_dir), + mock.optim.Lion, + default_lion_kwargs, + ) + + def test_bnb_adam8bit_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.ADAMW_BNB, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_adam_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.PAGED_ADAMW, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_adam8bit_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.PAGED_ADAMW_8BIT, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_ademamix_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.ADEMAMIX, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_ademamix8bit_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.ADEMAMIX_8BIT, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_ademamix_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.PAGED_ADEMAMIX, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_ademamix8bit_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.PAGED_ADEMAMIX_8BIT, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_lion_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.PAGED_LION, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_bnb_paged_lion8bit_no_bnb(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.PAGED_LION_8BIT, output_dir=tmp_dir) + + # Pretend that bnb does not exist, even if installed. By setting bnb to None, importing + # bnb will fail even if `bitsandbytes` is installed. + with patch.dict("sys.modules", {"bitsandbytes.optim": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + def test_anyprecision_adamw(self): + # Pretend that torchdistx is installed and mock torchdistx.optimizers.AnyPrecisionAdamW exists. + # Trainer.get_optimizer_cls_and_kwargs does not use AnyPrecisioinAdamW. It only has to return the + # class given, so mocking torchdistx.optimizers.AnyPrecisionAdamW should be fine for testing and allow + # the test to run without requiring a bnb installation. + mock = Mock() + modules = { + "torchdistx": mock, + "torchdistx.optimizers": mock.optimizers, + "torchdistx.optimizers.AnyPrecisionAdamW.": mock.optimizers.AnyPrecisionAdamW, + } + with tempfile.TemporaryDirectory() as tmp_dir: + with patch.dict("sys.modules", modules): + self.check_optim_and_kwargs( + TrainingArguments(optim=OptimizerNames.ADAMW_ANYPRECISION, output_dir=tmp_dir), + mock.optimizers.AnyPrecisionAdamW, + dict(default_adam_kwargs, **default_anyprecision_kwargs), + ) + + def test_no_torchdistx_anyprecision_adamw(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments(optim=OptimizerNames.ADAMW_ANYPRECISION, output_dir=tmp_dir) + + # Pretend that torchdistx does not exist, even if installed. By setting torchdistx to None, importing + # torchdistx.optimizers will fail even if torchdistx is installed. + with patch.dict("sys.modules", {"torchdistx.optimizers": None}): + with self.assertRaises(ValueError): + Trainer.get_optimizer_cls_and_kwargs(args) + + +@require_torch +@require_wandb +class TrainerHyperParameterWandbIntegrationTest(unittest.TestCase): + def setUp(self): + args = TrainingArguments("..") + self.n_epochs = args.num_train_epochs + self.batch_size = args.train_batch_size + + def test_hyperparameter_search(self): + def hp_space(trial): + return { + "method": "random", + "metric": {}, + "parameters": { + "a": {"distribution": "uniform", "min": 1e-6, "max": 1e-4}, + "b": {"distribution": "int_uniform", "min": 1, "max": 6}, + }, + } + + def model_init(config): + if config is None: + a = 0 + b = 0 + else: + a = config["a"] + b = config["b"] + model_config = RegressionModelConfig(a=a, b=b, double_output=False) + + return RegressionPreTrainedModel(model_config) + + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = get_regression_trainer( + output_dir=tmp_dir, + learning_rate=0.1, + logging_steps=1, + eval_strategy=IntervalStrategy.EPOCH, + save_strategy=IntervalStrategy.EPOCH, + num_train_epochs=4, + disable_tqdm=True, + load_best_model_at_end=True, + logging_dir="runs", + run_name="test", + model_init=model_init, + ) + sweep_kwargs = { + "direction": "minimize", + "hp_space": hp_space, + "backend": "wandb", + "n_trials": 4, + } + best_run = trainer.hyperparameter_search(**sweep_kwargs) + + self.assertIsNotNone(best_run.run_id) + self.assertIsNotNone(best_run.run_summary) + hp_keys = set(best_run.hyperparameters.keys()) + self.assertSetEqual(hp_keys, {"a", "b", "assignments", "metric"}) + + # pretend restarting the process purged the environ + import os + + del os.environ["WANDB_ENTITY"] + del os.environ["WANDB_PROJECT"] + sweep_kwargs["sweep_id"] = best_run.run_summary + updated_best_run = trainer.hyperparameter_search(**sweep_kwargs) + + self.assertIsNotNone(updated_best_run.run_id) + self.assertEqual(updated_best_run.run_summary, best_run.run_summary) + updated_hp_keys = set(updated_best_run.hyperparameters.keys()) + self.assertSetEqual(updated_hp_keys, {"a", "b", "assignments", "metric"}) + + +class HyperParameterSearchBackendsTest(unittest.TestCase): + def test_hyperparameter_search_backends(self): + self.assertEqual( + list(ALL_HYPERPARAMETER_SEARCH_BACKENDS.keys()), + list(HPSearchBackend), + ) + + +@require_torch +class OptimizerAndModelInspectionTest(unittest.TestCase): + def test_get_num_trainable_parameters(self): + model = nn.Sequential(nn.Linear(128, 64), nn.Linear(64, 32)) + # in_features * out_features + bias + layer_1 = 128 * 64 + 64 + layer_2 = 64 * 32 + 32 + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = Trainer(model=model, args=TrainingArguments(output_dir=tmp_dir, report_to="none")) + self.assertEqual(trainer.get_num_trainable_parameters(), layer_1 + layer_2) + # Freeze the last layer + for param in model[-1].parameters(): + param.requires_grad = False + self.assertEqual(trainer.get_num_trainable_parameters(), layer_1) + + def test_get_learning_rates(self): + model = nn.Sequential(nn.Linear(128, 64)) + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = Trainer(model=model, args=TrainingArguments(output_dir=tmp_dir, report_to="none")) + with self.assertRaises(ValueError): + trainer.get_learning_rates() + trainer.create_optimizer() + self.assertEqual(trainer.get_learning_rates(), [5e-05, 5e-05]) + + def test_get_optimizer_group(self): + model = nn.Sequential(nn.Linear(128, 64)) + with tempfile.TemporaryDirectory() as tmp_dir: + trainer = Trainer(model=model, args=TrainingArguments(output_dir=tmp_dir, report_to="none")) + # ValueError is raised if optimizer is None + with self.assertRaises(ValueError): + trainer.get_optimizer_group() + trainer.create_optimizer() + # Get groups + num_groups = len(trainer.get_optimizer_group()) + self.assertEqual(num_groups, 2) + # Get group of parameter + param = next(model.parameters()) + group = trainer.get_optimizer_group(param) + self.assertIn(param, group["params"]) + + @require_bitsandbytes + def test_bnb_8bit_optimizer_skip_embedding(self): + model = BasicTextGenerationModel(8, 4) + with tempfile.TemporaryDirectory() as tmp_dir: + for name_optim in ["rmsprop_bnb_8bit", "adamw_8bit"]: + args = TrainingArguments( + output_dir=tmp_dir, + report_to="none", + optim=name_optim, + ) + trainer = Trainer(model=model, args=args) + optimizer = trainer.create_optimizer() + modules = optimizer.mng.module_weight_config_triple + self.assertNotEqual(len(modules), 0) + module, name, config = modules[0] + self.assertIsInstance(module, torch.nn.Embedding) + self.assertEqual(name, "weight") + self.assertDictEqual(config, {"optim_bits": 32}) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_callback.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_callback.py new file mode 100644 index 0000000000000000000000000000000000000000..996cd1ecb9a230abebab1e8be347c4ca1826c24d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_callback.py @@ -0,0 +1,445 @@ +# 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. + + +import os +import shutil +import tempfile +import unittest +from unittest.mock import patch + +from transformers import ( + DefaultFlowCallback, + EarlyStoppingCallback, + IntervalStrategy, + PrinterCallback, + ProgressCallback, + Trainer, + TrainerCallback, + TrainerState, + TrainingArguments, + is_torch_available, +) +from transformers.testing_utils import require_torch +from transformers.trainer_callback import ExportableState + + +if is_torch_available(): + from transformers.trainer import DEFAULT_CALLBACKS, TRAINER_STATE_NAME + + from .test_trainer import RegressionDataset, RegressionModelConfig, RegressionPreTrainedModel + + +class MyTestExportableCallback(TrainerCallback, ExportableState): + def __init__(self, my_test_state="test"): + self.my_test_state = my_test_state + + def state(self): + return { + "args": { + "my_test_state": self.my_test_state, + }, + } + + +class MyTestTrainerCallback(TrainerCallback): + "A callback that registers the events that goes through." + + def __init__(self, my_test_state="test"): + self.events = [] + self.my_test_state = my_test_state + + def on_init_end(self, args, state, control, **kwargs): + self.events.append("on_init_end") + + def on_train_begin(self, args, state, control, **kwargs): + self.events.append("on_train_begin") + + def on_train_end(self, args, state, control, **kwargs): + self.events.append("on_train_end") + + def on_epoch_begin(self, args, state, control, **kwargs): + self.events.append("on_epoch_begin") + + def on_epoch_end(self, args, state, control, **kwargs): + self.events.append("on_epoch_end") + + def on_step_begin(self, args, state, control, **kwargs): + self.events.append("on_step_begin") + + def on_pre_optimizer_step(self, args, state, control, **kwargs): + self.events.append("on_pre_optimizer_step") + + def on_optimizer_step(self, args, state, control, **kwargs): + self.events.append("on_optimizer_step") + + def on_step_end(self, args, state, control, **kwargs): + self.events.append("on_step_end") + + def on_evaluate(self, args, state, control, **kwargs): + self.events.append("on_evaluate") + + def on_predict(self, args, state, control, **kwargs): + self.events.append("on_predict") + + def on_save(self, args, state, control, **kwargs): + self.events.append("on_save") + + def on_log(self, args, state, control, **kwargs): + self.events.append("on_log") + + def on_prediction_step(self, args, state, control, **kwargs): + self.events.append("on_prediction_step") + + +@require_torch +class TrainerCallbackTest(unittest.TestCase): + def setUp(self): + self.output_dir = tempfile.mkdtemp() + + def tearDown(self): + shutil.rmtree(self.output_dir) + + def get_trainer(self, a=0, b=0, train_len=64, eval_len=64, callbacks=None, disable_tqdm=False, **kwargs): + # disable_tqdm in TrainingArguments has a flaky default since it depends on the level of logging. We make sure + # its set to False since the tests later on depend on its value. + train_dataset = RegressionDataset(length=train_len) + eval_dataset = RegressionDataset(length=eval_len) + config = RegressionModelConfig(a=a, b=b) + model = RegressionPreTrainedModel(config) + + args = TrainingArguments(self.output_dir, disable_tqdm=disable_tqdm, report_to=[], **kwargs) + return Trainer( + model, + args, + train_dataset=train_dataset, + eval_dataset=eval_dataset, + callbacks=callbacks, + ) + + def check_callbacks_equality(self, cbs1, cbs2): + self.assertEqual(len(cbs1), len(cbs2)) + + # Order doesn't matter + cbs1 = sorted(cbs1, key=lambda cb: cb.__name__ if isinstance(cb, type) else cb.__class__.__name__) + cbs2 = sorted(cbs2, key=lambda cb: cb.__name__ if isinstance(cb, type) else cb.__class__.__name__) + + for cb1, cb2 in zip(cbs1, cbs2): + if isinstance(cb1, type) and isinstance(cb2, type): + self.assertEqual(cb1, cb2) + elif isinstance(cb1, type) and not isinstance(cb2, type): + self.assertEqual(cb1, cb2.__class__) + elif not isinstance(cb1, type) and isinstance(cb2, type): + self.assertEqual(cb1.__class__, cb2) + else: + self.assertEqual(cb1, cb2) + + def get_expected_events(self, trainer): + expected_events = ["on_init_end", "on_train_begin"] + step = 0 + train_dl_len = len(trainer.get_eval_dataloader()) + evaluation_events = ["on_prediction_step"] * len(trainer.get_eval_dataloader()) + ["on_log", "on_evaluate"] + for _ in range(trainer.state.num_train_epochs): + expected_events.append("on_epoch_begin") + for _ in range(train_dl_len): + step += 1 + expected_events += ["on_step_begin", "on_pre_optimizer_step", "on_optimizer_step", "on_step_end"] + if step % trainer.args.logging_steps == 0: + expected_events.append("on_log") + if trainer.args.eval_strategy == IntervalStrategy.STEPS and step % trainer.args.eval_steps == 0: + expected_events += evaluation_events.copy() + if step % trainer.args.save_steps == 0 or step == trainer.state.max_steps: + expected_events.append("on_save") + expected_events.append("on_epoch_end") + if trainer.args.eval_strategy == IntervalStrategy.EPOCH: + expected_events += evaluation_events.copy() + expected_events += ["on_log", "on_train_end"] + return expected_events + + def test_init_callback(self): + trainer = self.get_trainer() + expected_callbacks = DEFAULT_CALLBACKS.copy() + [ProgressCallback] + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + # Callbacks passed at init are added to the default callbacks + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback]) + expected_callbacks.append(MyTestTrainerCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + # TrainingArguments.disable_tqdm controls if use ProgressCallback or PrinterCallback + trainer = self.get_trainer(disable_tqdm=True) + expected_callbacks = DEFAULT_CALLBACKS.copy() + [PrinterCallback] + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + def test_add_remove_callback(self): + expected_callbacks = DEFAULT_CALLBACKS.copy() + [ProgressCallback] + trainer = self.get_trainer() + + # We can add, pop, or remove by class name + trainer.remove_callback(DefaultFlowCallback) + expected_callbacks.remove(DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + trainer = self.get_trainer() + cb = trainer.pop_callback(DefaultFlowCallback) + self.assertEqual(cb.__class__, DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + trainer.add_callback(DefaultFlowCallback) + expected_callbacks.insert(0, DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + # We can also add, pop, or remove by instance + trainer = self.get_trainer() + cb = trainer.callback_handler.callbacks[0] + trainer.remove_callback(cb) + expected_callbacks.remove(DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + trainer = self.get_trainer() + cb1 = trainer.callback_handler.callbacks[0] + cb2 = trainer.pop_callback(cb1) + self.assertEqual(cb1, cb2) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + trainer.add_callback(cb1) + expected_callbacks.insert(0, DefaultFlowCallback) + self.check_callbacks_equality(trainer.callback_handler.callbacks, expected_callbacks) + + def test_event_flow(self): + import warnings + + # XXX: for now ignore scatter_gather warnings in this test since it's not relevant to what's being tested + with warnings.catch_warnings(): + warnings.simplefilter(action="ignore", category=UserWarning) + + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback]) + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + # Independent log/save/eval + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback], logging_steps=5) + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback], save_steps=5) + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback], eval_steps=5, eval_strategy="steps") + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + trainer = self.get_trainer(callbacks=[MyTestTrainerCallback], eval_strategy="epoch") + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + # A bit of everything + trainer = self.get_trainer( + callbacks=[MyTestTrainerCallback], + logging_steps=3, + save_steps=10, + eval_steps=5, + eval_strategy="steps", + ) + trainer.train() + events = trainer.callback_handler.callbacks[-2].events + self.assertEqual(events, self.get_expected_events(trainer)) + + # warning should be emitted for duplicated callbacks + with patch("transformers.trainer_callback.logger.warning") as warn_mock: + trainer = self.get_trainer( + callbacks=[MyTestTrainerCallback, MyTestTrainerCallback], + ) + assert str(MyTestTrainerCallback) in warn_mock.call_args[0][0] + + def test_stateful_callbacks(self): + # Use something with non-defaults + cb = EarlyStoppingCallback(early_stopping_patience=5, early_stopping_threshold=0.2) + trainer = self.get_trainer( + callbacks=[cb], + load_best_model_at_end=True, + save_strategy="steps", + eval_strategy="steps", + save_steps=2, + eval_steps=2, + max_steps=2, + ) + trainer.train() + + # Create a new trainer with defaults + trainer = self.get_trainer( + callbacks=[EarlyStoppingCallback()], + load_best_model_at_end=True, + save_strategy="steps", + eval_strategy="steps", + save_steps=2, + eval_steps=2, + max_steps=2, + restore_callback_states_from_checkpoint=True, + ) + # Load it back in and verify values + checkpoint = os.path.join(self.output_dir, "checkpoint-2") + trainer.train(resume_from_checkpoint=checkpoint) + cb = [ + callback for callback in trainer.callback_handler.callbacks if isinstance(callback, EarlyStoppingCallback) + ][0] + assert cb.early_stopping_patience == 5 + assert cb.early_stopping_threshold == 0.2 + + def test_stateful_mixed_callbacks(self): + # Use two callbacks, one stateful one not + # Use something with non-defaults + cbs = [ + MyTestTrainerCallback(my_test_state="another value"), + EarlyStoppingCallback(early_stopping_patience=5, early_stopping_threshold=0.2), + ] + trainer = self.get_trainer( + callbacks=cbs, + load_best_model_at_end=True, + save_strategy="steps", + eval_strategy="steps", + save_steps=2, + eval_steps=2, + max_steps=2, + ) + trainer.train() + + # Create a new trainer with defaults + trainer = self.get_trainer( + callbacks=[EarlyStoppingCallback(), MyTestTrainerCallback()], + load_best_model_at_end=True, + save_strategy="steps", + eval_strategy="steps", + save_steps=2, + eval_steps=2, + max_steps=2, + restore_callback_states_from_checkpoint=True, + ) + # Load it back in and verify values + checkpoint = os.path.join(self.output_dir, "checkpoint-2") + trainer.train(resume_from_checkpoint=checkpoint) + cbs = [ + callback + for callback in trainer.callback_handler.callbacks + if isinstance(callback, (EarlyStoppingCallback, MyTestTrainerCallback)) + ] + assert len(cbs) == 2 + my_test, early_stopping = cbs + assert early_stopping.early_stopping_patience == 5 + assert early_stopping.early_stopping_threshold == 0.2 + assert my_test.my_test_state == "test" + + def test_stateful_duplicate_callbacks(self): + # Use something with non-defaults + cbs = [MyTestExportableCallback("first"), MyTestExportableCallback("second")] + trainer = self.get_trainer( + callbacks=cbs, + load_best_model_at_end=True, + save_strategy="steps", + eval_strategy="steps", + save_steps=2, + eval_steps=2, + max_steps=2, + ) + trainer.train() + + # Create a new trainer with defaults + trainer = self.get_trainer( + callbacks=[MyTestExportableCallback(), MyTestExportableCallback()], + load_best_model_at_end=True, + save_strategy="steps", + eval_strategy="steps", + save_steps=2, + eval_steps=2, + max_steps=2, + restore_callback_states_from_checkpoint=True, + ) + # Load it back in and verify values + checkpoint = os.path.join(self.output_dir, "checkpoint-2") + trainer.train(resume_from_checkpoint=checkpoint) + cbs = [ + callback + for callback in trainer.callback_handler.callbacks + if isinstance(callback, MyTestExportableCallback) + ] + assert len(cbs) == 2 + assert cbs[0].my_test_state == "first" + assert cbs[1].my_test_state == "second" + + def test_missing_stateful_callback(self): + cb = EarlyStoppingCallback() + trainer = self.get_trainer( + callbacks=[cb], + load_best_model_at_end=True, + save_strategy="steps", + eval_strategy="steps", + save_steps=2, + eval_steps=2, + max_steps=2, + ) + trainer.train() + + # Create a new trainer with defaults + trainer = self.get_trainer( + save_strategy="steps", + eval_strategy="steps", + save_steps=2, + eval_steps=2, + max_steps=2, + restore_callback_states_from_checkpoint=True, + ) + # Load it back in and verify values + checkpoint = os.path.join(self.output_dir, "checkpoint-2") + # warning should be emitted for not-present callbacks + with patch("transformers.trainer.logger.warning") as warn_mock: + trainer.train(resume_from_checkpoint=checkpoint) + assert "EarlyStoppingCallback" in warn_mock.call_args[0][0] + + def test_stateful_control(self): + trainer = self.get_trainer( + max_steps=2, + save_strategy="steps", + save_steps=2, + ) + trainer.train() + # Load it back in and verify values + trainer = self.get_trainer(max_steps=2, restore_callback_states_from_checkpoint=True) + checkpoint = os.path.join(self.output_dir, "checkpoint-2") + trainer.state = TrainerState.load_from_json(os.path.join(checkpoint, TRAINER_STATE_NAME)) + trainer._load_callback_state() + assert trainer.control.should_training_stop + + def test_no_duplicate_save_on_epoch_save_strategy(self): + times_saved = 0 + + class OnEndCallback(TrainerCallback): + def on_step_end(self, args: TrainingArguments, state: TrainerState, control, **kwargs): + nonlocal times_saved + if control.should_save: + times_saved += 1 + + def on_epoch_end(self, args: TrainingArguments, state: TrainerState, control, **kwargs): + nonlocal times_saved + if control.should_save: + times_saved += 1 + + trainer = self.get_trainer(max_steps=2, save_strategy="epoch", callbacks=[OnEndCallback]) + trainer.train() + assert times_saved == 1 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..54568caac37a9e55ba360cb0560af5c89e128067 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed.py @@ -0,0 +1,207 @@ +# 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. + + +import numpy as np + +from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available +from transformers.testing_utils import ( + TestCasePlus, + backend_device_count, + execute_subprocess_async, + get_torch_dist_unique_port, + require_torch_multi_accelerator, + run_first, + torch_device, +) +from transformers.training_args import ParallelMode +from transformers.utils import logging + + +logger = logging.get_logger(__name__) + + +if is_torch_available(): + import torch + from torch import nn + from torch.utils.data import Dataset, IterableDataset + + from transformers import Trainer + + class DummyDataset(Dataset): + def __init__(self, length: int = 101): + self.length = length + + def __len__(self): + return self.length + + def __getitem__(self, i) -> int: + return i + + class DummyDataCollator: + def __call__(self, features): + return {"input_ids": torch.tensor(features), "labels": torch.tensor(features)} + + class DummyModel(nn.Module): + def __init__(self): + super().__init__() + # Add some (unused) params otherwise DDP will complain. + self.fc = nn.Linear(120, 80) + + def forward(self, input_ids, labels=None): + if labels is not None: + return torch.tensor(0.0, device=input_ids.device), input_ids + else: + return input_ids + + class RegressionModel(nn.Module): + def __init__(self, a=0, b=0, double_output=False): + super().__init__() + self.a = nn.Parameter(torch.tensor(a).float()) + self.b = nn.Parameter(torch.tensor(b).float()) + self.double_output = double_output + self.config = None + + def forward(self, input_x, labels=None, **kwargs): + y = input_x * self.a + self.b + if labels is None: + return (y, y) if self.double_output else (y,) + loss = nn.functional.mse_loss(y, labels) + return (loss, y, y) if self.double_output else (loss, y) + + class SampleIterableDataset(IterableDataset): + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + self.dataset = RegressionDataset(a=a, b=b, length=length, seed=seed, label_names=label_names) + + def __iter__(self): + for i in range(len(self.dataset)): + yield self.dataset[i] + + class FiniteIterableDataset(SampleIterableDataset): + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + super().__init__(a, b, length, seed, label_names) + self.current_sample = 0 + + def __iter__(self): + while self.current_sample < len(self.dataset): + yield self.dataset[self.current_sample] + self.current_sample += 1 + + class RegressionDataset: + def __init__(self, a=2, b=3, length=64, seed=42, label_names=None): + np.random.seed(seed) + self.label_names = ["labels"] if label_names is None else label_names + self.length = length + self.x = np.random.normal(size=(length,)).astype(np.float32) + self.ys = [a * self.x + b + np.random.normal(scale=0.1, size=(length,)) for _ in self.label_names] + self.ys = [y.astype(np.float32) for y in self.ys] + + def __len__(self): + return self.length + + def __getitem__(self, i): + result = {name: y[i] for name, y in zip(self.label_names, self.ys)} + result["input_x"] = self.x[i] + return result + + +class TestTrainerDistributed(TestCasePlus): + @run_first + @require_torch_multi_accelerator + def test_trainer(self): + distributed_args = f"""--nproc_per_node={backend_device_count(torch_device)} + --master_port={get_torch_dist_unique_port()} + {self.test_file_dir}/test_trainer_distributed.py + """.split() + output_dir = self.get_auto_remove_tmp_dir() + args = f"--output_dir {output_dir} --report_to none".split() + cmd = ["torchrun"] + distributed_args + args + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +if __name__ == "__main__": + # The script below is meant to be run under torch.distributed, on a machine with multiple GPUs: + # + # PYTHONPATH="src" python -m torch.distributed.run --nproc_per_node 2 --output_dir output_dir ./tests/test_trainer_distributed.py + + parser = HfArgumentParser((TrainingArguments,)) + training_args = parser.parse_args_into_dataclasses()[0] + + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}, " + f"distributed training: {training_args.parallel_mode != ParallelMode.NOT_DISTRIBUTED}" + ) + + # Essentially, what we want to verify in the distributed case is that we get all samples back, + # in the right order. (this is crucial for prediction for instance) + for dataset_length in [101, 40, 7]: + dataset = DummyDataset(dataset_length) + + def compute_metrics(p: EvalPrediction) -> dict: + sequential = list(range(len(dataset))) + success = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential + if not success and training_args.local_rank == 0: + logger.warning( + "Predictions and/or labels do not match expected results:\n - predictions: " + f"{p.predictions.tolist()}\n - labels: {p.label_ids.tolist()}\n - expected: {sequential}" + ) + return {"success": success} + + trainer = Trainer( + model=DummyModel(), + args=training_args, + data_collator=DummyDataCollator(), + eval_dataset=dataset, + compute_metrics=compute_metrics, + ) + metrics = trainer.evaluate() + logger.info(metrics) + if metrics["eval_success"] is not True: + logger.error(metrics) + exit(1) + + p = trainer.predict(dataset) + logger.info(p.metrics) + if p.metrics["test_success"] is not True: + logger.error(p.metrics) + exit(1) + + trainer.args.eval_accumulation_steps = 2 + + metrics = trainer.evaluate() + logger.info(metrics) + if metrics["eval_success"] is not True: + logger.error(metrics) + exit(1) + + p = trainer.predict(dataset) + logger.info(p.metrics) + if p.metrics["test_success"] is not True: + logger.error(p.metrics) + exit(1) + + trainer.args.eval_accumulation_steps = None + + # Check that `dispatch_batches=False` will work on a finite iterable dataset + + train_dataset = FiniteIterableDataset(label_names=["labels", "extra"], length=1) + + model = RegressionModel() + training_args.per_device_train_batch_size = 1 + training_args.max_steps = 1 + training_args.accelerator_config.dispatch_batches = False + + trainer = Trainer(model, training_args, train_dataset=train_dataset) + trainer.train() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed_loss.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed_loss.py new file mode 100644 index 0000000000000000000000000000000000000000..93cc042fe6dcc724e747be25c30032e5a92dabc2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed_loss.py @@ -0,0 +1,107 @@ +import json + +import datasets + +from tests.trainer.test_trainer import StoreLossCallback +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + DataCollatorForLanguageModeling, + HfArgumentParser, + Trainer, + TrainingArguments, + set_seed, +) +from transformers.testing_utils import ( + TestCasePlus, + backend_device_count, + execute_subprocess_async, + get_torch_dist_unique_port, + require_torch_multi_accelerator, + run_first, + torch_device, +) + + +class TestTrainerDistributedLoss(TestCasePlus): + @run_first + @require_torch_multi_accelerator + def test_trainer(self): + device_count = backend_device_count(torch_device) + min_bs = 2 + output_dir = self.get_auto_remove_tmp_dir() + for gpu_num, enable, bs, name in ( + (1, True, min_bs * device_count, "base"), + (device_count, False, min_bs, "broken"), + (device_count, True, min_bs, "fixed"), + ): + distributed_args = f"""--nproc_per_node={gpu_num} + --master_port={get_torch_dist_unique_port()} + {self.test_file_dir}/test_trainer_distributed_loss.py + """.split() + args = f"--output_dir {output_dir}/{name} --per_device_train_batch_size {bs} --average_tokens_across_devices {enable}".split() + cmd = ["torchrun"] + distributed_args + args + execute_subprocess_async(cmd, env=self.get_env()) + with open(f"{output_dir}/base_losses.json") as f: + base_loss = json.load(f) + with open(f"{output_dir}/broken_losses.json") as f: + broken_loss = json.load(f) + with open(f"{output_dir}/fixed_losses.json") as f: + fixed_loss = json.load(f) + + broken_diff = [abs(base_loss[i] - broken_loss[i]) for i in range(len(base_loss))] + fixed_diff = [abs(base_loss[i] - fixed_loss[i]) for i in range(len(base_loss))] + sum_base = sum(base_loss) + sum_broken = sum(broken_loss) + relative_broken = abs(sum_base - sum_broken) / max(sum_base, sum_broken) + + # the gap may be smaller for other models, but it still ok. + self.assertGreater(max(broken_diff), 0.5) + self.assertLess(max(fixed_diff), 0.005) + self.assertLess(relative_broken, 0.1) + + +def run_distributed_training(training_args): + set_seed(42) + model_name = "nickypro/tinyllama-15M" + dataset_name = "wikitext" + dataset_config = "wikitext-2-raw-v1" + dataset = datasets.load_dataset(dataset_name, dataset_config, split="train[:100]") + tokenizer = AutoTokenizer.from_pretrained(model_name) + tokenizer.pad_token = tokenizer.eos_token + + def tokenize_function(examples): + return tokenizer(examples["text"], max_length=16, padding="max_length", truncation=True) + + tokenized_dataset = dataset.map(tokenize_function, batched=True) + + tokenizer.pad_token = tokenizer.eos_token + data_collator = DataCollatorForLanguageModeling(tokenizer=tokenizer, mlm=False) + + model = AutoModelForCausalLM.from_pretrained(model_name) + + loss_callback = StoreLossCallback() + + training_args.logging_steps = 1 + training_args.max_steps = 10 + training_args.learning_rate = 3e-4 + training_args.disable_tqdm = True + training_args.dataloader_drop_last = True + training_args.report_to = [] + + trainer = Trainer( + model, + training_args, + train_dataset=tokenized_dataset, + callbacks=[loss_callback], + data_collator=data_collator, + ) + trainer.train() + with open(training_args.output_dir + "_losses.json", "w") as f: + json.dump(loss_callback.losses, f) + + +if __name__ == "__main__": + parser = HfArgumentParser((TrainingArguments,)) + training_args = parser.parse_args_into_dataclasses()[0] + run_distributed_training(training_args) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed_worker_seed.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed_worker_seed.py new file mode 100644 index 0000000000000000000000000000000000000000..ded03826771fa1530aa0e8b46044ee14c507ab50 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_distributed_worker_seed.py @@ -0,0 +1,93 @@ +import random + +import numpy as np +import torch +import torch.distributed as dist +import torch.nn as nn +from torch.utils.data import Dataset + +from transformers import ( + HfArgumentParser, + Trainer, + TrainingArguments, + set_seed, +) +from transformers.testing_utils import ( + TestCasePlus, + backend_device_count, + execute_subprocess_async, + get_torch_dist_unique_port, + require_torch_multi_accelerator, + run_first, + torch_device, +) + + +def gather_from_all_gpus(tensor, world_size): + # Prepare a list to gather tensors from all processes + gather_list = [torch.zeros_like(tensor) for _ in range(world_size)] + dist.all_gather(gather_list, tensor) + return gather_list # List of tensors from all ranks + + +class DummyDataset(Dataset): + def __init__(self): + self.length = 64 + + def __len__(self): + return self.length + + def __getitem__(self, i) -> int: + x = random.random() + y = np.random.random() + z = torch.rand([]).item() + return {"x": torch.tensor([x, y, z])} + + +class DummyModel(nn.Module): + def __init__(self): + super().__init__() + self.fc = nn.Linear(3, 1) + + def forward(self, x): + local_tensor = torch.tensor(x, device=torch_device) + gathered = gather_from_all_gpus(local_tensor, dist.get_world_size()) + assert not all(torch.allclose(t, gathered[0]) for t in gathered[1:]) + y = self.fc(x) + return (y.mean(), y) + + +class TestTrainerDistributedWorkerSeed(TestCasePlus): + @run_first + @require_torch_multi_accelerator + def test_trainer(self): + device_count = backend_device_count(torch_device) + output_dir = self.get_auto_remove_tmp_dir() + distributed_args = f"""--nproc_per_node={device_count} + --master_port={get_torch_dist_unique_port()} + {self.test_file_dir}/test_trainer_distributed_worker_seed.py + """.split() + args = f"--output_dir {output_dir}".split() + cmd = ["torchrun"] + distributed_args + args + execute_subprocess_async(cmd, env=self.get_env()) + + +def run_distributed_training(training_args): + set_seed(42) + model = DummyModel() + dataset = DummyDataset() + training_args.max_steps = 10 + # dataloader_num_workers must be > 0 to enable worker_init_fn + training_args.dataloader_num_workers = 2 + trainer = Trainer( + model, + training_args, + train_dataset=dataset, + ) + trainer.train() + + +if __name__ == "__main__": + parser = HfArgumentParser((TrainingArguments,)) + training_args = parser.parse_args_into_dataclasses()[0] + run_distributed_training(training_args) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_fsdp.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_fsdp.py new file mode 100644 index 0000000000000000000000000000000000000000..1e30f9f4549d684cecd84b55eca8bea82a16534b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_fsdp.py @@ -0,0 +1,203 @@ +# 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. + + +from transformers import is_torch_available +from transformers.testing_utils import ( + TestCasePlus, + backend_device_count, + execute_subprocess_async, + get_torch_dist_unique_port, + require_accelerate, + require_fp8, + require_torch_multi_accelerator, + run_first, + torch_device, +) + + +if is_torch_available(): + import torch + import torch.distributed + import torch.utils.data + + from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + DataCollatorForSeq2Seq, + EvalPrediction, + GenerationConfig, + HfArgumentParser, + PreTrainedTokenizerBase, + Seq2SeqTrainer, + Seq2SeqTrainingArguments, + ) + + class DummyTextDataset(torch.utils.data.Dataset[str]): + def __init__(self, tokenizer: PreTrainedTokenizerBase) -> None: + data = 4 * [ + "Hello world!", + "The quick brown fox jumps over the lazy dog.", + ] + self.data = [ + {k: v.squeeze(0) for k, v in tokenizer(item, return_tensors="pt", return_attention_mask=True).items()} + for item in data + ] + for item in self.data: + item["labels"] = item["input_ids"] + + def __len__(self) -> int: + return len(self.data) + + def __getitem__(self, i: int) -> str: + return self.data[i] + + +class TestFSDPTrainer(TestCasePlus): + @require_torch_multi_accelerator + @require_accelerate + @run_first + def test_trainer(self): + output_dir = self.get_auto_remove_tmp_dir() + cmd = [ + "accelerate", + "launch", + "--use_fsdp", + "--main_process_port", + f"{get_torch_dist_unique_port()}", + "--num_processes", + f"{backend_device_count(torch_device)}", + "--fsdp_transformer_layer_cls_to_wrap", + "GPT2Block", + f"{self.test_file_dir}/test_trainer_fsdp.py", + "--output_dir", + f"{output_dir}", + "--report_to", + "none", + ] + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +class TestFSDPTrainerFP8(TestCasePlus): + @require_torch_multi_accelerator + @require_accelerate + @require_fp8 + @run_first + def test_trainer(self): + output_dir = self.get_auto_remove_tmp_dir() + cmd = [ + "accelerate", + "launch", + "--use_fsdp", + "--main_process_port", + f"{get_torch_dist_unique_port()}", + "--num_processes", + f"{backend_device_count(torch_device)}", + "--mixed_precision", + "fp8", + "--fsdp_transformer_layer_cls_to_wrap", + "GPT2Block", + f"{self.test_file_dir}/test_trainer_fsdp.py", + "--output_dir", + f"{output_dir}", + "--report_to", + "none", + ] + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +class TestFSDPTrainerWrap(TestCasePlus): + @require_torch_multi_accelerator + @require_accelerate + @run_first + def test_trainer(self): + output_dir = self.get_auto_remove_tmp_dir() + cmd = [ + "accelerate", + "launch", + "--use_fsdp", + "--main_process_port", + f"{get_torch_dist_unique_port()}", + "--num_processes", + f"{backend_device_count(torch_device)}", + "--fsdp_transformer_layer_cls_to_wrap", + "GPT2Block", + f"{self.test_file_dir}/test_trainer_fsdp.py", + "--output_dir", + f"{output_dir}", + "--report_to", + "none", + "--auto_find_batch_size", + "True", + ] + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +class TestFSDPTrainerTorchCompile(TestCasePlus): + @require_torch_multi_accelerator + @require_accelerate + @run_first + def test_trainer(self): + output_dir = self.get_auto_remove_tmp_dir() + cmd = [ + "accelerate", + "launch", + "--use_fsdp", + "--main_process_port", + f"{get_torch_dist_unique_port()}", + "--num_processes", + f"{backend_device_count(torch_device)}", + "--fsdp_transformer_layer_cls_to_wrap", + "GPT2Block", + f"{self.test_file_dir}/test_trainer_fsdp.py", + "--torch_compile_mode", + "default", + "--output_dir", + f"{output_dir}", + "--report_to", + "none", + ] + execute_subprocess_async(cmd, env=self.get_env()) + # successful return here == success - any errors would have caused an error in the sub-call + + +if __name__ == "__main__": + parser = HfArgumentParser((Seq2SeqTrainingArguments,)) + training_args = parser.parse_args_into_dataclasses()[0] + training_args.per_device_eval_batch_size = 1 + training_args.use_legacy_prediction_loop = False + training_args.predict_with_generate = True + training_args.generation_config = GenerationConfig(max_length=30) + + pretrained_model_name = "hf-internal-testing/tiny-random-gpt2" + tokenizer = AutoTokenizer.from_pretrained(pretrained_model_name) + tokenizer.pad_token = tokenizer.eos_token + device = torch.device(torch.distributed.get_rank()) + model = AutoModelForCausalLM.from_pretrained(pretrained_model_name).to(device) + + def compute_metrics(p: EvalPrediction) -> dict[str, bool]: + return {"accuracy": (p.predictions == p.label_ids).mean()} + + trainer = Seq2SeqTrainer( + model=model, + args=training_args, + data_collator=DataCollatorForSeq2Seq(tokenizer, model), + eval_dataset=DummyTextDataset(tokenizer), + compute_metrics=compute_metrics, + ) + + metrics = trainer.evaluate() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_seq2seq.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_seq2seq.py new file mode 100644 index 0000000000000000000000000000000000000000..0c4716a2bceb3838a9bd0e075cdc21af8892648a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_seq2seq.py @@ -0,0 +1,205 @@ +# Copyright 2020 the HuggingFace Inc. team. +# +# 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 transformers import ( + AutoModelForSeq2SeqLM, + BertTokenizer, + DataCollatorForSeq2Seq, + EncoderDecoderModel, + GenerationConfig, + Seq2SeqTrainer, + Seq2SeqTrainingArguments, + T5Tokenizer, +) +from transformers.testing_utils import TestCasePlus, require_sentencepiece, require_torch, slow +from transformers.utils import is_datasets_available + + +if is_datasets_available(): + import datasets + + +@require_sentencepiece +class Seq2seqTrainerTester(TestCasePlus): + @slow + @require_torch + def test_finetune_bert2bert(self): + bert2bert = EncoderDecoderModel.from_encoder_decoder_pretrained("prajjwal1/bert-tiny", "prajjwal1/bert-tiny") + tokenizer = BertTokenizer.from_pretrained("google-bert/bert-base-uncased") + + bert2bert.config.vocab_size = bert2bert.config.encoder.vocab_size + bert2bert.config.eos_token_id = tokenizer.sep_token_id + bert2bert.config.decoder_start_token_id = tokenizer.cls_token_id + bert2bert.config.max_length = 128 + + train_dataset = datasets.load_dataset("abisee/cnn_dailymail", "3.0.0", split="train[:1%]") + val_dataset = datasets.load_dataset("abisee/cnn_dailymail", "3.0.0", split="validation[:1%]") + + train_dataset = train_dataset.select(range(32)) + val_dataset = val_dataset.select(range(16)) + + batch_size = 4 + + def _map_to_encoder_decoder_inputs(batch): + # Tokenizer will automatically set [BOS] [EOS] + inputs = tokenizer(batch["article"], padding="max_length", truncation=True, max_length=512) + outputs = tokenizer(batch["highlights"], padding="max_length", truncation=True, max_length=128) + batch["input_ids"] = inputs.input_ids + batch["attention_mask"] = inputs.attention_mask + + batch["decoder_input_ids"] = outputs.input_ids + batch["labels"] = outputs.input_ids.copy() + batch["labels"] = [ + [-100 if token == tokenizer.pad_token_id else token for token in labels] for labels in batch["labels"] + ] + batch["decoder_attention_mask"] = outputs.attention_mask + + assert all(len(x) == 512 for x in inputs.input_ids) + assert all(len(x) == 128 for x in outputs.input_ids) + + return batch + + def _compute_metrics(pred): + labels_ids = pred.label_ids + pred_ids = pred.predictions + + # all unnecessary tokens are removed + pred_str = tokenizer.batch_decode(pred_ids, skip_special_tokens=True) + label_str = tokenizer.batch_decode(labels_ids, skip_special_tokens=True) + + accuracy = sum([int(pred_str[i] == label_str[i]) for i in range(len(pred_str))]) / len(pred_str) + + return {"accuracy": accuracy} + + # map train dataset + train_dataset = train_dataset.map( + _map_to_encoder_decoder_inputs, + batched=True, + batch_size=batch_size, + remove_columns=["article", "highlights"], + ) + train_dataset.set_format( + type="torch", + columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"], + ) + + # same for validation dataset + val_dataset = val_dataset.map( + _map_to_encoder_decoder_inputs, + batched=True, + batch_size=batch_size, + remove_columns=["article", "highlights"], + ) + val_dataset.set_format( + type="torch", + columns=["input_ids", "attention_mask", "decoder_input_ids", "decoder_attention_mask", "labels"], + ) + + output_dir = self.get_auto_remove_tmp_dir() + + training_args = Seq2SeqTrainingArguments( + output_dir=output_dir, + per_device_train_batch_size=batch_size, + per_device_eval_batch_size=batch_size, + predict_with_generate=True, + eval_strategy="steps", + do_train=True, + do_eval=True, + warmup_steps=0, + eval_steps=2, + logging_steps=2, + report_to="none", + ) + + # instantiate trainer + trainer = Seq2SeqTrainer( + model=bert2bert, + args=training_args, + compute_metrics=_compute_metrics, + train_dataset=train_dataset, + eval_dataset=val_dataset, + processing_class=tokenizer, + ) + + # start training + trainer.train() + + @slow + @require_torch + def test_return_sequences(self): + # Tests that the number of generated sequences is correct when num_return_sequences > 1 + # and essentially ensuring that `accelerator.gather()` is used instead of `gather_for_metrics` + INPUT_COLUMN = "question" + TARGET_COLUMN = "answer" + MAX_INPUT_LENGTH = 256 + MAX_TARGET_LENGTH = 256 + + dataset = datasets.load_dataset("openai/gsm8k", "main", split="train[:38]") + model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small") + tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") + data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, return_tensors="pt", padding="longest") + gen_config = GenerationConfig.from_pretrained( + "google-t5/t5-small", max_length=None, min_length=None, max_new_tokens=256, min_new_tokens=1, num_beams=5 + ) + + training_args = Seq2SeqTrainingArguments(".", predict_with_generate=True, report_to="none") + + trainer = Seq2SeqTrainer( + model=model, + args=training_args, + processing_class=tokenizer, + data_collator=data_collator, + compute_metrics=lambda x: {"samples": x[0].shape[0]}, + ) + + def prepare_data(examples): + # Remove pairs where at least one record is none + inputs = examples[INPUT_COLUMN] + targets = examples[TARGET_COLUMN] + + model_inputs = tokenizer(inputs, max_length=MAX_INPUT_LENGTH, truncation=True) + labels = tokenizer(text_target=targets, max_length=MAX_TARGET_LENGTH, truncation=True) + model_inputs["labels"] = labels["input_ids"] + + return model_inputs + + prepared_dataset = dataset.map(prepare_data, batched=True, remove_columns=[INPUT_COLUMN, TARGET_COLUMN]) + dataset_len = len(prepared_dataset) # 38 + + for num_return_sequences in range(3, 0, -1): + gen_config.num_return_sequences = num_return_sequences + metrics = trainer.evaluate(eval_dataset=prepared_dataset, generation_config=gen_config) + assert metrics["eval_samples"] == dataset_len * num_return_sequences, ( + f"Got {metrics['eval_samples']}, expected: {dataset_len * num_return_sequences}" + ) + + @require_torch + def test_bad_generation_config_fail_early(self): + # Tests that a bad generation config causes the trainer to fail early + model = AutoModelForSeq2SeqLM.from_pretrained("google-t5/t5-small") + tokenizer = T5Tokenizer.from_pretrained("google-t5/t5-small") + data_collator = DataCollatorForSeq2Seq(tokenizer, model=model, return_tensors="pt", padding="longest") + gen_config = GenerationConfig(do_sample=False, top_p=0.9) # bad: top_p is not compatible with do_sample=False + + training_args = Seq2SeqTrainingArguments( + ".", predict_with_generate=True, generation_config=gen_config, report_to="none" + ) + with self.assertRaises(ValueError) as exc: + _ = Seq2SeqTrainer( + model=model, + args=training_args, + processing_class=tokenizer, + data_collator=data_collator, + compute_metrics=lambda x: {"samples": x[0].shape[0]}, + ) + self.assertIn("Fix these issues to train your model", str(exc.exception)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_tpu.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_tpu.py new file mode 100644 index 0000000000000000000000000000000000000000..e7bb3d26406127e199128d41cc07ce24f2ea077b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_tpu.py @@ -0,0 +1,130 @@ +# 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. + +# This test is meant to be run in on an instance with TPUs like this: +# +# python examples/pytorch/xla_spawn.py --num_cores=8 tests/test_trainer_tpu.py +# +# Replace 8 with the number of TPU cores you have. +# + +import sys + +from transformers import EvalPrediction, HfArgumentParser, TrainingArguments, is_torch_available +from transformers.utils import logging + + +logger = logging.get_logger(__name__) + + +if is_torch_available(): + import torch + from torch import nn + from torch.utils.data import Dataset + + from transformers import Trainer + + class DummyDataset(Dataset): + def __init__(self, length: int = 101): + self.length = length + + def __len__(self): + return self.length + + def __getitem__(self, i) -> int: + return i + + class DummyDataCollator: + def __call__(self, features): + return {"input_ids": torch.tensor(features), "labels": torch.tensor(features)} + + class DummyModel(nn.Module): + def __init__(self): + super().__init__() + # Add some (unused) params otherwise DDP will complain. + self.fc = nn.Linear(120, 80) + + def forward(self, input_ids, labels=None): + if labels is not None: + return torch.tensor(0.0, device=input_ids.device), input_ids + else: + return input_ids + + +def main(): + parser = HfArgumentParser((TrainingArguments,)) + sys.argv += ["--output_dir", "./examples"] + training_args = parser.parse_args_into_dataclasses()[0] + + logger.warning( + f"Process rank: {training_args.local_rank}, device: {training_args.device}, " + f"tpu_num_cores: {training_args.tpu_num_cores}", + ) + + # Essentially, what we want to verify in the distributed case is + # that we get all samples back, in the right order. + # (this is crucial for prediction for instance) + for dataset_length in [1001, 256, 15]: + dataset = DummyDataset(dataset_length) + + def compute_metrics(p: EvalPrediction) -> dict: + sequential = list(range(len(dataset))) + success = p.predictions.tolist() == sequential and p.label_ids.tolist() == sequential + return {"success": success} + + trainer = Trainer( + model=DummyModel(), + args=training_args, + data_collator=DummyDataCollator(), + eval_dataset=dataset, + compute_metrics=compute_metrics, + ) + metrics = trainer.evaluate() + logger.info(metrics) + if metrics["eval_success"] is not True: + logger.error(metrics) + exit(1) + + p = trainer.predict(dataset) + logger.info(p.metrics) + if p.metrics["test_success"] is not True: + logger.error(p.metrics) + exit(1) + + trainer.args.eval_accumulation_steps = 2 + + metrics = trainer.evaluate() + logger.info(metrics) + if metrics["eval_success"] is not True: + logger.error(metrics) + exit(1) + + p = trainer.predict(dataset) + logger.info(p.metrics) + if p.metrics["test_success"] is not True: + logger.error(p.metrics) + exit(1) + + trainer.args.eval_accumulation_steps = None + + logger.info("🔥 All distributed tests successful") + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f24031b5d4ce876428e3c50980ecdc97c4e40335 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/trainer/test_trainer_utils.py @@ -0,0 +1,615 @@ +# Copyright 2018 the HuggingFace Inc. team. +# +# 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. + +import copy +import unittest + +import numpy as np + +from transformers.data.data_collator import default_data_collator +from transformers.testing_utils import require_accelerate, require_torch +from transformers.trainer_utils import RemoveColumnsCollator, find_executable_batch_size +from transformers.utils import is_torch_available + + +if is_torch_available(): + import torch + from torch import nn + from torch.utils.data import IterableDataset + + from transformers.modeling_outputs import SequenceClassifierOutput + from transformers.tokenization_utils_base import BatchEncoding + from transformers.trainer_pt_utils import ( + DistributedLengthGroupedSampler, + DistributedSamplerWithLoop, + DistributedTensorGatherer, + EvalLoopContainer, + IterableDatasetShard, + LabelSmoother, + LengthGroupedSampler, + SequentialDistributedSampler, + ShardSampler, + get_parameter_names, + numpy_pad_and_concatenate, + torch_pad_and_concatenate, + ) + + class TstLayer(nn.Module): + def __init__(self, hidden_size): + super().__init__() + self.linear1 = nn.Linear(hidden_size, hidden_size) + self.ln1 = nn.LayerNorm(hidden_size) + self.linear2 = nn.Linear(hidden_size, hidden_size) + self.ln2 = nn.LayerNorm(hidden_size) + self.bias = nn.Parameter(torch.zeros(hidden_size)) + + def forward(self, x): + h = self.ln1(nn.functional.relu(self.linear1(x))) + h = nn.functional.relu(self.linear2(x)) + return self.ln2(x + h + self.bias) + + class RandomIterableDataset(IterableDataset): + # For testing, an iterable dataset of random length + def __init__(self, p_stop=0.01, max_length=1000): + self.p_stop = p_stop + self.max_length = max_length + self.generator = torch.Generator() + + def __iter__(self): + count = 0 + stop = False + while not stop and count < self.max_length: + yield count + count += 1 + number = torch.rand(1, generator=self.generator).item() + stop = number < self.p_stop + + +@require_torch +class TrainerUtilsTest(unittest.TestCase): + def test_distributed_tensor_gatherer(self): + # Simulate a result with a dataset of size 21, 4 processes and chunks of lengths 2, 3, 1 + world_size = 4 + num_samples = 21 + input_indices = [ + [0, 1, 6, 7, 12, 13, 18, 19], + [2, 3, 4, 8, 9, 10, 14, 15, 16, 20, 0, 1], + [5, 11, 17, 2], + ] + + predictions = np.random.normal(size=(num_samples, 13)) + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices in input_indices: + gatherer.add_arrays(predictions[indices]) + result = gatherer.finalize() + self.assertTrue(np.array_equal(result, predictions)) + + # With nested tensors + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices in input_indices: + gatherer.add_arrays([predictions[indices], [predictions[indices], predictions[indices]]]) + result = gatherer.finalize() + self.assertTrue(isinstance(result, list)) + self.assertEqual(len(result), 2) + self.assertTrue(isinstance(result[1], list)) + self.assertEqual(len(result[1]), 2) + self.assertTrue(np.array_equal(result[0], predictions)) + self.assertTrue(np.array_equal(result[1][0], predictions)) + self.assertTrue(np.array_equal(result[1][1], predictions)) + + def test_distributed_tensor_gatherer_different_shapes(self): + # Simulate a result with a dataset of size 21, 4 processes and chunks of lengths 2, 3, 1 + world_size = 4 + num_samples = 21 + input_indices = [ + [0, 1, 6, 7, 12, 13, 18, 19], + [2, 3, 4, 8, 9, 10, 14, 15, 16, 20, 0, 1], + [5, 11, 17, 2], + ] + sequence_lengths = [8, 10, 13] + + predictions = np.random.normal(size=(num_samples, 13)) + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices, seq_length in zip(input_indices, sequence_lengths): + gatherer.add_arrays(predictions[indices, :seq_length]) + result = gatherer.finalize() + + # Remove the extra samples added at the end for a round multiple of num processes. + actual_indices = [input_indices[0], input_indices[1][:-2], input_indices[2][:-1]] + for indices, seq_length in zip(actual_indices, sequence_lengths): + self.assertTrue(np.array_equal(result[indices, :seq_length], predictions[indices, :seq_length])) + + # With nested tensors + predictions = np.random.normal(size=(num_samples, 13)) + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices, seq_length in zip(input_indices, sequence_lengths): + gatherer.add_arrays([predictions[indices, :seq_length], predictions[indices]]) + result = gatherer.finalize() + + for indices, seq_length in zip(actual_indices, sequence_lengths): + self.assertTrue(np.array_equal(result[0][indices, :seq_length], predictions[indices, :seq_length])) + self.assertTrue(np.array_equal(result[1], predictions)) + + # Check if works if varying seq_length is second + gatherer = DistributedTensorGatherer(world_size=world_size, num_samples=num_samples) + for indices, seq_length in zip(input_indices, sequence_lengths): + gatherer.add_arrays([predictions[indices], predictions[indices, :seq_length]]) + result = gatherer.finalize() + + self.assertTrue(np.array_equal(result[0], predictions)) + for indices, seq_length in zip(actual_indices, sequence_lengths): + self.assertTrue(np.array_equal(result[1][indices, :seq_length], predictions[indices, :seq_length])) + + def test_label_smoothing(self): + epsilon = 0.1 + num_labels = 12 + random_logits = torch.randn(4, 5, num_labels) + random_labels = torch.randint(0, num_labels, (4, 5)) + loss = nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) + model_output = SequenceClassifierOutput(logits=random_logits) + label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) + log_probs = -nn.functional.log_softmax(random_logits, dim=-1) + expected_loss = (1 - epsilon) * loss + epsilon * log_probs.mean() + torch.testing.assert_close(label_smoothed_loss, expected_loss) + + # With a few -100 labels + random_labels[0, 1] = -100 + random_labels[2, 1] = -100 + random_labels[2, 3] = -100 + + loss = nn.functional.cross_entropy(random_logits.view(-1, num_labels), random_labels.view(-1)) + model_output = SequenceClassifierOutput(logits=random_logits) + label_smoothed_loss = LabelSmoother(0.1)(model_output, random_labels) + log_probs = -nn.functional.log_softmax(random_logits, dim=-1) + # Mask the log probs with the -100 labels + log_probs[0, 1] = 0.0 + log_probs[2, 1] = 0.0 + log_probs[2, 3] = 0.0 + expected_loss = (1 - epsilon) * loss + epsilon * log_probs.sum() / (num_labels * 17) + torch.testing.assert_close(label_smoothed_loss, expected_loss) + + def test_group_by_length(self): + # Get some inputs of random lengths + lengths = torch.randint(0, 25, (100,)).tolist() + # Put one bigger than the others to check it ends up in first position + lengths[32] = 50 + + indices = list(LengthGroupedSampler(4, lengths=lengths)) + # The biggest element should be first + self.assertEqual(lengths[indices[0]], 50) + # The indices should be a permutation of range(100) + self.assertEqual(sorted(indices), list(range(100))) + + def test_group_by_length_with_dict(self): + # Get some inputs of random lengths + data = [] + for _ in range(6): + input_ids = torch.randint(0, 25, (100,)).tolist() + data.append({"input_ids": input_ids}) + # Put one bigger than the others to check it ends up in first position + data[3]["input_ids"] = torch.randint(0, 25, (105,)).tolist() + + indices = list(LengthGroupedSampler(4, dataset=data)) + # The biggest element should be first + self.assertEqual(len(data[indices[0]]["input_ids"]), 105) + # The indices should be a permutation of range(6) + self.assertEqual(sorted(indices), list(range(6))) + + def test_group_by_length_with_batch_encoding(self): + # Get some inputs of random lengths + data = [] + for _ in range(6): + input_ids = torch.randint(0, 25, (100,)).tolist() + data.append(BatchEncoding({"input_ids": input_ids})) + # Put one bigger than the others to check it ends up in first position + data[3]["input_ids"] = torch.randint(0, 25, (105,)).tolist() + + indices = list(LengthGroupedSampler(4, dataset=data)) + # The biggest element should be first + self.assertEqual(len(data[indices[0]]["input_ids"]), 105) + # The indices should be a permutation of range(6) + self.assertEqual(sorted(indices), list(range(6))) + + def test_distributed_length_grouped(self): + # Get some inputs of random lengths + lengths = torch.randint(0, 25, (100,)).tolist() + # Put one bigger than the others to check it ends up in first position + lengths[32] = 50 + + indices_process_0 = list(DistributedLengthGroupedSampler(4, num_replicas=2, rank=0, lengths=lengths)) + indices_process_1 = list(DistributedLengthGroupedSampler(4, num_replicas=2, rank=1, lengths=lengths)) + # The biggest element should be first + self.assertEqual(lengths[indices_process_0[0]], 50) + # The indices should be a permutation of range(100) + self.assertEqual(sorted(indices_process_0 + indices_process_1), list(range(100))) + + def test_get_parameter_names(self): + model = nn.Sequential(TstLayer(128), nn.ModuleList([TstLayer(128), TstLayer(128)])) + # fmt: off + self.assertEqual( + get_parameter_names(model, [nn.LayerNorm]), + ['0.linear1.weight', '0.linear1.bias', '0.linear2.weight', '0.linear2.bias', '0.bias', '1.0.linear1.weight', '1.0.linear1.bias', '1.0.linear2.weight', '1.0.linear2.bias', '1.0.bias', '1.1.linear1.weight', '1.1.linear1.bias', '1.1.linear2.weight', '1.1.linear2.bias', '1.1.bias'] + ) + # fmt: on + + def test_get_parameter_names_rmsnorm(self): + class RMSNorm(nn.Module): + def __init__(self, hidden_size): + super().__init__() + self.weight = nn.Parameter(torch.ones(hidden_size)) + self.bias = nn.Parameter(torch.zeros(hidden_size)) + + class ModelWithRMSNorm(nn.Module): + def __init__(self): + super().__init__() + self.linear = nn.Linear(128, 128) + self.rmsnorm = RMSNorm(128) + self.bias = nn.Parameter(torch.zeros(128)) + + model = ModelWithRMSNorm() + # Test both type-based and name-based filtering + decay_parameters = get_parameter_names(model, [], ["bias", "rmsnorm"]) + + # Parameters that should be in weight decay + self.assertIn("linear.weight", decay_parameters) + + # Parameters that should NOT be in weight decay + self.assertNotIn("linear.bias", decay_parameters) + self.assertNotIn("rmsnorm.weight", decay_parameters) + self.assertNotIn("rmsnorm.bias", decay_parameters) + self.assertNotIn("bias", decay_parameters) + + def test_distributed_sampler_with_loop(self): + batch_size = 16 + for length in [23, 64, 123]: + dataset = list(range(length)) + shard1 = DistributedSamplerWithLoop(dataset, batch_size, num_replicas=2, rank=0) + shard2 = DistributedSamplerWithLoop(dataset, batch_size, num_replicas=2, rank=1) + + # Set seeds + shard1.set_epoch(0) + shard2.set_epoch(0) + + # Sample + samples1 = list(shard1) + samples2 = list(shard2) + + self.assertTrue(len(samples1) % batch_size == 0) + self.assertTrue(len(samples2) % batch_size == 0) + + total = [] + for sample1, sample2 in zip(samples1, samples2): + total += [sample1, sample2] + + self.assertEqual(set(total[:length]), set(dataset)) + self.assertEqual(set(total[length:]), set(total[: (len(total) - length)])) + + def test_sequential_distributed_sampler(self): + batch_size = 16 + for length in [23, 64, 123]: + dataset = list(range(length)) + shard1 = SequentialDistributedSampler(dataset, num_replicas=2, rank=0) + shard2 = SequentialDistributedSampler(dataset, num_replicas=2, rank=1) + + # Sample + samples1 = list(shard1) + samples2 = list(shard2) + + total = samples1 + samples2 + + self.assertListEqual(total[:length], dataset) + self.assertListEqual(total[length:], dataset[: (len(total) - length)]) + + # With a batch_size passed + shard1 = SequentialDistributedSampler(dataset, num_replicas=2, rank=0, batch_size=batch_size) + shard2 = SequentialDistributedSampler(dataset, num_replicas=2, rank=1, batch_size=batch_size) + + # Sample + samples1 = list(shard1) + samples2 = list(shard2) + + self.assertTrue(len(samples1) % batch_size == 0) + self.assertTrue(len(samples2) % batch_size == 0) + + total = samples1 + samples2 + + self.assertListEqual(total[:length], dataset) + self.assertListEqual(total[length:], dataset[: (len(total) - length)]) + + def check_iterable_dataset_shard(self, dataset, batch_size, drop_last, num_processes=2, epoch=0): + # Set the seed for the base dataset to get the proper reference. + dataset.generator.manual_seed(epoch) + reference = list(dataset) + + shards = [ + IterableDatasetShard( + dataset, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i + ) + for i in range(num_processes) + ] + for shard in shards: + shard.set_epoch(epoch) + shard_lists = [list(shard) for shard in shards] + + for shard in shard_lists: + # All shards have a number of samples that is a round multiple of batch size + self.assertTrue(len(shard) % batch_size == 0) + # All shards have the same number of samples + self.assertEqual(len(shard), len(shard_lists[0])) + + for shard in shards: + # All shards know the total number of samples + self.assertEqual(shard.num_examples, len(reference)) + + observed = [] + for idx in range(0, len(shard_lists[0]), batch_size): + for shard in shard_lists: + observed += shard[idx : idx + batch_size] + + # If drop_last is False we loop through samples at the beginning to have a size that is a round multiple of + # batch_size + if not drop_last: + while len(reference) < len(observed): + reference += reference + self.assertListEqual(observed, reference[: len(observed)]) + + # Check equivalence between IterableDataset and ShardSampler + dataset.generator.manual_seed(epoch) + reference = list(dataset) + + sampler_shards = [ + ShardSampler( + reference, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i + ) + for i in range(num_processes) + ] + for shard, sampler_shard in zip(shard_lists, sampler_shards): + self.assertListEqual(shard, list(sampler_shard)) + + def test_iterable_dataset_shard(self): + dataset = RandomIterableDataset() + + self.check_iterable_dataset_shard(dataset, 4, drop_last=True, num_processes=2, epoch=0) + self.check_iterable_dataset_shard(dataset, 4, drop_last=False, num_processes=2, epoch=0) + + self.check_iterable_dataset_shard(dataset, 4, drop_last=True, num_processes=3, epoch=42) + self.check_iterable_dataset_shard(dataset, 4, drop_last=False, num_processes=3, epoch=42) + + def test_iterable_dataset_shard_with_length(self): + sampler_shards = [ + IterableDatasetShard(list(range(100)), batch_size=4, drop_last=True, num_processes=2, process_index=i) + for i in range(2) + ] + + # Build expected shards: each process will have batches of size 4 until there is not enough elements to + # form two full batches (so we stop at 96 = (100 // (4 * 2)) * 4) + expected_shards = [[], []] + current_shard = 0 + for i in range(0, 96, 4): + expected_shards[current_shard].extend(list(range(i, i + 4))) + current_shard = 1 - current_shard + + self.assertListEqual([list(shard) for shard in sampler_shards], expected_shards) + self.assertListEqual([len(shard) for shard in sampler_shards], [len(shard) for shard in expected_shards]) + + sampler_shards = [ + IterableDatasetShard(list(range(100)), batch_size=4, drop_last=False, num_processes=2, process_index=i) + for i in range(2) + ] + # When drop_last=False, we get two last full batches by looping back to the beginning. + expected_shards[0].extend(list(range(96, 100))) + expected_shards[1].extend(list(range(0, 4))) + + self.assertListEqual([list(shard) for shard in sampler_shards], expected_shards) + self.assertListEqual([len(shard) for shard in sampler_shards], [len(shard) for shard in expected_shards]) + + def check_shard_sampler(self, dataset, batch_size, drop_last, num_processes=2): + shards = [ + ShardSampler( + dataset, batch_size=batch_size, drop_last=drop_last, num_processes=num_processes, process_index=i + ) + for i in range(num_processes) + ] + shard_lists = [list(shard) for shard in shards] + + for shard in shard_lists: + # All shards have a number of samples that is a round multiple of batch size + self.assertTrue(len(shard) % batch_size == 0) + # All shards have the same number of samples + self.assertEqual(len(shard), len(shard_lists[0])) + + observed = [] + for idx in range(0, len(shard_lists[0]), batch_size): + for shard in shard_lists: + observed += shard[idx : idx + batch_size] + + # If drop_last is False we loop through samples at the beginning to have a size that is a round multiple of + # batch_size + reference = copy.copy(dataset) + if not drop_last: + while len(reference) < len(observed): + reference += reference + self.assertListEqual(observed, reference[: len(observed)]) + + def test_shard_sampler(self): + for n_elements in [64, 123]: + dataset = list(range(n_elements)) + + self.check_shard_sampler(dataset, 4, drop_last=True, num_processes=2) + self.check_shard_sampler(dataset, 4, drop_last=False, num_processes=2) + + self.check_shard_sampler(dataset, 4, drop_last=True, num_processes=3) + self.check_shard_sampler(dataset, 4, drop_last=False, num_processes=3) + + @require_accelerate + def test_executable_batch_size(self): + batch_sizes = [] + + @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=True) + def mock_training_loop_function(batch_size): + nonlocal batch_sizes + batch_sizes.append(batch_size) + if batch_size > 16: + raise RuntimeError("CUDA out of memory.") + + mock_training_loop_function() + self.assertEqual(batch_sizes, [64, 57, 51, 45, 40, 36, 32, 28, 25, 22, 19, 17, 15]) + + @require_accelerate + def test_executable_batch_size_no_search(self): + batch_sizes = [] + + @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=False) + def mock_training_loop_function(batch_size): + nonlocal batch_sizes + batch_sizes.append(batch_size) + + mock_training_loop_function() + self.assertEqual(batch_sizes, [64]) + + @require_accelerate + def test_executable_batch_size_with_error(self): + @find_executable_batch_size(starting_batch_size=64, auto_find_batch_size=False) + def mock_training_loop_function(batch_size): + raise RuntimeError("CUDA out of memory.") + + with self.assertRaises(RuntimeError) as cm: + mock_training_loop_function() + self.assertEqual("CUDA out of memory", cm.args[0]) + + def test_pad_and_concatenate_with_1d(self): + """Tests whether pad_and_concatenate works with scalars.""" + array1 = 1.0 + array2 = 2.0 + result = numpy_pad_and_concatenate(array1, array2) + self.assertTrue(np.array_equal(np.array([1.0, 2.0]), result)) + + tensor1 = torch.tensor(1.0) + tensor2 = torch.tensor(2.0) + result = torch_pad_and_concatenate(tensor1, tensor2) + self.assertTrue(torch.equal(result, torch.Tensor([1.0, 2.0]))) + + def test_remove_columns_collator(self): + class MockLogger: + def __init__(self) -> None: + self.called = 0 + + def info(self, msg): + self.called += 1 + self.last_msg = msg + + data_batch = [ + {"col1": 1, "col2": 2, "col3": 3}, + {"col1": 1, "col2": 2, "col3": 3}, + ] + logger = MockLogger() + remove_columns_collator = RemoveColumnsCollator( + default_data_collator, ["col1", "col2"], logger, "model", "training" + ) + + self.assertNotIn("col3", remove_columns_collator(data_batch)) + # check that the logging message is printed out only once + remove_columns_collator(data_batch) + remove_columns_collator(data_batch) + self.assertEqual(logger.called, 1) + self.assertIn("col3", logger.last_msg) + + def test_eval_loop_container(self): + batch_1 = [ + torch.ones([8, 5]), + {"loss": torch.tensor(1.0)}, + (torch.ones([8, 2, 3]), torch.ones([8, 2])), + ] + batch_2 = [ + torch.ones([4, 5]), + {"loss": torch.tensor(2.0)}, + (torch.ones([4, 2, 3]), torch.ones([4, 6])), + ] + + concat_container = EvalLoopContainer(do_nested_concat=True, padding_index=-100) + concat_container.add(batch_1) + concat_container.add(batch_2) + concat_container.to_cpu_and_numpy() + arrays = concat_container.get_arrays() + + # Test two nested batches concatenation + self.assertIsInstance(arrays, list) + self.assertEqual(len(arrays), 3) + self.assertIsInstance(arrays[0], np.ndarray) + self.assertEqual(arrays[0].shape, (12, 5)) + self.assertIsInstance(arrays[1], dict) + self.assertIsInstance(arrays[1]["loss"], np.ndarray) + self.assertEqual(arrays[1]["loss"].shape, (2,)) + self.assertTrue(np.allclose(arrays[1]["loss"], np.array([1.0, 2.0]))) + self.assertIsInstance(arrays[2], tuple) + self.assertEqual(len(arrays[2]), 2) + self.assertEqual(arrays[2][0].shape, (12, 2, 3)) + self.assertEqual(arrays[2][1].shape, (12, 6)) + # check that first batch padded with padding index -100 after concatenation + self.assertEqual(arrays[2][1][0][2], -100) + + # Test two batches with no concatenation + list_container = EvalLoopContainer(do_nested_concat=False) + list_container.add(batch_1) + list_container.add(batch_2) + list_container.to_cpu_and_numpy() + arrays = list_container.get_arrays() + + self.assertEqual(len(arrays), 2) + self.assertIsInstance(arrays, list) + np_batch_1, np_batch_2 = arrays + + self.assertIsInstance(np_batch_1, list) + self.assertEqual(len(np_batch_1), 3) + self.assertIsInstance(np_batch_1[0], np.ndarray) + self.assertIsInstance(np_batch_1[1], dict) + self.assertIsInstance(np_batch_1[2], tuple) + self.assertEqual(np_batch_1[0].shape, (8, 5)) + self.assertEqual(np_batch_1[1]["loss"].shape, ()) + self.assertEqual(np_batch_1[2][0].shape, (8, 2, 3)) + self.assertEqual(np_batch_1[2][1].shape, (8, 2)) + + self.assertIsInstance(np_batch_2, list) + self.assertEqual(len(np_batch_2), 3) + self.assertIsInstance(np_batch_2[0], np.ndarray) + self.assertIsInstance(np_batch_2[1], dict) + self.assertIsInstance(np_batch_2[2], tuple) + self.assertEqual(np_batch_2[0].shape, (4, 5)) + self.assertEqual(np_batch_2[1]["loss"].shape, ()) + self.assertEqual(np_batch_2[2][0].shape, (4, 2, 3)) + self.assertEqual(np_batch_2[2][1].shape, (4, 6)) + + # Test no batches + none_arr = EvalLoopContainer(do_nested_concat=True, padding_index=-100).get_arrays() + self.assertIsNone(none_arr) + + none_arr = EvalLoopContainer(do_nested_concat=False).get_arrays() + self.assertIsNone(none_arr) + + # Test one batch + concat_container = EvalLoopContainer(do_nested_concat=True, padding_index=-100) + concat_container.add(batch_1) + arrays = concat_container.get_arrays() + self.assertIsInstance(arrays, list) + self.assertEqual(len(arrays), 3) + self.assertIsInstance(arrays[0], np.ndarray) + self.assertEqual(arrays[0].shape, (8, 5)) + self.assertIsInstance(arrays[1], dict) + self.assertIsInstance(arrays[1]["loss"], np.ndarray) + self.assertEqual(arrays[1]["loss"].shape, ()) + self.assertTrue(np.allclose(arrays[1]["loss"], np.array([1.0]))) + self.assertIsInstance(arrays[2], tuple) + self.assertEqual(len(arrays[2]), 2) + self.assertEqual(arrays[2][0].shape, (8, 2, 3)) + self.assertEqual(arrays[2][1].shape, (8, 2)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/failing_export.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/failing_export.py new file mode 100644 index 0000000000000000000000000000000000000000..3ee0176063836ae2544a00b928470f5eb395aed7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/failing_export.py @@ -0,0 +1,23 @@ +# 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. + +# fmt: off + +from transformers.utils.import_utils import requires + + +@requires(backends=("random_item_that_should_not_exist",)) +class A0: + def __init__(self): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_raw_register.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_raw_register.py new file mode 100644 index 0000000000000000000000000000000000000000..a1df4a9c2e93c52c3dc9dbadd3b61c35fe5f2de7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_raw_register.py @@ -0,0 +1,80 @@ +# 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. + +# fmt: off + +from transformers.utils.import_utils import requires + + +@requires() +class A0: + def __init__(self): + pass + + +@requires() +def a0(): + pass + + +@requires(backends=("torch", "tf")) +class A1: + def __init__(self): + pass + + +@requires(backends=("torch", "tf")) +def a1(): + pass + + +@requires( + backends=("torch", "tf") +) +class A2: + def __init__(self): + pass + + +@requires( + backends=("torch", "tf") +) +def a2(): + pass + + +@requires( + backends=( + "torch", + "tf" + ) +) +class A3: + def __init__(self): + pass + + +@requires( + backends=( + "torch", + "tf" + ) +) +def a3(): + pass + +@requires(backends=()) +class A4: + def __init__(self): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_raw_register_with_versions.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_raw_register_with_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..6d7c10e979395857566b405aea42433bccc95422 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_raw_register_with_versions.py @@ -0,0 +1,92 @@ +# 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. + +# fmt: off + +from transformers.utils.import_utils import requires + + +@requires(backends=("torch>=2.5",)) +class D0: + def __init__(self): + pass + + +@requires(backends=("torch>=2.5",)) +def d0(): + pass + + +@requires(backends=("torch>2.5",)) +class D1: + def __init__(self): + pass + + +@requires(backends=("torch>2.5",)) +def d1(): + pass + + +@requires(backends=("torch<=2.5",)) +class D2: + def __init__(self): + pass + + +@requires(backends=("torch<=2.5",)) +def d2(): + pass + +@requires(backends=("torch<2.5",)) +class D3: + def __init__(self): + pass + + +@requires(backends=("torch<2.5",)) +def d3(): + pass + + +@requires(backends=("torch==2.5",)) +class D4: + def __init__(self): + pass + + +@requires(backends=("torch==2.5",)) +def d4(): + pass + + +@requires(backends=("torch!=2.5",)) +class D5: + def __init__(self): + pass + + +@requires(backends=("torch!=2.5",)) +def d5(): + pass + +@requires(backends=("torch>=2.5", "accelerate<0.20")) +class D6: + def __init__(self): + pass + + +@requires(backends=("torch>=2.5", "accelerate<0.20")) +def d6(): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_register_with_comments.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_register_with_comments.py new file mode 100644 index 0000000000000000000000000000000000000000..aed2b196ca68ce5c1be102eafb3ca8765e5ac5c0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_register_with_comments.py @@ -0,0 +1,79 @@ +# 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. + +# fmt: off + +from transformers.utils.import_utils import requires + + +@requires() +# That's a statement +class B0: + def __init__(self): + pass + + +@requires() +# That's a statement +def b0(): + pass + + +@requires(backends=("torch", "tf")) +# That's a statement +class B1: + def __init__(self): + pass + + +@requires(backends=("torch", "tf")) +# That's a statement +def b1(): + pass + + +@requires(backends=("torch", "tf")) +# That's a statement +class B2: + def __init__(self): + pass + + +@requires(backends=("torch", "tf")) +# That's a statement +def b2(): + pass + + +@requires( + backends=( + "torch", + "tf" + ) +) +# That's a statement +class B3: + def __init__(self): + pass + + +@requires( + backends=( + "torch", + "tf" + ) +) +# That's a statement +def b3(): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_register_with_duplicates.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_register_with_duplicates.py new file mode 100644 index 0000000000000000000000000000000000000000..84e6b2b91a74bacc48964751f6a20b42290be8af --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/import_structures/import_structure_register_with_duplicates.py @@ -0,0 +1,77 @@ +# 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. + +# fmt: off + +from transformers.utils.import_utils import requires + + +@requires(backends=("torch", "torch")) +class C0: + def __init__(self): + pass + + +@requires(backends=("torch", "torch")) +def c0(): + pass + + +@requires(backends=("torch", "torch")) +# That's a statement +class C1: + def __init__(self): + pass + + +@requires(backends=("torch", "torch")) +# That's a statement +def c1(): + pass + + +@requires(backends=("torch", "torch")) +# That's a statement +class C2: + def __init__(self): + pass + + +@requires(backends=("torch", "torch")) +# That's a statement +def c2(): + pass + + +@requires( + backends=( + "torch", + "torch" + ) +) +# That's a statement +class C3: + def __init__(self): + pass + + +@requires( + backends=( + "torch", + "torch" + ) +) +# That's a statement +def c3(): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_activations.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_activations.py new file mode 100644 index 0000000000000000000000000000000000000000..e19b575d1523a3d2dadb8f1678a0a125ee93a869 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_activations.py @@ -0,0 +1,74 @@ +# 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. + +import unittest + +from transformers import is_torch_available +from transformers.testing_utils import require_torch + + +if is_torch_available(): + import torch + + from transformers.activations import gelu_new, gelu_python, get_activation + + +@require_torch +class TestActivations(unittest.TestCase): + def test_gelu_versions(self): + x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) + torch_builtin = get_activation("gelu") + torch.testing.assert_close(gelu_python(x), torch_builtin(x)) + self.assertFalse(torch.allclose(gelu_python(x), gelu_new(x))) + + def test_gelu_10(self): + x = torch.tensor([-100, -1, -0.1, 0, 0.1, 1.0, 100]) + torch_builtin = get_activation("gelu") + gelu10 = get_activation("gelu_10") + + y_gelu = torch_builtin(x) + y_gelu_10 = gelu10(x) + + clipped_mask = torch.where(y_gelu_10 < 10.0, 1, 0) + + self.assertTrue(torch.max(y_gelu_10).item() == 10.0) + torch.testing.assert_close(y_gelu * clipped_mask, y_gelu_10 * clipped_mask) + + def test_get_activation(self): + get_activation("gelu") + get_activation("gelu_10") + get_activation("gelu_fast") + get_activation("gelu_new") + get_activation("gelu_python") + get_activation("gelu_pytorch_tanh") + get_activation("linear") + get_activation("mish") + get_activation("quick_gelu") + get_activation("relu") + get_activation("sigmoid") + get_activation("silu") + get_activation("swish") + get_activation("tanh") + with self.assertRaises(KeyError): + get_activation("bogus") + with self.assertRaises(KeyError): + get_activation(None) + + def test_activations_are_distinct_objects(self): + act1 = get_activation("gelu") + act1.a = 1 + act2 = get_activation("gelu") + self.assertEqual(act1.a, 1) + with self.assertRaises(AttributeError): + _ = act2.a diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_add_new_model_like.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_add_new_model_like.py new file mode 100644 index 0000000000000000000000000000000000000000..dffe7189780607e3c767005a4288384a27aacdcd --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_add_new_model_like.py @@ -0,0 +1,826 @@ +# 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. +import os +import shutil +import tempfile +import textwrap +import unittest +from datetime import date +from pathlib import Path + +import transformers.commands.add_new_model_like +from transformers.commands.add_new_model_like import ModelInfos, create_new_model_like +from transformers.testing_utils import require_torch + + +REPO_PATH = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) +MODELS_TO_COPY = ("auto", "llama", "phi4_multimodal") +CURRENT_YEAR = date.today().year + + +@require_torch +class TestAddNewModelLike(unittest.TestCase): + @classmethod + def setUpClass(cls): + """ + Create a temporary repo with the same structure as Transformers, with just 2 models. + """ + cls.FAKE_REPO = tempfile.TemporaryDirectory().name + os.makedirs(os.path.join(cls.FAKE_REPO, "src", "transformers", "models"), exist_ok=True) + os.makedirs(os.path.join(cls.FAKE_REPO, "tests", "models"), exist_ok=True) + os.makedirs(os.path.join(cls.FAKE_REPO, "docs", "source", "en", "model_doc"), exist_ok=True) + + # We need to copy the utils to run the cleanup commands + utils_src = os.path.join(REPO_PATH, "utils") + shutil.copytree(utils_src, utils_src.replace(REPO_PATH, cls.FAKE_REPO)) + # Copy the __init__ files + model_init = os.path.join(REPO_PATH, "src", "transformers", "models", "__init__.py") + shutil.copy(model_init, model_init.replace(REPO_PATH, cls.FAKE_REPO)) + doc_toc = os.path.join(REPO_PATH, "docs", "source", "en", "_toctree.yml") + shutil.copy(doc_toc, doc_toc.replace(REPO_PATH, cls.FAKE_REPO)) + # We need the pyproject for ruff as well + pyproject = os.path.join(REPO_PATH, "pyproject.toml") + shutil.copy(pyproject, pyproject.replace(REPO_PATH, cls.FAKE_REPO)) + # Copy over all the specific model files + for model in MODELS_TO_COPY: + model_src = os.path.join(REPO_PATH, "src", "transformers", "models", model) + shutil.copytree(model_src, model_src.replace(REPO_PATH, cls.FAKE_REPO)) + + test_src = os.path.join(REPO_PATH, "tests", "models", model) + shutil.copytree(test_src, test_src.replace(REPO_PATH, cls.FAKE_REPO)) + + if model != "auto": + doc_src = os.path.join(REPO_PATH, "docs", "source", "en", "model_doc", f"{model}.md") + shutil.copy(doc_src, doc_src.replace(REPO_PATH, cls.FAKE_REPO)) + + # Replace the globals + cls.ORIGINAL_REPO = transformers.commands.add_new_model_like.REPO_PATH + cls.ORIGINAL_TRANSFORMERS_REPO = transformers.commands.add_new_model_like.TRANSFORMERS_PATH + transformers.commands.add_new_model_like.REPO_PATH = Path(cls.FAKE_REPO) + transformers.commands.add_new_model_like.TRANSFORMERS_PATH = Path(cls.FAKE_REPO) / "src" / "transformers" + + # For convenience + cls.MODEL_PATH = os.path.join(cls.FAKE_REPO, "src", "transformers", "models") + cls.TESTS_MODEL_PATH = os.path.join(cls.FAKE_REPO, "tests", "models") + cls.DOC_PATH = os.path.join(cls.FAKE_REPO, "docs", "source", "en") + + @classmethod + def tearDownClass(cls): + transformers.commands.add_new_model_like.REPO_PATH = cls.ORIGINAL_REPO + transformers.commands.add_new_model_like.TRANSFORMERS_PATH = cls.ORIGINAL_TRANSFORMERS_REPO + del cls.FAKE_REPO + + def assertFileIsEqual(self, text: str, filepath: str): + with open(filepath, "r") as f: + file_text = f.read() + self.assertEqual(file_text.strip(), text.strip()) + + def assertInFile(self, text: str, filepath: str): + with open(filepath, "r") as f: + file_text = f.read() + self.assertTrue(text in file_text) + + def test_llama_without_tokenizers(self): + # This is the structure without adding the tokenizers + filenames_to_add = ( + ("configuration_llama.py", True), + ("modeling_llama.py", True), + ("tokenization_llama.py", False), + ("tokenization_llama_fast.py", False), + ("image_processing_llama.py", False), + ("image_processing_llama_fast.py", False), + ("video_processing_llama.py", False), + ("feature_extraction_llama.py", False), + ("processing_llama.py", False), + ) + # Run the command + create_new_model_like( + old_model_infos=ModelInfos("llama"), + new_lowercase_name="my_test", + new_model_paper_name="MyTest", + filenames_to_add=filenames_to_add, + create_fast_image_processor=False, + ) + + # First assert that all files were created correctly + model_repo = os.path.join(self.MODEL_PATH, "my_test") + tests_repo = os.path.join(self.TESTS_MODEL_PATH, "my_test") + self.assertTrue(os.path.isfile(os.path.join(model_repo, "modular_my_test.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "modeling_my_test.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "configuration_my_test.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "__init__.py"))) + self.assertTrue(os.path.isfile(os.path.join(self.DOC_PATH, "model_doc", "my_test.md"))) + self.assertTrue(os.path.isfile(os.path.join(tests_repo, "__init__.py"))) + self.assertTrue(os.path.isfile(os.path.join(tests_repo, "test_modeling_my_test.py"))) + + # Now assert the correct imports/auto mappings/toctree were added + self.assertInFile( + "from .my_test import *\n", + os.path.join(self.MODEL_PATH, "__init__.py"), + ) + self.assertInFile( + '("my_test", "MyTestConfig"),\n', + os.path.join(self.MODEL_PATH, "auto", "configuration_auto.py"), + ) + self.assertInFile( + '("my_test", "MyTest"),\n', + os.path.join(self.MODEL_PATH, "auto", "configuration_auto.py"), + ) + self.assertInFile( + '("my_test", "MyTestModel"),\n', + os.path.join(self.MODEL_PATH, "auto", "modeling_auto.py"), + ) + self.assertInFile( + '("my_test", "MyTestForCausalLM"),\n', + os.path.join(self.MODEL_PATH, "auto", "modeling_auto.py"), + ) + self.assertInFile( + '("my_test", "MyTestForSequenceClassification"),\n', + os.path.join(self.MODEL_PATH, "auto", "modeling_auto.py"), + ) + self.assertInFile( + '("my_test", "MyTestForQuestionAnswering"),\n', + os.path.join(self.MODEL_PATH, "auto", "modeling_auto.py"), + ) + self.assertInFile( + '("my_test", "MyTestForTokenClassification"),\n', + os.path.join(self.MODEL_PATH, "auto", "modeling_auto.py"), + ) + self.assertInFile( + "- local: model_doc/my_test\n title: MyTest\n", + os.path.join(self.DOC_PATH, "_toctree.yml"), + ) + + # Check some exact file creation. For model definition, only check modular as modeling/config/etc... are created + # directly from it + EXPECTED_MODULAR = textwrap.dedent( + f""" + # coding=utf-8 + # Copyright {CURRENT_YEAR} 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. + + from ..llama.configuration_llama import LlamaConfig + from ..llama.modeling_llama import ( + LlamaAttention, + LlamaDecoderLayer, + LlamaForCausalLM, + LlamaForQuestionAnswering, + LlamaForSequenceClassification, + LlamaForTokenClassification, + LlamaMLP, + LlamaModel, + LlamaPreTrainedModel, + LlamaRMSNorm, + LlamaRotaryEmbedding, + ) + + + class MyTestConfig(LlamaConfig): + pass + + + class MyTestRMSNorm(LlamaRMSNorm): + pass + + + class MyTestRotaryEmbedding(LlamaRotaryEmbedding): + pass + + + class MyTestMLP(LlamaMLP): + pass + + + class MyTestAttention(LlamaAttention): + pass + + + class MyTestDecoderLayer(LlamaDecoderLayer): + pass + + + class MyTestPreTrainedModel(LlamaPreTrainedModel): + pass + + + class MyTestModel(LlamaModel): + pass + + + class MyTestForCausalLM(LlamaForCausalLM): + pass + + + class MyTestForSequenceClassification(LlamaForSequenceClassification): + pass + + + class MyTestForQuestionAnswering(LlamaForQuestionAnswering): + pass + + + class MyTestForTokenClassification(LlamaForTokenClassification): + pass + + + __all__ = [ + "MyTestConfig", + "MyTestForCausalLM", + "MyTestModel", + "MyTestPreTrainedModel", + "MyTestForSequenceClassification", + "MyTestForQuestionAnswering", + "MyTestForTokenClassification", + ] + """ + ) + self.assertFileIsEqual(EXPECTED_MODULAR, os.path.join(model_repo, "modular_my_test.py")) + + EXPECTED_INIT = textwrap.dedent( + f""" + # coding=utf-8 + # Copyright {CURRENT_YEAR} 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. + + from typing import TYPE_CHECKING + + from ...utils import _LazyModule + from ...utils.import_utils import define_import_structure + + + if TYPE_CHECKING: + from .configuration_my_test import * + from .modeling_my_test import * + else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) + + """ + ) + self.assertFileIsEqual(EXPECTED_INIT, os.path.join(model_repo, "__init__.py")) + + EXPECTED_DOC = textwrap.dedent( + f""" + + + + # MyTest + + ## Overview + + The MyTest model was proposed in []() by . + + + The abstract from the paper is the following: + + + + Tips: + + + + This model was contributed by [INSERT YOUR HF USERNAME HERE](https://huggingface.co/). + The original code can be found [here](). + + ## Usage examples + + + + ## MyTestConfig + + [[autodoc]] MyTestConfig + + ## MyTestForCausalLM + + [[autodoc]] MyTestForCausalLM + + ## MyTestModel + + [[autodoc]] MyTestModel + - forward + + ## MyTestPreTrainedModel + + [[autodoc]] MyTestPreTrainedModel + - forward + + ## MyTestForSequenceClassification + + [[autodoc]] MyTestForSequenceClassification + + ## MyTestForQuestionAnswering + + [[autodoc]] MyTestForQuestionAnswering + + ## MyTestForTokenClassification + + [[autodoc]] MyTestForTokenClassification + """ + ) + self.assertFileIsEqual(EXPECTED_DOC, os.path.join(self.DOC_PATH, "model_doc", "my_test.md")) + + def test_phi4_with_all_processors(self): + # This is the structure without adding the tokenizers + filenames_to_add = ( + ("configuration_phi4_multimodal.py", True), + ("modeling_phi4_multimodal.py", True), + ("tokenization_phi4_multimodal.py", False), + ("tokenization_phi4_multimodal_fast.py", False), + ("image_processing_phi4_multimodal.py", False), + ("image_processing_phi4_multimodal_fast.py", True), + ("video_processing_phi4_multimodal.py", False), + ("feature_extraction_phi4_multimodal.py", True), + ("processing_phi4_multimodal.py", True), + ) + # Run the command + create_new_model_like( + old_model_infos=ModelInfos("phi4_multimodal"), + new_lowercase_name="my_test2", + new_model_paper_name="MyTest2", + filenames_to_add=filenames_to_add, + create_fast_image_processor=False, + ) + + # First assert that all files were created correctly + model_repo = os.path.join(self.MODEL_PATH, "my_test2") + tests_repo = os.path.join(self.TESTS_MODEL_PATH, "my_test2") + self.assertTrue(os.path.isfile(os.path.join(model_repo, "modular_my_test2.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "modeling_my_test2.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "configuration_my_test2.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "image_processing_my_test2_fast.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "feature_extraction_my_test2.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "processing_my_test2.py"))) + self.assertTrue(os.path.isfile(os.path.join(model_repo, "__init__.py"))) + self.assertTrue(os.path.isfile(os.path.join(self.DOC_PATH, "model_doc", "my_test2.md"))) + self.assertTrue(os.path.isfile(os.path.join(tests_repo, "__init__.py"))) + self.assertTrue(os.path.isfile(os.path.join(tests_repo, "test_modeling_my_test2.py"))) + self.assertTrue(os.path.isfile(os.path.join(tests_repo, "test_feature_extraction_my_test2.py"))) + self.assertTrue(os.path.isfile(os.path.join(tests_repo, "test_image_processing_my_test2.py"))) + + # Now assert the correct imports/auto mappings/toctree were added + self.assertInFile( + "from .my_test2 import *\n", + os.path.join(self.MODEL_PATH, "__init__.py"), + ) + self.assertInFile( + '("my_test2", "MyTest2Config"),\n', + os.path.join(self.MODEL_PATH, "auto", "configuration_auto.py"), + ) + self.assertInFile( + '("my_test2", "MyTest2"),\n', + os.path.join(self.MODEL_PATH, "auto", "configuration_auto.py"), + ) + self.assertInFile( + '("my_test2", "MyTest2Model"),\n', + os.path.join(self.MODEL_PATH, "auto", "modeling_auto.py"), + ) + self.assertInFile( + '("my_test2", "MyTest2ForCausalLM"),\n', + os.path.join(self.MODEL_PATH, "auto", "modeling_auto.py"), + ) + self.assertInFile( + '("my_test2", (None, "MyTest2ImageProcessorFast")),\n', + os.path.join(self.MODEL_PATH, "auto", "image_processing_auto.py"), + ) + self.assertInFile( + '("my_test2", "MyTest2FeatureExtractor"),\n', + os.path.join(self.MODEL_PATH, "auto", "feature_extraction_auto.py"), + ) + self.assertInFile( + '("my_test2", "MyTest2Processor"),\n', + os.path.join(self.MODEL_PATH, "auto", "processing_auto.py"), + ) + self.assertInFile( + "- local: model_doc/my_test2\n title: MyTest2\n", + os.path.join(self.DOC_PATH, "_toctree.yml"), + ) + + # Check some exact file creation. For model definition, only check modular as modeling/config/etc... are created + # directly from it + EXPECTED_MODULAR = textwrap.dedent( + f""" + # coding=utf-8 + # Copyright {CURRENT_YEAR} 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. + + from ..phi4_multimodal.configuration_phi4_multimodal import ( + Phi4MultimodalAudioConfig, + Phi4MultimodalConfig, + Phi4MultimodalVisionConfig, + ) + from ..phi4_multimodal.feature_extraction_phi4_multimodal import Phi4MultimodalFeatureExtractor + from ..phi4_multimodal.image_processing_phi4_multimodal_fast import ( + Phi4MultimodalFastImageProcessorKwargs, + Phi4MultimodalImageProcessorFast, + ) + from ..phi4_multimodal.modeling_phi4_multimodal import ( + Phi4MultimodalAttention, + Phi4MultimodalAudioAttention, + Phi4MultimodalAudioConformerEncoderLayer, + Phi4MultimodalAudioConvModule, + Phi4MultimodalAudioDepthWiseSeperableConv1d, + Phi4MultimodalAudioEmbedding, + Phi4MultimodalAudioGluPointWiseConv, + Phi4MultimodalAudioMeanVarianceNormLayer, + Phi4MultimodalAudioMLP, + Phi4MultimodalAudioModel, + Phi4MultimodalAudioNemoConvSubsampling, + Phi4MultimodalAudioPreTrainedModel, + Phi4MultimodalAudioRelativeAttentionBias, + Phi4MultimodalDecoderLayer, + Phi4MultimodalFeatureEmbedding, + Phi4MultimodalForCausalLM, + Phi4MultimodalImageEmbedding, + Phi4MultimodalMLP, + Phi4MultimodalModel, + Phi4MultimodalPreTrainedModel, + Phi4MultimodalRMSNorm, + Phi4MultimodalRotaryEmbedding, + Phi4MultimodalVisionAttention, + Phi4MultimodalVisionEmbeddings, + Phi4MultimodalVisionEncoder, + Phi4MultimodalVisionEncoderLayer, + Phi4MultimodalVisionMLP, + Phi4MultimodalVisionModel, + Phi4MultimodalVisionMultiheadAttentionPoolingHead, + Phi4MultimodalVisionPreTrainedModel, + ) + from ..phi4_multimodal.processing_phi4_multimodal import Phi4MultimodalProcessor, Phi4MultimodalProcessorKwargs + + + class MyTest2VisionConfig(Phi4MultimodalVisionConfig): + pass + + + class MyTest2AudioConfig(Phi4MultimodalAudioConfig): + pass + + + class MyTest2Config(Phi4MultimodalConfig): + pass + + + class MyTest2VisionMLP(Phi4MultimodalVisionMLP): + pass + + + class MyTest2VisionAttention(Phi4MultimodalVisionAttention): + pass + + + class MyTest2VisionEncoderLayer(Phi4MultimodalVisionEncoderLayer): + pass + + + class MyTest2VisionEncoder(Phi4MultimodalVisionEncoder): + pass + + + class MyTest2VisionPreTrainedModel(Phi4MultimodalVisionPreTrainedModel): + pass + + + class MyTest2VisionEmbeddings(Phi4MultimodalVisionEmbeddings): + pass + + + class MyTest2VisionMultiheadAttentionPoolingHead(Phi4MultimodalVisionMultiheadAttentionPoolingHead): + pass + + + class MyTest2VisionModel(Phi4MultimodalVisionModel): + pass + + + class MyTest2ImageEmbedding(Phi4MultimodalImageEmbedding): + pass + + + class MyTest2AudioMLP(Phi4MultimodalAudioMLP): + pass + + + class MyTest2AudioAttention(Phi4MultimodalAudioAttention): + pass + + + class MyTest2AudioDepthWiseSeperableConv1d(Phi4MultimodalAudioDepthWiseSeperableConv1d): + pass + + + class MyTest2AudioGluPointWiseConv(Phi4MultimodalAudioGluPointWiseConv): + pass + + + class MyTest2AudioConvModule(Phi4MultimodalAudioConvModule): + pass + + + class MyTest2AudioConformerEncoderLayer(Phi4MultimodalAudioConformerEncoderLayer): + pass + + + class MyTest2AudioNemoConvSubsampling(Phi4MultimodalAudioNemoConvSubsampling): + pass + + + class MyTest2AudioRelativeAttentionBias(Phi4MultimodalAudioRelativeAttentionBias): + pass + + + class MyTest2AudioMeanVarianceNormLayer(Phi4MultimodalAudioMeanVarianceNormLayer): + pass + + + class MyTest2AudioPreTrainedModel(Phi4MultimodalAudioPreTrainedModel): + pass + + + class MyTest2AudioModel(Phi4MultimodalAudioModel): + pass + + + class MyTest2AudioEmbedding(Phi4MultimodalAudioEmbedding): + pass + + + class MyTest2RMSNorm(Phi4MultimodalRMSNorm): + pass + + + class MyTest2MLP(Phi4MultimodalMLP): + pass + + + class MyTest2Attention(Phi4MultimodalAttention): + pass + + + class MyTest2DecoderLayer(Phi4MultimodalDecoderLayer): + pass + + + class MyTest2FeatureEmbedding(Phi4MultimodalFeatureEmbedding): + pass + + + class MyTest2RotaryEmbedding(Phi4MultimodalRotaryEmbedding): + pass + + + class MyTest2PreTrainedModel(Phi4MultimodalPreTrainedModel): + pass + + + class MyTest2Model(Phi4MultimodalModel): + pass + + + class MyTest2ForCausalLM(Phi4MultimodalForCausalLM): + pass + + + class MyTest2FastImageProcessorKwargs(Phi4MultimodalFastImageProcessorKwargs): + pass + + + class MyTest2ImageProcessorFast(Phi4MultimodalImageProcessorFast): + pass + + + class MyTest2FeatureExtractor(Phi4MultimodalFeatureExtractor): + pass + + + class MyTest2ProcessorKwargs(Phi4MultimodalProcessorKwargs): + pass + + + class MyTest2Processor(Phi4MultimodalProcessor): + pass + + + __all__ = [ + "MyTest2VisionConfig", + "MyTest2AudioConfig", + "MyTest2Config", + "MyTest2AudioPreTrainedModel", + "MyTest2AudioModel", + "MyTest2VisionPreTrainedModel", + "MyTest2VisionModel", + "MyTest2PreTrainedModel", + "MyTest2Model", + "MyTest2ForCausalLM", + "MyTest2ImageProcessorFast", + "MyTest2FeatureExtractor", + "MyTest2Processor", + ] + """ + ) + self.assertFileIsEqual(EXPECTED_MODULAR, os.path.join(model_repo, "modular_my_test2.py")) + + EXPECTED_INIT = textwrap.dedent( + f""" + # coding=utf-8 + # Copyright {CURRENT_YEAR} 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. + + from typing import TYPE_CHECKING + + from ...utils import _LazyModule + from ...utils.import_utils import define_import_structure + + + if TYPE_CHECKING: + from .configuration_my_test2 import * + from .feature_extraction_my_test2 import * + from .image_processing_my_test2_fast import * + from .modeling_my_test2 import * + from .processing_my_test2 import * + else: + import sys + + _file = globals()["__file__"] + sys.modules[__name__] = _LazyModule(__name__, _file, define_import_structure(_file), module_spec=__spec__) + """ + ) + self.assertFileIsEqual(EXPECTED_INIT, os.path.join(model_repo, "__init__.py")) + + EXPECTED_DOC = textwrap.dedent( + f""" + + + + # MyTest2 + + ## Overview + + The MyTest2 model was proposed in []() by . + + + The abstract from the paper is the following: + + + + Tips: + + + + This model was contributed by [INSERT YOUR HF USERNAME HERE](https://huggingface.co/). + The original code can be found [here](). + + ## Usage examples + + + + ## MyTest2VisionConfig + + [[autodoc]] MyTest2VisionConfig + + ## MyTest2AudioConfig + + [[autodoc]] MyTest2AudioConfig + + ## MyTest2Config + + [[autodoc]] MyTest2Config + + ## MyTest2AudioPreTrainedModel + + [[autodoc]] MyTest2AudioPreTrainedModel + - forward + + ## MyTest2AudioModel + + [[autodoc]] MyTest2AudioModel + - forward + + ## MyTest2VisionPreTrainedModel + + [[autodoc]] MyTest2VisionPreTrainedModel + - forward + + ## MyTest2VisionModel + + [[autodoc]] MyTest2VisionModel + - forward + + ## MyTest2PreTrainedModel + + [[autodoc]] MyTest2PreTrainedModel + - forward + + ## MyTest2Model + + [[autodoc]] MyTest2Model + - forward + + ## MyTest2ForCausalLM + + [[autodoc]] MyTest2ForCausalLM + + ## MyTest2ImageProcessorFast + + [[autodoc]] MyTest2ImageProcessorFast + + ## MyTest2FeatureExtractor + + [[autodoc]] MyTest2FeatureExtractor + + ## MyTest2Processor + + [[autodoc]] MyTest2Processor + """ + ) + self.assertFileIsEqual(EXPECTED_DOC, os.path.join(self.DOC_PATH, "model_doc", "my_test2.md")) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_audio_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_audio_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..4d0459d9a8b0eba5b61b08f7b08f04cd8e0ccf8d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_audio_utils.py @@ -0,0 +1,1751 @@ +# Copyright 2023 HuggingFace 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. + +import unittest + +import numpy as np +import pytest + +from transformers.audio_utils import ( + amplitude_to_db, + amplitude_to_db_batch, + chroma_filter_bank, + hertz_to_mel, + mel_filter_bank, + mel_to_hertz, + power_to_db, + power_to_db_batch, + spectrogram, + spectrogram_batch, + window_function, +) +from transformers.testing_utils import is_librosa_available, require_librosa + + +if is_librosa_available(): + from librosa.filters import chroma + + +class AudioUtilsFunctionTester(unittest.TestCase): + # will be set in `def _load_datasamples` + _dataset = None + + def test_hertz_to_mel(self): + self.assertEqual(hertz_to_mel(0.0), 0.0) + self.assertAlmostEqual(hertz_to_mel(100), 150.48910241) + + inputs = np.array([100, 200]) + expected = np.array([150.48910241, 283.22989816]) + self.assertTrue(np.allclose(hertz_to_mel(inputs), expected)) + + self.assertEqual(hertz_to_mel(0.0, "slaney"), 0.0) + self.assertEqual(hertz_to_mel(100, "slaney"), 1.5) + + inputs = np.array([60, 100, 200, 1000, 1001, 2000]) + expected = np.array([0.9, 1.5, 3.0, 15.0, 15.01453781, 25.08188016]) + self.assertTrue(np.allclose(hertz_to_mel(inputs, "slaney"), expected)) + + inputs = np.array([60, 100, 200, 1000, 1001, 2000]) + expected = np.array([92.6824, 150.4899, 283.2313, 999.9907, 1000.6534, 1521.3674]) + self.assertTrue(np.allclose(hertz_to_mel(inputs, "kaldi"), expected)) + + with pytest.raises(ValueError): + hertz_to_mel(100, mel_scale=None) + + def test_mel_to_hertz(self): + self.assertEqual(mel_to_hertz(0.0), 0.0) + self.assertAlmostEqual(mel_to_hertz(150.48910241), 100) + + inputs = np.array([150.48910241, 283.22989816]) + expected = np.array([100, 200]) + self.assertTrue(np.allclose(mel_to_hertz(inputs), expected)) + + self.assertEqual(mel_to_hertz(0.0, "slaney"), 0.0) + self.assertEqual(mel_to_hertz(1.5, "slaney"), 100) + + inputs = np.array([0.9, 1.5, 3.0, 15.0, 15.01453781, 25.08188016]) + expected = np.array([60, 100, 200, 1000, 1001, 2000]) + self.assertTrue(np.allclose(mel_to_hertz(inputs, "slaney"), expected)) + + inputs = np.array([92.6824, 150.4899, 283.2313, 999.9907, 1000.6534, 1521.3674]) + expected = np.array([60, 100, 200, 1000, 1001, 2000]) + self.assertTrue(np.allclose(mel_to_hertz(inputs, "kaldi"), expected)) + + with pytest.raises(ValueError): + mel_to_hertz(100, mel_scale=None) + + def test_mel_filter_bank_shape(self): + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm=None, + mel_scale="htk", + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm="slaney", + mel_scale="slaney", + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm="slaney", + mel_scale="slaney", + triangularize_in_mel_space=True, + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + def test_mel_filter_bank_htk(self): + mel_filters = mel_filter_bank( + num_frequency_bins=16, + num_mel_filters=4, + min_frequency=0, + max_frequency=2000, + sampling_rate=4000, + norm=None, + mel_scale="htk", + ) + # fmt: off + expected = np.array([ + [0.0 , 0.0 , 0.0 , 0.0 ], + [0.61454786, 0.0 , 0.0 , 0.0 ], + [0.82511046, 0.17488954, 0.0 , 0.0 ], + [0.35597035, 0.64402965, 0.0 , 0.0 ], + [0.0 , 0.91360726, 0.08639274, 0.0 ], + [0.0 , 0.55547007, 0.44452993, 0.0 ], + [0.0 , 0.19733289, 0.80266711, 0.0 ], + [0.0 , 0.0 , 0.87724349, 0.12275651], + [0.0 , 0.0 , 0.6038449 , 0.3961551 ], + [0.0 , 0.0 , 0.33044631, 0.66955369], + [0.0 , 0.0 , 0.05704771, 0.94295229], + [0.0 , 0.0 , 0.0 , 0.83483975], + [0.0 , 0.0 , 0.0 , 0.62612982], + [0.0 , 0.0 , 0.0 , 0.41741988], + [0.0 , 0.0 , 0.0 , 0.20870994], + [0.0 , 0.0 , 0.0 , 0.0 ] + ]) + # fmt: on + self.assertTrue(np.allclose(mel_filters, expected)) + + def test_mel_filter_bank_slaney(self): + mel_filters = mel_filter_bank( + num_frequency_bins=16, + num_mel_filters=4, + min_frequency=0, + max_frequency=2000, + sampling_rate=4000, + norm=None, + mel_scale="slaney", + ) + # fmt: off + expected = np.array([ + [0.0 , 0.0 , 0.0 , 0.0 ], + [0.39869419, 0.0 , 0.0 , 0.0 ], + [0.79738839, 0.0 , 0.0 , 0.0 ], + [0.80391742, 0.19608258, 0.0 , 0.0 ], + [0.40522322, 0.59477678, 0.0 , 0.0 ], + [0.00652903, 0.99347097, 0.0 , 0.0 ], + [0.0 , 0.60796161, 0.39203839, 0.0 ], + [0.0 , 0.20939631, 0.79060369, 0.0 ], + [0.0 , 0.0 , 0.84685344, 0.15314656], + [0.0 , 0.0 , 0.52418477, 0.47581523], + [0.0 , 0.0 , 0.2015161 , 0.7984839 ], + [0.0 , 0.0 , 0.0 , 0.9141874 ], + [0.0 , 0.0 , 0.0 , 0.68564055], + [0.0 , 0.0 , 0.0 , 0.4570937 ], + [0.0 , 0.0 , 0.0 , 0.22854685], + [0.0 , 0.0 , 0.0 , 0.0 ] + ]) + # fmt: on + self.assertTrue(np.allclose(mel_filters, expected)) + + def test_mel_filter_bank_kaldi(self): + mel_filters = mel_filter_bank( + num_frequency_bins=16, + num_mel_filters=4, + min_frequency=0, + max_frequency=2000, + sampling_rate=4000, + norm=None, + mel_scale="kaldi", + triangularize_in_mel_space=True, + ) + # fmt: off + # here the expected values from torchaudio.compliance.kaldi.get_mel_banks + # note that we compute values in float64 while they do it in float32 + expected = np.array( + [ + [0.0000000000000000, 0.0000000000000000, 0.0000000000000000, 0.0000000000000000], + [0.6457883715629578, 0.0000000000000000, 0.0000000000000000, 0.0000000000000000], + [0.8044781088829041, 0.1955219060182571, 0.0000000000000000, 0.0000000000000000], + [0.3258901536464691, 0.6741098165512085, 0.0000000000000000, 0.0000000000000000], + [0.0000000000000000, 0.9021250009536743, 0.0978749766945839, 0.0000000000000000], + [0.0000000000000000, 0.5219038724899292, 0.4780961275100708, 0.0000000000000000], + [0.0000000000000000, 0.1771058291196823, 0.8228941559791565, 0.0000000000000000], + [0.0000000000000000, 0.0000000000000000, 0.8616894483566284, 0.1383105516433716], + [0.0000000000000000, 0.0000000000000000, 0.5710380673408508, 0.4289619624614716], + [0.0000000000000000, 0.0000000000000000, 0.3015440106391907, 0.6984559893608093], + [0.0000000000000000, 0.0000000000000000, 0.0503356307744980, 0.9496643543243408], + [0.0000000000000000, 0.0000000000000000, 0.0000000000000000, 0.8150880336761475], + [0.0000000000000000, 0.0000000000000000, 0.0000000000000000, 0.5938932299613953], + [0.0000000000000000, 0.0000000000000000, 0.0000000000000000, 0.3851676583290100], + [0.0000000000000000, 0.0000000000000000, 0.0000000000000000, 0.1875794380903244], + ], + dtype=np.float64, + ) + # fmt: on + + # kaldi implementation does not compute values for last fft bin + # indeed, they enforce max_frequency <= sampling_rate / 2 and + # therefore they know that last fft bin filter bank values will be all 0 + # and pad after with zeros + # to comply with our API for `mel_filter_bank`, we need to also pad here + expected = np.pad(expected, ((0, 1), (0, 0))) + + self.assertTrue(np.allclose(mel_filters, expected)) + + def test_mel_filter_bank_slaney_norm(self): + mel_filters = mel_filter_bank( + num_frequency_bins=16, + num_mel_filters=4, + min_frequency=0, + max_frequency=2000, + sampling_rate=4000, + norm="slaney", + mel_scale="slaney", + ) + # fmt: off + expected = np.array([ + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], + [1.19217795e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], + [2.38435591e-03, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00], + [2.40387905e-03, 5.86232616e-04, 0.00000000e+00, 0.00000000e+00], + [1.21170110e-03, 1.77821783e-03, 0.00000000e+00, 0.00000000e+00], + [1.95231437e-05, 2.97020305e-03, 0.00000000e+00, 0.00000000e+00], + [0.00000000e+00, 1.81763684e-03, 1.04857612e-03, 0.00000000e+00], + [0.00000000e+00, 6.26036972e-04, 2.11460963e-03, 0.00000000e+00], + [0.00000000e+00, 0.00000000e+00, 2.26505954e-03, 3.07332945e-04], + [0.00000000e+00, 0.00000000e+00, 1.40202503e-03, 9.54861093e-04], + [0.00000000e+00, 0.00000000e+00, 5.38990521e-04, 1.60238924e-03], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.83458185e-03], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 1.37593638e-03], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 9.17290923e-04], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 4.58645462e-04], + [0.00000000e+00, 0.00000000e+00, 0.00000000e+00, 0.00000000e+00] + ]) + # fmt: on + self.assertTrue(np.allclose(mel_filters, expected)) + + def test_window_function(self): + window = window_function(16, "hann") + self.assertEqual(len(window), 16) + + # fmt: off + expected = np.array([ + 0.0, 0.03806023, 0.14644661, 0.30865828, 0.5, 0.69134172, 0.85355339, 0.96193977, + 1.0, 0.96193977, 0.85355339, 0.69134172, 0.5, 0.30865828, 0.14644661, 0.03806023, + ]) + # fmt: on + self.assertTrue(np.allclose(window, expected)) + + def _load_datasamples(self, num_samples): + from datasets import load_dataset + + if self._dataset is None: + self._dataset = load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + speech_samples = self._dataset.sort("id")[:num_samples]["audio"] + return [x["array"] for x in speech_samples] + + def test_spectrogram_impulse(self): + waveform = np.zeros(40) + waveform[9] = 1.0 # impulse shifted in time + + spec = spectrogram( + waveform, + window_function(12, "hann", frame_length=16), + frame_length=16, + hop_length=4, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (9, 11)) + + expected = np.array([[0.0, 0.0669873, 0.9330127, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) + self.assertTrue(np.allclose(spec, expected)) + + def test_spectrogram_batch_impulse(self): + waveform1 = np.zeros(40) + waveform1[9] = 1.0 + + waveform2 = np.zeros(28) + waveform2[12] = 3.0 + + waveform3 = np.zeros(51) + waveform3[26] = 4.5 + + waveform_list = [waveform1, waveform2, waveform3] + + spec_list = spectrogram_batch( + waveform_list, + window_function(12, "hann", frame_length=16), + frame_length=16, + hop_length=4, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + + self.assertEqual(spec_list[0].shape, (9, 11)) + self.assertEqual(spec_list[1].shape, (9, 8)) + self.assertEqual(spec_list[2].shape, (9, 13)) + + expected1 = np.array([[0.0, 0.0669873, 0.9330127, 0.5, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]]) + expected2 = np.array([[0.0, 0.0, 0.75, 3.0, 0.75, 0.0, 0.0, 0.0]]) + expected3 = np.array([[0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 3.375, 3.375, 0.0, 0.0, 0.0, 0.0, 0.0]]) + + self.assertTrue(np.allclose(spec_list[0], expected1)) + self.assertTrue(np.allclose(spec_list[1], expected2)) + self.assertTrue(np.allclose(spec_list[2], expected3)) + + def test_spectrogram_integration_test(self): + waveform = self._load_datasamples(1)[0] + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (257, 732)) + + # fmt: off + expected = np.array([ + 0.02464888, 0.04648664, 0.05872392, 0.02311783, 0.0327175 , + 0.02433643, 0.01198814, 0.02055709, 0.01559287, 0.01394357, + 0.01299037, 0.01728045, 0.0254554 , 0.02486533, 0.02011792, + 0.01755333, 0.02100457, 0.02337024, 0.01436963, 0.01464558, + 0.0211017 , 0.0193489 , 0.01272165, 0.01858462, 0.03722598, + 0.0456542 , 0.03281558, 0.00620586, 0.02226466, 0.03618042, + 0.03508182, 0.02271432, 0.01051649, 0.01225771, 0.02315293, + 0.02331886, 0.01417785, 0.0106844 , 0.01791214, 0.017177 , + 0.02125114, 0.05028201, 0.06830665, 0.05216664, 0.01963666, + 0.06941418, 0.11513043, 0.12257859, 0.10948435, 0.08568069, + 0.05509328, 0.05047818, 0.047112 , 0.05060737, 0.02982424, + 0.02803827, 0.02933729, 0.01760491, 0.00587815, 0.02117637, + 0.0293578 , 0.03452379, 0.02194803, 0.01676056, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 400], expected)) + + spec = spectrogram( + waveform, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + fft_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (257, 732)) + self.assertTrue(np.allclose(spec[:64, 400], expected)) + + mel_filters = mel_filter_bank( + num_frequency_bins=257, + num_mel_filters=400, + min_frequency=20, + max_frequency=8000, + sampling_rate=16000, + norm=None, + mel_scale="kaldi", + triangularize_in_mel_space=True, + ) + + spec = spectrogram( + waveform, + window_function(400, "povey", periodic=False), + frame_length=400, + hop_length=160, + fft_length=512, + power=2.0, + center=False, + pad_mode="reflect", + onesided=True, + preemphasis=0.97, + mel_filters=mel_filters, + log_mel="log", + mel_floor=1.1920928955078125e-07, + remove_dc_offset=True, + ) + self.assertEqual(spec.shape, (400, 584)) + + # fmt: off + expected = np.array([-15.94238515, -8.20712299, -8.22704352, -15.94238515, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -6.52463769, -7.73677889, -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -4.18650018, -3.37195286, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -4.70190154, -2.4217066 , -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -5.62755239, -3.53385194, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -9.43303023, -8.77480925, -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -4.2951092 , -5.51585994, + -15.94238515, -15.94238515, -15.94238515, -4.40151721, + -3.95228878, -15.94238515, -15.94238515, -15.94238515, + -6.10365415, -4.59494697, -15.94238515, -15.94238515, + -15.94238515, -8.10727767, -6.2585298 , -15.94238515, + -15.94238515, -15.94238515, -5.60161702, -4.47217004, + -15.94238515, -15.94238515, -15.94238515, -5.91641988] + ) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 400], expected, atol=1e-5)) + + def test_spectrogram_batch_integration_test(self): + waveform_list = self._load_datasamples(3) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec_list[0].shape, (257, 732)) + self.assertEqual(spec_list[1].shape, (257, 602)) + self.assertEqual(spec_list[2].shape, (257, 1561)) + + # fmt: off + expected1 = np.array([ + 0.02464888, 0.04648664, 0.05872392, 0.02311783, 0.0327175 , + 0.02433643, 0.01198814, 0.02055709, 0.01559287, 0.01394357, + 0.01299037, 0.01728045, 0.0254554 , 0.02486533, 0.02011792, + 0.01755333, 0.02100457, 0.02337024, 0.01436963, 0.01464558, + 0.0211017 , 0.0193489 , 0.01272165, 0.01858462, 0.03722598, + 0.0456542 , 0.03281558, 0.00620586, 0.02226466, 0.03618042, + 0.03508182, 0.02271432, 0.01051649, 0.01225771, 0.02315293, + 0.02331886, 0.01417785, 0.0106844 , 0.01791214, 0.017177 , + 0.02125114, 0.05028201, 0.06830665, 0.05216664, 0.01963666, + 0.06941418, 0.11513043, 0.12257859, 0.10948435, 0.08568069, + 0.05509328, 0.05047818, 0.047112 , 0.05060737, 0.02982424, + 0.02803827, 0.02933729, 0.01760491, 0.00587815, 0.02117637, + 0.0293578 , 0.03452379, 0.02194803, 0.01676056, + ]) + expected2 = np.array([ + 7.61983171e-02, 1.45338190e-01, 2.63903728e+00, 7.74429535e+00, + 9.61932980e+00, 5.40767686e+00, 1.08924884e+00, 3.40908262e+00, + 3.59484250e+00, 1.68451077e+00, 5.88405873e-01, 1.17042530e+00, + 9.94803324e-01, 3.53757065e-01, 5.47699239e-01, 9.48368581e-01, + 7.17770457e-01, 2.09396633e-01, 1.77574463e-01, 2.35644731e-01, + 1.31535991e-01, 1.53539552e-02, 4.34416305e-02, 5.32897267e-02, + 4.03567305e-02, 1.41842226e-02, 2.90514538e-02, 3.36549485e-02, + 1.53516624e-02, 2.37464225e-02, 4.60092464e-02, 4.05769324e-02, + 4.82633401e-03, 4.12675364e-02, 7.13859796e-02, 6.16866566e-02, + 2.55657822e-02, 1.68923281e-02, 1.91299946e-02, 1.60033798e-02, + 1.33405095e-02, 1.52065457e-02, 1.21833352e-02, 2.25786382e-03, + 6.15358376e-03, 1.07647616e-02, 1.23051018e-02, 6.75289378e-03, + 2.71127435e-03, 1.06515263e-02, 1.18463583e-02, 7.14347935e-03, + 1.87912782e-03, 4.44236027e-03, 5.19630243e-03, 2.46666998e-03, + 1.01598645e-03, 1.21589237e-03, 1.29095500e-03, 1.07447628e-03, + 1.40218156e-03, 3.65402623e-03, 4.00592755e-03, 4.20001841e-03 + ]) + expected3 = np.array([ + 0.07805249, 0.34305022, 0.55617084, 1.22475182, 1.17040678, + 0.51540532, 0.23570016, 0.06630775, 0.09017777, 0.07693192, + 0.0333643 , 0.04873054, 0.04668559, 0.02384041, 0.02780435, + 0.0289717 , 0.01704903, 0.0201644 , 0.01700376, 0.02176975, + 0.02042491, 0.00732129, 0.00326042, 0.00245065, 0.00510645, + 0.00681892, 0.00739329, 0.00551437, 0.0070674 , 0.00630015, + 0.00379566, 0.0060098 , 0.00311543, 0.00902284, 0.01171038, + 0.01202166, 0.01759194, 0.01652899, 0.01201872, 0.01295351, + 0.00756432, 0.01415318, 0.02349972, 0.02296833, 0.02429341, + 0.02447459, 0.01835044, 0.01437871, 0.02262246, 0.02972324, + 0.03392252, 0.03037546, 0.01116927, 0.01555062, 0.02833379, + 0.02294212, 0.02069847, 0.02496927, 0.02273526, 0.01341643, + 0.00805407, 0.00624943, 0.01076262, 0.01876003 + ]) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][:64, 400], expected1)) + self.assertTrue(np.allclose(spec_list[1][:64, 400], expected2)) + self.assertTrue(np.allclose(spec_list[2][:64, 400], expected3)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + fft_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec_list[0].shape, (257, 732)) + self.assertEqual(spec_list[1].shape, (257, 602)) + self.assertEqual(spec_list[2].shape, (257, 1561)) + self.assertTrue(np.allclose(spec_list[0][:64, 400], expected1)) + self.assertTrue(np.allclose(spec_list[1][:64, 400], expected2)) + self.assertTrue(np.allclose(spec_list[2][:64, 400], expected3)) + + mel_filters = mel_filter_bank( + num_frequency_bins=257, + num_mel_filters=400, + min_frequency=20, + max_frequency=8000, + sampling_rate=16000, + norm=None, + mel_scale="kaldi", + triangularize_in_mel_space=True, + ) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "povey", periodic=False), + frame_length=400, + hop_length=160, + fft_length=512, + power=2.0, + center=False, + pad_mode="reflect", + onesided=True, + preemphasis=0.97, + mel_filters=mel_filters, + log_mel="log", + mel_floor=1.1920928955078125e-07, + remove_dc_offset=True, + ) + self.assertEqual(spec_list[0].shape, (400, 584)) + self.assertEqual(spec_list[1].shape, (400, 480)) + self.assertEqual(spec_list[2].shape, (400, 1247)) + + # fmt: off + expected1 = np.array([-15.94238515, -8.20712299, -8.22704352, -15.94238515, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -6.52463769, -7.73677889, -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -4.18650018, -3.37195286, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -4.70190154, -2.4217066 , -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -5.62755239, -3.53385194, + -15.94238515, -15.94238515, -15.94238515, -15.94238515, + -9.43303023, -8.77480925, -15.94238515, -15.94238515, + -15.94238515, -15.94238515, -4.2951092 , -5.51585994, + -15.94238515, -15.94238515, -15.94238515, -4.40151721, + -3.95228878, -15.94238515, -15.94238515, -15.94238515, + -6.10365415, -4.59494697, -15.94238515, -15.94238515, + -15.94238515, -8.10727767, -6.2585298 , -15.94238515, + -15.94238515, -15.94238515, -5.60161702, -4.47217004, + -15.94238515, -15.94238515, -15.94238515, -5.91641988] + ) + expected2 = np.array([-15.942385, -8.531508, -8.551396, -15.942385, -15.942385, + -15.942385, -15.942385, -15.942385, -5.626043, -6.8381968, + -15.942385, -15.942385, -15.942385, -15.942385, -3.3122184, + -2.49764, -15.942385, -15.942385, -15.942385, -15.942385, + -3.625868, -1.3457257, -15.942385, -15.942385, -15.942385, + -15.942385, -4.2223063, -2.1285915, -15.942385, -15.942385, + -15.942385, -15.942385, -8.611152, -7.952894, -15.942385, + -15.942385, -15.942385, -15.942385, -2.7585578, -3.9793255, + -15.942385, -15.942385, -15.942385, -2.5377562, -2.0885658, + -15.942385, -15.942385, -15.942385, -3.8310733, -2.322393, + -15.942385, -15.942385, -15.942385, -7.674944, -5.8261633, + -15.942385, -15.942385, -15.942385, -3.5960004, -2.4665844, + -15.942385, -15.942385, -15.942385, -1.7905309] + ) + expected3 = np.array([-15.942385, -13.406995, -13.426883, -15.942385, -15.942385, + -15.942385, -15.942385, -15.942385, -15.942385, -15.942385, + -15.942385, -15.942385, -15.942385, -15.942385, -13.493383, + -12.678805, -15.942385, -15.942385, -15.942385, -15.942385, + -14.809377, -12.529235, -15.942385, -15.942385, -15.942385, + -15.942385, -13.838827, -11.745112, -15.942385, -15.942385, + -15.942385, -15.942385, -13.9336405, -13.275384, -15.942385, + -15.942385, -15.942385, -15.942385, -13.043786, -14.264554, + -15.942385, -15.942385, -15.942385, -13.060181, -12.610991, + -15.942385, -15.942385, -15.942385, -14.152064, -12.643384, + -15.942385, -15.942385, -15.942385, -14.48317, -12.634389, + -15.942385, -15.942385, -15.942385, -14.627316, -13.4979, + -15.942385, -15.942385, -15.942385, -12.6279955] + ) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][:64, 400], expected1, atol=1e-5)) + self.assertTrue(np.allclose(spec_list[1][:64, 400], expected2, atol=1e-5)) + self.assertTrue(np.allclose(spec_list[2][:64, 400], expected3, atol=1e-5)) + + def test_spectrogram_center_padding(self): + waveform = self._load_datasamples(1)[0] + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=True, + pad_mode="reflect", + ) + self.assertEqual(spec.shape, (257, 732)) + + # fmt: off + expected = np.array([ + 0.1287945 , 0.12792738, 0.08311573, 0.03155122, 0.02470202, + 0.00727857, 0.00910694, 0.00686163, 0.01238981, 0.01473668, + 0.00336144, 0.00370314, 0.00600871, 0.01120164, 0.01942998, + 0.03132008, 0.0232842 , 0.01124642, 0.02754783, 0.02423725, + 0.00147893, 0.00038027, 0.00112299, 0.00596233, 0.00571529, + 0.02084235, 0.0231855 , 0.00810006, 0.01837943, 0.00651339, + 0.00093931, 0.00067426, 0.01058399, 0.01270507, 0.00151734, + 0.00331913, 0.00302416, 0.01081792, 0.00754549, 0.00148963, + 0.00111943, 0.00152573, 0.00608017, 0.01749986, 0.01205949, + 0.0143082 , 0.01910573, 0.00413786, 0.03916619, 0.09873404, + 0.08302026, 0.02673891, 0.00401255, 0.01397392, 0.00751862, + 0.01024884, 0.01544606, 0.00638907, 0.00623633, 0.0085103 , + 0.00217659, 0.00276204, 0.00260835, 0.00299299, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 0], expected)) + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=True, + pad_mode="constant", + ) + self.assertEqual(spec.shape, (257, 732)) + + # fmt: off + expected = np.array([ + 0.06558744, 0.06889656, 0.06263352, 0.04264418, 0.03404115, + 0.03244197, 0.02279134, 0.01646339, 0.01452216, 0.00826055, + 0.00062093, 0.0031821 , 0.00419456, 0.00689327, 0.01106367, + 0.01712119, 0.01721762, 0.00977533, 0.01606626, 0.02275621, + 0.01727687, 0.00992739, 0.01217688, 0.01049927, 0.01022947, + 0.01302475, 0.01166873, 0.01081812, 0.01057327, 0.00767912, + 0.00429567, 0.00089625, 0.00654583, 0.00912084, 0.00700984, + 0.00225026, 0.00290545, 0.00667712, 0.00730663, 0.00410813, + 0.00073102, 0.00219296, 0.00527618, 0.00996585, 0.01123781, + 0.00872816, 0.01165121, 0.02047945, 0.03681747, 0.0514379 , + 0.05137928, 0.03960042, 0.02821562, 0.01813349, 0.01201322, + 0.01260964, 0.00900654, 0.00207905, 0.00456714, 0.00850599, + 0.00788239, 0.00664407, 0.00824227, 0.00628301, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 0], expected)) + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=False, + ) + self.assertEqual(spec.shape, (257, 728)) + + # fmt: off + expected = np.array([ + 0.00250445, 0.02161521, 0.06232229, 0.04339567, 0.00937727, + 0.01080616, 0.00248685, 0.0095264 , 0.00727476, 0.0079152 , + 0.00839946, 0.00254932, 0.00716622, 0.005559 , 0.00272623, + 0.00581774, 0.01896395, 0.01829788, 0.01020514, 0.01632692, + 0.00870888, 0.02065827, 0.0136022 , 0.0132382 , 0.011827 , + 0.00194505, 0.0189979 , 0.026874 , 0.02194014, 0.01923883, + 0.01621437, 0.00661967, 0.00289517, 0.00470257, 0.00957801, + 0.00191455, 0.00431664, 0.00544359, 0.01126213, 0.00785778, + 0.00423469, 0.01322504, 0.02226548, 0.02318576, 0.03428908, + 0.03648811, 0.0202938 , 0.011902 , 0.03226198, 0.06347476, + 0.01306318, 0.05308729, 0.05474771, 0.03127991, 0.00998512, + 0.01449977, 0.01272741, 0.00868176, 0.00850386, 0.00313876, + 0.00811857, 0.00538216, 0.00685749, 0.00535275, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:64, 0], expected)) + + def test_spectrogram_batch_center_padding(self): + waveform_list = self._load_datasamples(3) + + spec_list = spectrogram_batch( + waveform_list, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=True, + pad_mode="reflect", + ) + self.assertEqual(spec_list[0].shape, (257, 732)) + self.assertEqual(spec_list[1].shape, (257, 602)) + self.assertEqual(spec_list[2].shape, (257, 1561)) + + # fmt: off + expected1 = np.array([ + 0.1287945 , 0.12792738, 0.08311573, 0.03155122, 0.02470202, + 0.00727857, 0.00910694, 0.00686163, 0.01238981, 0.01473668, + 0.00336144, 0.00370314, 0.00600871, 0.01120164, 0.01942998, + 0.03132008, 0.0232842 , 0.01124642, 0.02754783, 0.02423725, + 0.00147893, 0.00038027, 0.00112299, 0.00596233, 0.00571529, + 0.02084235, 0.0231855 , 0.00810006, 0.01837943, 0.00651339, + 0.00093931, 0.00067426, 0.01058399, 0.01270507, 0.00151734, + 0.00331913, 0.00302416, 0.01081792, 0.00754549, 0.00148963, + 0.00111943, 0.00152573, 0.00608017, 0.01749986, 0.01205949, + 0.0143082 , 0.01910573, 0.00413786, 0.03916619, 0.09873404, + 0.08302026, 0.02673891, 0.00401255, 0.01397392, 0.00751862, + 0.01024884, 0.01544606, 0.00638907, 0.00623633, 0.0085103 , + 0.00217659, 0.00276204, 0.00260835, 0.00299299, + ]) + expected2 = np.array([ + 1.89624839e-02, 1.23274978e-02, 3.69160250e-02, 4.76267971e-02, + 1.39258439e-02, 2.98370440e-02, 2.74845166e-03, 3.01934010e-03, + 1.18722776e-02, 9.70834121e-03, 2.06300567e-04, 6.32975250e-04, + 8.20603687e-03, 1.21864351e-02, 3.28791840e-03, 3.36801982e-04, + 2.79373326e-03, 5.00530424e-03, 8.46884679e-03, 1.14089288e-02, + 8.59052036e-03, 2.88538425e-03, 9.95071139e-03, 6.80431770e-03, + 2.95809377e-03, 1.46285209e-04, 3.36268265e-03, 4.80051298e-04, + 2.84506916e-03, 9.34222655e-04, 3.42161348e-03, 2.79612141e-03, + 3.38875921e-03, 2.85030343e-03, 5.39513239e-05, 2.72908504e-03, + 2.09591188e-03, 5.00271388e-04, 8.31917219e-04, 2.37967237e-03, + 1.75001193e-03, 1.31826295e-04, 8.83622793e-04, 1.54303256e-04, + 3.09544569e-03, 4.08527814e-03, 2.73566321e-03, 1.78805250e-03, + 9.53314066e-06, 1.74316950e-03, 1.51099428e-03, 8.65990878e-04, + 8.44859460e-04, 5.35220199e-04, 5.36562002e-04, 8.33181897e-04, + 8.22705682e-04, 1.81083288e-03, 9.75003233e-04, 6.73114730e-04, + 6.81665202e-04, 2.05180887e-03, 1.10151991e-03, 4.75923851e-04, + ]) + expected3 = np.array([ + 0.07079848, 0.04237922, 0.0220724, 0.04446052, 0.03598337, + 0.03327273, 0.02545774, 0.01319528, 0.00919659, 0.01376867, + 0.00361992, 0.00608425, 0.01105873, 0.0105565, 0.00744286, + 0.00244849, 0.00257317, 0.00749989, 0.01061386, 0.01525312, + 0.00656914, 0.01199581, 0.00487319, 0.00830956, 0.0046706, + 0.00588962, 0.00544486, 0.00565179, 0.00050112, 0.01108059, + 0.00217417, 0.00453234, 0.00537306, 0.00269329, 0.00342333, + 0.00095484, 0.00708934, 0.00660373, 0.00543686, 0.00217186, + 0.00431519, 0.00457764, 0.00503529, 0.01166454, 0.01375581, + 0.01467224, 0.00873404, 0.00534086, 0.00476848, 0.0226163, + 0.0314, 0.00151021, 0.01975221, 0.01637519, 0.00046068, + 0.0460544, 0.06285986, 0.03151625, 0.0013598, 0.004804, + 0.0073824, 0.02312599, 0.02613977, 0.01056851 + ]) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][:64, 0], expected1)) + self.assertTrue(np.allclose(spec_list[1][:64, 0], expected2)) + self.assertTrue(np.allclose(spec_list[2][:64, 0], expected3)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=True, + pad_mode="constant", + ) + self.assertEqual(spec_list[0].shape, (257, 732)) + self.assertEqual(spec_list[1].shape, (257, 602)) + self.assertEqual(spec_list[2].shape, (257, 1561)) + + # fmt: off + expected1 = np.array([ + 0.06558744, 0.06889656, 0.06263352, 0.04264418, 0.03404115, + 0.03244197, 0.02279134, 0.01646339, 0.01452216, 0.00826055, + 0.00062093, 0.0031821 , 0.00419456, 0.00689327, 0.01106367, + 0.01712119, 0.01721762, 0.00977533, 0.01606626, 0.02275621, + 0.01727687, 0.00992739, 0.01217688, 0.01049927, 0.01022947, + 0.01302475, 0.01166873, 0.01081812, 0.01057327, 0.00767912, + 0.00429567, 0.00089625, 0.00654583, 0.00912084, 0.00700984, + 0.00225026, 0.00290545, 0.00667712, 0.00730663, 0.00410813, + 0.00073102, 0.00219296, 0.00527618, 0.00996585, 0.01123781, + 0.00872816, 0.01165121, 0.02047945, 0.03681747, 0.0514379 , + 0.05137928, 0.03960042, 0.02821562, 0.01813349, 0.01201322, + 0.01260964, 0.00900654, 0.00207905, 0.00456714, 0.00850599, + 0.00788239, 0.00664407, 0.00824227, 0.00628301, + ]) + expected2 = np.array([ + 0.00955754, 0.01445548, 0.02393902, 0.02903068, 0.02512844, + 0.01508297, 0.00474784, 0.00440362, 0.0073898, 0.00546519, + 0.00126077, 0.00240507, 0.00523254, 0.00632742, 0.00415215, + 0.00056628, 0.00161288, 0.0026956, 0.00431587, 0.00621471, + 0.00791291, 0.0079454, 0.00594525, 0.00334581, 0.00180047, + 0.00144485, 0.00175764, 0.00188037, 0.00134889, 0.00150253, + 0.00178821, 0.00158875, 0.00204339, 0.00266497, 0.00280556, + 0.00221949, 0.00108956, 0.000532, 0.00108454, 0.00129254, + 0.00089315, 0.00022803, 0.00038176, 0.0011302, 0.00189306, + 0.0021964, 0.00203576, 0.00207306, 0.00217727, 0.00174297, + 0.00103331, 0.00076695, 0.0007422, 0.00061986, 0.00081204, + 0.00079615, 0.00089417, 0.00105452, 0.00042615, 0.00066372, + 0.00132765, 0.00122087, 0.00054903, 0.00107945, + ]) + expected3 = np.array([ + 0.03573493, 0.03625983, 0.03341755, 0.02431477, 0.01770546, + 0.0169356 , 0.01579034, 0.01600499, 0.01329064, 0.00747957, + 0.00367372, 0.00403853, 0.00519597, 0.00551022, 0.00532757, + 0.00367569, 0.00130341, 0.00345149, 0.00520744, 0.00872308, + 0.01172503, 0.00948154, 0.00344236, 0.00387997, 0.00425455, + 0.00394357, 0.00711733, 0.00615654, 0.00055756, 0.00656414, + 0.00852001, 0.00666252, 0.00509767, 0.00246784, 0.00376049, + 0.00682879, 0.00641118, 0.00469685, 0.00358701, 0.0015552 , + 0.00261458, 0.00701979, 0.00929578, 0.00894536, 0.00828491, + 0.00773528, 0.00552091, 0.00259871, 0.00933179, 0.01588626, + 0.01697887, 0.01268552, 0.00957255, 0.01204092, 0.02123362, + 0.03062669, 0.03215763, 0.02629963, 0.01769568, 0.01088869, + 0.01151334, 0.01378197, 0.01319263, 0.01066859, + ]) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][:64, 0], expected1)) + self.assertTrue(np.allclose(spec_list[1][:64, 0], expected2)) + self.assertTrue(np.allclose(spec_list[2][:64, 0], expected3)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(512, "hann"), + frame_length=512, + hop_length=128, + center=False, + ) + self.assertEqual(spec_list[0].shape, (257, 728)) + self.assertEqual(spec_list[1].shape, (257, 598)) + self.assertEqual(spec_list[2].shape, (257, 1557)) + + # fmt: off + expected1 = np.array([ + 0.00250445, 0.02161521, 0.06232229, 0.04339567, 0.00937727, + 0.01080616, 0.00248685, 0.0095264 , 0.00727476, 0.0079152 , + 0.00839946, 0.00254932, 0.00716622, 0.005559 , 0.00272623, + 0.00581774, 0.01896395, 0.01829788, 0.01020514, 0.01632692, + 0.00870888, 0.02065827, 0.0136022 , 0.0132382 , 0.011827 , + 0.00194505, 0.0189979 , 0.026874 , 0.02194014, 0.01923883, + 0.01621437, 0.00661967, 0.00289517, 0.00470257, 0.00957801, + 0.00191455, 0.00431664, 0.00544359, 0.01126213, 0.00785778, + 0.00423469, 0.01322504, 0.02226548, 0.02318576, 0.03428908, + 0.03648811, 0.0202938 , 0.011902 , 0.03226198, 0.06347476, + 0.01306318, 0.05308729, 0.05474771, 0.03127991, 0.00998512, + 0.01449977, 0.01272741, 0.00868176, 0.00850386, 0.00313876, + 0.00811857, 0.00538216, 0.00685749, 0.00535275, + ]) + expected2 = np.array([ + 0.01232908, 0.05980514, 0.08285419, 0.01850723, 0.02823627, + 0.00204369, 0.01372626, 0.00956435, 0.02267217, 0.00947112, + 0.00355174, 0.00418008, 0.00843608, 0.01559252, 0.01125505, + 0.00183573, 0.00765051, 0.0109983 , 0.00890545, 0.00583453, + 0.00115901, 0.00579039, 0.00151353, 0.00395812, 0.00231413, + 0.00384272, 0.00313914, 0.00072331, 0.00338935, 0.00383328, + 0.00218129, 0.00284516, 0.00228538, 0.00083603, 0.00111663, + 0.00235799, 0.00142748, 0.00092908, 0.0012966 , 0.0011403 , + 0.0010619 , 0.00158732, 0.00289866, 0.00216709, 0.00313325, + 0.00361277, 0.00202507, 0.0009948 , 0.00114428, 0.00200851, + 0.0009234 , 0.00063468, 0.00018746, 0.00100463, 0.00053799, + 0.00080009, 0.00158291, 0.00172077, 0.00173586, 0.00197127, + 0.00107058, 0.00043486, 0.0009859 , 0.00215484, + ]) + expected3 = np.array([ + 0.01864123, 0.06131337, 0.08346292, 0.04936386, 0.02792609, + 0.01005205, 0.00884826, 0.02198604, 0.02421535, 0.00957573, + 0.00503561, 0.00241331, 0.00175652, 0.00195889, 0.00453299, + 0.0020317 , 0.00249264, 0.00517483, 0.01111943, 0.0150079 , + 0.01977743, 0.01253825, 0.00517561, 0.01031712, 0.00579466, + 0.00783679, 0.0071415 , 0.00591847, 0.01510728, 0.01194921, + 0.00518072, 0.00125978, 0.00577552, 0.01050614, 0.0077644 , + 0.0042905 , 0.00278469, 0.00166695, 0.00255013, 0.00578153, + 0.00586451, 0.00929514, 0.01501226, 0.00741419, 0.00310625, + 0.00086757, 0.00595618, 0.0053882 , 0.0116266 , 0.02504773, + 0.02889692, 0.03739442, 0.04730207, 0.03856638, 0.05700104, + 0.04299267, 0.02153366, 0.03740607, 0.03811468, 0.01575022, + 0.00676344, 0.01359865, 0.01769319, 0.00907966, + ]) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][:64, 0], expected1)) + self.assertTrue(np.allclose(spec_list[1][:64, 0], expected2)) + self.assertTrue(np.allclose(spec_list[2][:64, 0], expected3)) + + def test_spectrogram_shapes(self): + waveform = self._load_datasamples(1)[0] + + spec = spectrogram( + waveform, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (201, 732)) + + spec = spectrogram( + waveform, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + power=1.0, + center=False, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (201, 729)) + + spec = spectrogram( + waveform, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + fft_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec.shape, (257, 732)) + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=64, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec.shape, (512, 1464)) + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=64, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec.shape, (512, 1464)) + + spec = spectrogram( + waveform, + window_function(512, "hann"), + frame_length=512, + hop_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec.shape, (512, 183)) + + def test_spectrogram_batch_shapes(self): + waveform_list = self._load_datasamples(3) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec_list[0].shape, (201, 732)) + self.assertEqual(spec_list[1].shape, (201, 602)) + self.assertEqual(spec_list[2].shape, (201, 1561)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + power=1.0, + center=False, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec_list[0].shape, (201, 729)) + self.assertEqual(spec_list[1].shape, (201, 599)) + self.assertEqual(spec_list[2].shape, (201, 1558)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann"), + frame_length=400, + hop_length=128, + fft_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=True, + ) + self.assertEqual(spec_list[0].shape, (257, 732)) + self.assertEqual(spec_list[1].shape, (257, 602)) + self.assertEqual(spec_list[2].shape, (257, 1561)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=64, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec_list[0].shape, (512, 1464)) + self.assertEqual(spec_list[1].shape, (512, 1204)) + self.assertEqual(spec_list[2].shape, (512, 3122)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(512, "hann"), + frame_length=512, + hop_length=64, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec_list[0].shape, (512, 1464)) + self.assertEqual(spec_list[1].shape, (512, 1204)) + self.assertEqual(spec_list[2].shape, (512, 3122)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(512, "hann"), + frame_length=512, + hop_length=512, + power=1.0, + center=True, + pad_mode="reflect", + onesided=False, + ) + self.assertEqual(spec_list[0].shape, (512, 183)) + self.assertEqual(spec_list[1].shape, (512, 151)) + self.assertEqual(spec_list[2].shape, (512, 391)) + + def test_mel_spectrogram(self): + waveform = self._load_datasamples(1)[0] + + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm=None, + mel_scale="htk", + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + spec = spectrogram( + waveform, + window_function(800, "hann", frame_length=1024), + frame_length=1024, + hop_length=128, + power=2.0, + ) + self.assertEqual(spec.shape, (513, 732)) + + spec = spectrogram( + waveform, + window_function(800, "hann", frame_length=1024), + frame_length=1024, + hop_length=128, + power=2.0, + mel_filters=mel_filters, + ) + self.assertEqual(spec.shape, (13, 732)) + + # fmt: off + expected = np.array([ + 1.08027889e+02, 1.48080673e+01, 7.70758213e+00, 9.57676639e-01, + 8.81639061e-02, 5.26073833e-02, 1.52736155e-02, 9.95350117e-03, + 7.95364356e-03, 1.01148004e-02, 4.29241020e-03, 9.90708797e-03, + 9.44153646e-04 + ]) + # fmt: on + self.assertTrue(np.allclose(spec[:, 300], expected)) + + def test_mel_spectrogram_batch(self): + waveform_list = self._load_datasamples(3) + + mel_filters = mel_filter_bank( + num_frequency_bins=513, + num_mel_filters=13, + min_frequency=100, + max_frequency=4000, + sampling_rate=16000, + norm=None, + mel_scale="htk", + ) + self.assertEqual(mel_filters.shape, (513, 13)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(800, "hann", frame_length=1024), + frame_length=1024, + hop_length=128, + power=2.0, + ) + self.assertEqual(spec_list[0].shape, (513, 732)) + self.assertEqual(spec_list[1].shape, (513, 602)) + self.assertEqual(spec_list[2].shape, (513, 1561)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(800, "hann", frame_length=1024), + frame_length=1024, + hop_length=128, + power=2.0, + mel_filters=mel_filters, + ) + self.assertEqual(spec_list[0].shape, (13, 732)) + self.assertEqual(spec_list[1].shape, (13, 602)) + self.assertEqual(spec_list[2].shape, (13, 1561)) + + # fmt: off + expected1 = np.array([ + 1.08027889e+02, 1.48080673e+01, 7.70758213e+00, 9.57676639e-01, + 8.81639061e-02, 5.26073833e-02, 1.52736155e-02, 9.95350117e-03, + 7.95364356e-03, 1.01148004e-02, 4.29241020e-03, 9.90708797e-03, + 9.44153646e-04 + ]) + expected2 = np.array([ + 71.82577165, 109.44693334, 272.4834194, 164.90450355, + 16.54056349, 11.60810547, 24.87525946, 21.07317022, + 1.26736284, 1.4583074, 1.36659061, 1.76305768, + 2.03703503 + ]) + expected3 = np.array([ + 5.22246749e+02, 6.92660728e+02, 2.65895922e+02, 2.06526565e+01, + 2.28692104e+00, 1.19473622e+00, 8.43228216e-01, 3.20760592e+00, + 1.33654151e+00, 1.51050684e-01, 2.78282477e-01, 9.25020981e-01, + 2.29908841e-01 + ]) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][:, 300], expected1)) + self.assertTrue(np.allclose(spec_list[1][:, 300], expected2)) + self.assertTrue(np.allclose(spec_list[2][:, 300], expected3)) + + def test_spectrogram_power(self): + waveform = self._load_datasamples(1)[0] + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=None, + ) + self.assertEqual(spec.shape, (257, 732)) + self.assertEqual(spec.dtype, np.complex64) + + # fmt: off + expected = np.array([ + 0.01452305+0.01820039j, -0.01737362-0.01641946j, + 0.0121028 +0.01565081j, -0.02794554-0.03021514j, + 0.04719803+0.04086519j, -0.04391563-0.02779365j, + 0.05682834+0.01571325j, -0.08604821-0.02023657j, + 0.07497991+0.0186641j , -0.06366091-0.00922475j, + 0.11003416+0.0114788j , -0.13677941-0.01523552j, + 0.10934535-0.00117226j, -0.11635598+0.02551187j, + 0.14708674-0.03469823j, -0.1328196 +0.06034218j, + 0.12667368-0.13973421j, -0.14764774+0.18912019j, + 0.10235471-0.12181523j, -0.00773012+0.04730498j, + -0.01487191-0.07312611j, -0.02739162+0.09619419j, + 0.02895459-0.05398273j, 0.01198589+0.05276592j, + -0.02117299-0.10123465j, 0.00666388+0.09526499j, + -0.01672773-0.05649684j, 0.02723125+0.05939891j, + -0.01879361-0.062954j , 0.03686557+0.04568823j, + -0.07394181-0.07949649j, 0.06238583+0.13905765j, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[64:96, 321], expected)) + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=1.0, + ) + self.assertEqual(spec.shape, (257, 732)) + self.assertEqual(spec.dtype, np.float64) + + # fmt: off + expected = np.array([ + 0.02328461, 0.02390484, 0.01978448, 0.04115711, 0.0624309 , + 0.05197181, 0.05896072, 0.08839577, 0.07726794, 0.06432579, + 0.11063128, 0.13762532, 0.10935163, 0.11911998, 0.15112405, + 0.14588428, 0.18860507, 0.23992978, 0.15910825, 0.04793241, + 0.07462307, 0.10001811, 0.06125769, 0.05411011, 0.10342509, + 0.09549777, 0.05892122, 0.06534349, 0.06569936, 0.05870678, + 0.10856833, 0.1524107 , 0.11463385, 0.05766969, 0.12385171, + 0.14472842, 0.11978184, 0.10353675, 0.07244056, 0.03461861, + 0.02624896, 0.02227475, 0.01238363, 0.00885281, 0.0110049 , + 0.00807005, 0.01033663, 0.01703181, 0.01445856, 0.00585615, + 0.0132431 , 0.02754132, 0.01524478, 0.0204908 , 0.07453328, + 0.10716327, 0.07195779, 0.08816078, 0.18340898, 0.16449876, + 0.12322842, 0.1621659 , 0.12334293, 0.06033659, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[64:128, 321], expected)) + + spec = spectrogram( + waveform, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=2.0, + ) + self.assertEqual(spec.shape, (257, 732)) + self.assertEqual(spec.dtype, np.float64) + + # fmt: off + expected = np.array([ + 5.42173162e-04, 5.71441371e-04, 3.91425507e-04, 1.69390778e-03, + 3.89761780e-03, 2.70106923e-03, 3.47636663e-03, 7.81381316e-03, + 5.97033510e-03, 4.13780799e-03, 1.22392802e-02, 1.89407300e-02, + 1.19577805e-02, 1.41895693e-02, 2.28384770e-02, 2.12822221e-02, + 3.55718732e-02, 5.75663000e-02, 2.53154356e-02, 2.29751552e-03, + 5.56860259e-03, 1.00036217e-02, 3.75250424e-03, 2.92790355e-03, + 1.06967501e-02, 9.11982451e-03, 3.47171025e-03, 4.26977174e-03, + 4.31640586e-03, 3.44648538e-03, 1.17870830e-02, 2.32290216e-02, + 1.31409196e-02, 3.32579296e-03, 1.53392460e-02, 2.09463164e-02, + 1.43476883e-02, 1.07198600e-02, 5.24763530e-03, 1.19844836e-03, + 6.89007982e-04, 4.96164430e-04, 1.53354369e-04, 7.83722571e-05, + 1.21107812e-04, 6.51257360e-05, 1.06845939e-04, 2.90082477e-04, + 2.09049831e-04, 3.42945241e-05, 1.75379610e-04, 7.58524227e-04, + 2.32403356e-04, 4.19872697e-04, 5.55520924e-03, 1.14839673e-02, + 5.17792348e-03, 7.77232368e-03, 3.36388536e-02, 2.70598419e-02, + 1.51852425e-02, 2.62977779e-02, 1.52134784e-02, 3.64050455e-03, + ]) + # fmt: on + self.assertTrue(np.allclose(spec[64:128, 321], expected)) + + def test_spectrogram_batch_power(self): + waveform_list = self._load_datasamples(3) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=None, + ) + self.assertEqual(spec_list[0].shape, (257, 732)) + self.assertEqual(spec_list[0].dtype, np.complex64) + self.assertEqual(spec_list[1].shape, (257, 602)) + self.assertEqual(spec_list[1].dtype, np.complex64) + self.assertEqual(spec_list[2].shape, (257, 1561)) + self.assertEqual(spec_list[2].dtype, np.complex64) + + # fmt: off + expected1 = np.array([ + 0.01452305+0.01820039j, -0.01737362-0.01641946j, + 0.0121028 +0.01565081j, -0.02794554-0.03021514j, + 0.04719803+0.04086519j, -0.04391563-0.02779365j, + 0.05682834+0.01571325j, -0.08604821-0.02023657j, + 0.07497991+0.0186641j , -0.06366091-0.00922475j, + 0.11003416+0.0114788j , -0.13677941-0.01523552j, + 0.10934535-0.00117226j, -0.11635598+0.02551187j, + 0.14708674-0.03469823j, -0.1328196 +0.06034218j, + 0.12667368-0.13973421j, -0.14764774+0.18912019j, + 0.10235471-0.12181523j, -0.00773012+0.04730498j, + -0.01487191-0.07312611j, -0.02739162+0.09619419j, + 0.02895459-0.05398273j, 0.01198589+0.05276592j, + -0.02117299-0.10123465j, 0.00666388+0.09526499j, + -0.01672773-0.05649684j, 0.02723125+0.05939891j, + -0.01879361-0.062954j , 0.03686557+0.04568823j, + -0.07394181-0.07949649j, 0.06238583+0.13905765j, + ]) + expected2 = np.array([ + -0.01634146-7.0067253e-03j, -0.00068403+9.2661660e-03j, + 0.00571721-3.9035487e-03j, -0.00915086+1.5033451e-03j, + 0.01138636+5.4256055e-03j, -0.00294282-1.2016168e-02j, + -0.00428711+7.3687937e-03j, -0.001002 -1.3972387e-03j, + 0.00622582+3.7551194e-03j, -0.00137886-7.0342086e-03j, + -0.00824075+3.8430823e-03j, 0.0107349 +7.1450039e-03j, + 0.00363763-1.4242286e-02j, -0.01499857+1.7917662e-05j, + -0.0046242 +1.2500680e-02j, 0.02180984+7.2047939e-03j, + -0.00273568-1.6844695e-02j, -0.00178986-7.5209686e-03j, + -0.01661806+1.2662713e-03j, -0.01045276+2.0611197e-02j, + 0.03252975+2.5592113e-02j, 0.03945662-6.7136563e-02j, + -0.10622615+4.9393820e-03j, 0.06684612+6.4607985e-02j, + -0.00753762-5.1637031e-02j, -0.00220644+1.8002450e-02j, + -0.00357443-4.1291970e-03j, 0.01463647-1.4063751e-03j, + -0.02252573-1.1189026e-02j, 0.00276293+1.9019062e-02j, + 0.01216721+1.2095908e-03j, 0.00034753-7.4386634e-03j + ]) + expected3 = np.array([ + 2.3276670e-02+0.0406534j, -2.4413882e-02-0.07868771j, + 1.0993068e-02+0.05550544j, -1.5825305e-02+0.00480187j, + 4.7617555e-02-0.04421869j, -7.1669750e-02+0.06317082j, + 5.9706111e-02-0.08369736j, -2.2317577e-02+0.08915959j, + -2.3291381e-02-0.06601578j, 5.9362967e-02+0.03185856j, + -6.5269925e-02+0.0030586j, 5.0898481e-02-0.04319243j, + -4.0413942e-02+0.08051146j, 3.0059000e-02-0.09730332j, + -1.2479190e-02+0.09703682j, -6.1806822e-03-0.09617531j, + 2.6907364e-02+0.08084074j, -4.1639723e-02-0.03391053j, + 3.1113219e-02-0.01497662j, 3.4023849e-03+0.03632669j, + -4.9804080e-02-0.039231j, 8.9777440e-02+0.02577243j, + -9.2947647e-02+0.01514865j, 6.2368069e-02-0.05954866j, + -2.9966677e-02+0.06520324j, -8.2365885e-05-0.0440613j , + 2.0203773e-02+0.04350767j, -8.9924788e-04-0.05406843j, + -3.5951469e-02+0.03055602j, 3.3790238e-02+0.02182594j, + 1.0919777e-03-0.06437822j, -1.8534327e-02+0.07866792j + ]) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][64:96, 321], expected1)) + self.assertTrue(np.allclose(spec_list[1][64:96, 321], expected2)) + self.assertTrue(np.allclose(spec_list[2][64:96, 321], expected3)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=1.0, + ) + self.assertEqual(spec_list[0].shape, (257, 732)) + self.assertEqual(spec_list[0].dtype, np.float64) + self.assertEqual(spec_list[1].shape, (257, 602)) + self.assertEqual(spec_list[1].dtype, np.float64) + self.assertEqual(spec_list[2].shape, (257, 1561)) + self.assertEqual(spec_list[2].dtype, np.float64) + + # fmt: off + expected1 = np.array([ + 0.02328461, 0.02390484, 0.01978448, 0.04115711, 0.0624309 , + 0.05197181, 0.05896072, 0.08839577, 0.07726794, 0.06432579, + 0.11063128, 0.13762532, 0.10935163, 0.11911998, 0.15112405, + 0.14588428, 0.18860507, 0.23992978, 0.15910825, 0.04793241, + 0.07462307, 0.10001811, 0.06125769, 0.05411011, 0.10342509, + 0.09549777, 0.05892122, 0.06534349, 0.06569936, 0.05870678, + 0.10856833, 0.1524107 , 0.11463385, 0.05766969, 0.12385171, + 0.14472842, 0.11978184, 0.10353675, 0.07244056, 0.03461861, + 0.02624896, 0.02227475, 0.01238363, 0.00885281, 0.0110049 , + 0.00807005, 0.01033663, 0.01703181, 0.01445856, 0.00585615, + 0.0132431 , 0.02754132, 0.01524478, 0.0204908 , 0.07453328, + 0.10716327, 0.07195779, 0.08816078, 0.18340898, 0.16449876, + 0.12322842, 0.1621659 , 0.12334293, 0.06033659, + ]) + expected2 = np.array([ + 0.01778026, 0.00929138, 0.00692273, 0.00927352, 0.01261294, + 0.01237128, 0.00852516, 0.00171938, 0.00727061, 0.00716808, + 0.00909281, 0.01289532, 0.01469949, 0.01499858, 0.01332855, + 0.02296907, 0.01706539, 0.00773101, 0.01666623, 0.02311021, + 0.0413901, 0.07787261, 0.10634092, 0.09296556, 0.05218428, + 0.01813716, 0.00546139, 0.01470388, 0.02515159, 0.0192187, + 0.01222719, 0.00744678, 0.01045674, 0.01923522, 0.01990819, + 0.01174323, 0.01535391, 0.02786647, 0.02904595, 0.0313408 , + 0.0340503, 0.03118268, 0.02915136, 0.04200513, 0.05563153, + 0.05429446, 0.05021769, 0.05882667, 0.06668596, 0.06555867, + 0.04523559, 0.01489498, 0.01031892, 0.02134155, 0.01736669, + 0.0195216, 0.03971575, 0.03938636, 0.02052712, 0.03104931, + 0.0902727, 0.09022622, 0.03275532, 0.0172633, + ]) + expected3 = np.array([ + 0.04684551, 0.08238806, 0.05658358, 0.01653778, 0.06498249, + 0.09553589, 0.10281084, 0.09191031, 0.07000408, 0.06737158, + 0.06534155, 0.06675509, 0.09008541, 0.10184046, 0.09783596, + 0.0963737, 0.08520112, 0.05370093, 0.03453015, 0.03648568, + 0.06339967, 0.09340346, 0.09417402, 0.08623119, 0.07175977, + 0.04406138, 0.04796988, 0.05407591, 0.0471824 , 0.04022626, + 0.06438748, 0.0808218, 0.0745263, 0.06191467, 0.03116328, + 0.03206497, 0.05867718, 0.04424652, 0.04448404, 0.07032498, + 0.08300796, 0.07895744, 0.0816894, 0.09392357, 0.07571699, + 0.03967651, 0.07703795, 0.06464871, 0.08704693, 0.14085226, + 0.1350321, 0.18794712, 0.27043005, 0.26596246, 0.19948336, + 0.06545141, 0.13204652, 0.08554521, 0.2262849, 0.33900721, + 0.3970475, 0.3482436, 0.17134947, 0.46249565, + ]) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][64:128, 321], expected1)) + self.assertTrue(np.allclose(spec_list[1][64:128, 321], expected2)) + self.assertTrue(np.allclose(spec_list[2][64:128, 321], expected3)) + + spec_list = spectrogram_batch( + waveform_list, + window_function(400, "hann", frame_length=512), + frame_length=512, + hop_length=128, + power=2.0, + ) + self.assertEqual(spec_list[0].shape, (257, 732)) + self.assertEqual(spec_list[0].dtype, np.float64) + self.assertEqual(spec_list[1].shape, (257, 602)) + self.assertEqual(spec_list[1].dtype, np.float64) + self.assertEqual(spec_list[2].shape, (257, 1561)) + self.assertEqual(spec_list[2].dtype, np.float64) + + # fmt: off + expected1 = np.array([ + 5.42173162e-04, 5.71441371e-04, 3.91425507e-04, 1.69390778e-03, + 3.89761780e-03, 2.70106923e-03, 3.47636663e-03, 7.81381316e-03, + 5.97033510e-03, 4.13780799e-03, 1.22392802e-02, 1.89407300e-02, + 1.19577805e-02, 1.41895693e-02, 2.28384770e-02, 2.12822221e-02, + 3.55718732e-02, 5.75663000e-02, 2.53154356e-02, 2.29751552e-03, + 5.56860259e-03, 1.00036217e-02, 3.75250424e-03, 2.92790355e-03, + 1.06967501e-02, 9.11982451e-03, 3.47171025e-03, 4.26977174e-03, + 4.31640586e-03, 3.44648538e-03, 1.17870830e-02, 2.32290216e-02, + 1.31409196e-02, 3.32579296e-03, 1.53392460e-02, 2.09463164e-02, + 1.43476883e-02, 1.07198600e-02, 5.24763530e-03, 1.19844836e-03, + 6.89007982e-04, 4.96164430e-04, 1.53354369e-04, 7.83722571e-05, + 1.21107812e-04, 6.51257360e-05, 1.06845939e-04, 2.90082477e-04, + 2.09049831e-04, 3.42945241e-05, 1.75379610e-04, 7.58524227e-04, + 2.32403356e-04, 4.19872697e-04, 5.55520924e-03, 1.14839673e-02, + 5.17792348e-03, 7.77232368e-03, 3.36388536e-02, 2.70598419e-02, + 1.51852425e-02, 2.62977779e-02, 1.52134784e-02, 3.64050455e-03, + ]) + expected2 = np.array([ + 3.16137604e-04, 8.63297362e-05, 4.79241720e-05, 8.59982493e-05, + 1.59086326e-04, 1.53048476e-04, 7.26783945e-05, 2.95627100e-06, + 5.28617352e-05, 5.13813355e-05, 8.26792588e-05, 1.66289156e-04, + 2.16075069e-04, 2.24957314e-04, 1.77650211e-04, 5.27578282e-04, + 2.91227688e-04, 5.97685493e-05, 2.77763360e-04, 5.34081651e-04, + 1.71314057e-03, 6.06414277e-03, 1.13083916e-02, 8.64259617e-03, + 2.72319867e-03, 3.28956593e-04, 2.98268126e-05, 2.16204145e-04, + 6.32602626e-04, 3.69358508e-04, 1.49504171e-04, 5.54544917e-05, + 1.09343371e-04, 3.69993847e-04, 3.96335839e-04, 1.37903521e-04, + 2.35742483e-04, 7.76540114e-04, 8.43667068e-04, 9.82245923e-04, + 1.15942286e-03, 9.72359636e-04, 8.49801853e-04, 1.76443092e-03, + 3.09486753e-03, 2.94788822e-03, 2.52181630e-03, 3.46057723e-03, + 4.44701769e-03, 4.29793858e-03, 2.04625858e-03, 2.21860290e-04, + 1.06480179e-04, 4.55461892e-04, 3.01601836e-04, 3.81092892e-04, + 1.57734053e-03, 1.55128531e-03, 4.21362677e-04, 9.64059883e-04, + 8.14916019e-03, 8.14077014e-03, 1.07291131e-03, 2.98021545e-04, + ]) + expected3 = np.array([ + 0.0021945 , 0.00678779, 0.0032017 , 0.0002735 , 0.00422272, + 0.00912711, 0.01057007, 0.00844751, 0.00490057, 0.00453893, + 0.00426952, 0.00445624, 0.00811538, 0.01037148, 0.00957188, + 0.00928789, 0.00725923, 0.00288379, 0.00119233, 0.0013312 , + 0.00401952, 0.00872421, 0.00886875, 0.00743582, 0.00514946, + 0.00194141, 0.00230111, 0.0029242 , 0.00222618, 0.00161815, + 0.00414575, 0.00653216, 0.00555417, 0.00383343, 0.00097115, + 0.00102816, 0.00344301, 0.00195775, 0.00197883, 0.0049456 , + 0.00689032, 0.00623428, 0.00667316, 0.00882164, 0.00573306, + 0.00157423, 0.00593485, 0.00417946, 0.00757717, 0.01983936, + 0.01823367, 0.03532412, 0.07313241, 0.07073603, 0.03979361, + 0.00428389, 0.01743628, 0.00731798, 0.05120486, 0.11492589, + 0.15764671, 0.1212736 , 0.02936064, 0.21390222 + ]) + # fmt: on + self.assertTrue(np.allclose(spec_list[0][64:128, 321], expected1)) + self.assertTrue(np.allclose(spec_list[1][64:128, 321], expected2)) + self.assertTrue(np.allclose(spec_list[2][64:128, 321], expected3)) + + def test_power_to_db(self): + spectrogram = np.zeros((2, 3)) + spectrogram[0, 0] = 2.0 + spectrogram[0, 1] = 0.5 + spectrogram[0, 2] = 0.707 + spectrogram[1, 1] = 1.0 + + output = power_to_db(spectrogram, reference=1.0) + expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-100.0, 0.0, -100.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, reference=2.0) + expected = np.array([[0.0, -6.02059991, -4.51610582], [-103.01029996, -3.01029996, -103.01029996]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, min_value=1e-6) + expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-60.0, 0.0, -60.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, db_range=80) + expected = np.array([[3.01029996, -3.01029996, -1.50580586], [-76.98970004, 0.0, -76.98970004]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, reference=2.0, db_range=80) + expected = np.array([[0.0, -6.02059991, -4.51610582], [-80.0, -3.01029996, -80.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db(spectrogram, reference=2.0, min_value=1e-6, db_range=80) + expected = np.array([[0.0, -6.02059991, -4.51610582], [-63.01029996, -3.01029996, -63.01029996]]) + self.assertTrue(np.allclose(output, expected)) + + with pytest.raises(ValueError): + power_to_db(spectrogram, reference=0.0) + with pytest.raises(ValueError): + power_to_db(spectrogram, min_value=0.0) + with pytest.raises(ValueError): + power_to_db(spectrogram, db_range=-80) + + def test_power_to_db_batch(self): + # Setup a batch of spectrograms with varying values and lengths + batch_spectrogram = np.zeros((3, 2, 3)) + batch_spectrogram[0, 0, 0] = 2.0 + batch_spectrogram[0, 0, 1] = 0.5 + batch_spectrogram[0, 0, 2] = 0.707 + batch_spectrogram[0, 1, 1] = 1.0 + batch_spectrogram[1, :, :2] = batch_spectrogram[0, :, :2] * 1.5 + batch_spectrogram[2, :, :1] = batch_spectrogram[0, :, :1] * 0.5 + + # Expected values computed by applying `power_to_db` iteratively + output = power_to_db_batch(batch_spectrogram, reference=1.0) + expected = np.array( + [ + [[3.01029996, -3.01029996, -1.50580586], [-100, 0, -100]], + [[4.77121255, -1.24938737, -100], [-100, 1.76091259, -100]], + [[0, -100, -100], [-100, -100, -100]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db_batch(batch_spectrogram, reference=2.0) + expected = np.array( + [ + [[0, -6.02059991, -4.51610582], [-103.01029996, -3.01029996, -103.01029996]], + [[1.76091259, -4.25968732, -103.01029996], [-103.01029996, -1.24938737, -103.01029996]], + [[-3.01029996, -103.01029996, -103.01029996], [-103.01029996, -103.01029996, -103.01029996]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db_batch(batch_spectrogram, min_value=1e-6) + expected = np.array( + [ + [[3.01029996, -3.01029996, -1.50580586], [-60, 0, -60]], + [[4.77121255, -1.24938737, -60], [-60, 1.76091259, -60]], + [[0, -60, -60], [-60, -60, -60]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db_batch(batch_spectrogram, db_range=80) + expected = np.array( + [ + [[3.01029996, -3.01029996, -1.50580586], [-76.98970004, 0, -76.98970004]], + [[4.77121255, -1.24938737, -75.22878745], [-75.22878745, 1.76091259, -75.22878745]], + [[0, -80, -80], [-80, -80, -80]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db_batch(batch_spectrogram, reference=2.0, db_range=80) + expected = np.array( + [ + [[0, -6.02059991, -4.51610582], [-80, -3.01029996, -80]], + [[1.76091259, -4.25968732, -78.23908741], [-78.23908741, -1.24938737, -78.23908741]], + [[-3.01029996, -83.01029996, -83.01029996], [-83.01029996, -83.01029996, -83.01029996]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = power_to_db_batch(batch_spectrogram, reference=2.0, min_value=1e-6, db_range=80) + expected = np.array( + [ + [[0, -6.02059991, -4.51610582], [-63.01029996, -3.01029996, -63.01029996]], + [[1.76091259, -4.25968732, -63.01029996], [-63.01029996, -1.24938737, -63.01029996]], + [[-3.01029996, -63.01029996, -63.01029996], [-63.01029996, -63.01029996, -63.01029996]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + with pytest.raises(ValueError): + power_to_db_batch(batch_spectrogram, reference=0.0) + with pytest.raises(ValueError): + power_to_db_batch(batch_spectrogram, min_value=0.0) + with pytest.raises(ValueError): + power_to_db_batch(batch_spectrogram, db_range=-80) + + def test_amplitude_to_db(self): + spectrogram = np.zeros((2, 3)) + spectrogram[0, 0] = 2.0 + spectrogram[0, 1] = 0.5 + spectrogram[0, 2] = 0.707 + spectrogram[1, 1] = 1.0 + + output = amplitude_to_db(spectrogram, reference=1.0) + expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-100.0, 0.0, -100.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, reference=2.0) + expected = np.array([[0.0, -12.04119983, -9.03221164], [-106.02059991, -6.02059991, -106.02059991]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, min_value=1e-3) + expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-60.0, 0.0, -60.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, db_range=80) + expected = np.array([[6.02059991, -6.02059991, -3.01161172], [-73.97940009, 0.0, -73.97940009]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, reference=2.0, db_range=80) + expected = np.array([[0.0, -12.04119983, -9.03221164], [-80.0, -6.02059991, -80.0]]) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db(spectrogram, reference=2.0, min_value=1e-3, db_range=80) + expected = np.array([[0.0, -12.04119983, -9.03221164], [-66.02059991, -6.02059991, -66.02059991]]) + self.assertTrue(np.allclose(output, expected)) + + with pytest.raises(ValueError): + amplitude_to_db(spectrogram, reference=0.0) + with pytest.raises(ValueError): + amplitude_to_db(spectrogram, min_value=0.0) + with pytest.raises(ValueError): + amplitude_to_db(spectrogram, db_range=-80) + + def test_amplitude_to_db_batch(self): + # Setup a batch of spectrograms with varying values and lengths + batch_spectrogram = np.zeros((3, 2, 3)) + batch_spectrogram[0, 0, 0] = 2.0 + batch_spectrogram[0, 0, 1] = 0.5 + batch_spectrogram[0, 0, 2] = 0.707 + batch_spectrogram[0, 1, 1] = 1.0 + batch_spectrogram[1, :, :2] = batch_spectrogram[0, :, :2] * 1.5 + batch_spectrogram[2, :, :1] = batch_spectrogram[0, :, :1] * 0.5 + + # Expected values computed by applying `amplitude_to_db` iteratively + output = amplitude_to_db_batch(batch_spectrogram, reference=1.0) + expected = np.array( + [ + [[6.02059991, -6.02059991, -3.01161172], [-100, 0, -100]], + [[9.54242509, -2.49877473, -100], [-100, 3.52182518, -100]], + [[0, -100, -100], [-100, -100, -100]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db_batch(batch_spectrogram, reference=2.0) + expected = np.array( + [ + [[0, -12.04119983, -9.03221164], [-106.02059991, -6.02059991, -106.02059991]], + [[3.52182518, -8.51937465, -106.02059991], [-106.02059991, -2.49877473, -106.02059991]], + [[-6.02059991, -106.02059991, -106.02059991], [-106.02059991, -106.02059991, -106.02059991]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db_batch(batch_spectrogram, min_value=1e-3) + expected = np.array( + [ + [[6.02059991, -6.02059991, -3.01161172], [-60, 0, -60]], + [[9.54242509, -2.49877473, -60], [-60, 3.52182518, -60]], + [[0, -60, -60], [-60, -60, -60]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db_batch(batch_spectrogram, db_range=80) + expected = np.array( + [ + [[6.02059991, -6.02059991, -3.01161172], [-73.97940009, 0, -73.97940009]], + [[9.54242509, -2.49877473, -70.45757491], [-70.45757491, 3.52182518, -70.45757491]], + [[0, -80, -80], [-80, -80, -80]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db_batch(batch_spectrogram, reference=2.0, db_range=80) + expected = np.array( + [ + [[0, -12.04119983, -9.03221164], [-80, -6.02059991, -80]], + [[3.52182518, -8.51937465, -76.47817482], [-76.47817482, -2.49877473, -76.47817482]], + [[-6.02059991, -86.02059991, -86.02059991], [-86.02059991, -86.02059991, -86.02059991]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + output = amplitude_to_db_batch(batch_spectrogram, reference=2.0, min_value=1e-3, db_range=80) + expected = np.array( + [ + [[0, -12.04119983, -9.03221164], [-66.02059991, -6.02059991, -66.02059991]], + [[3.52182518, -8.51937465, -66.02059991], [-66.02059991, -2.49877473, -66.02059991]], + [[-6.02059991, -66.02059991, -66.02059991], [-66.02059991, -66.02059991, -66.02059991]], + ] + ) + self.assertTrue(np.allclose(output, expected)) + + with pytest.raises(ValueError): + amplitude_to_db_batch(batch_spectrogram, reference=0.0) + with pytest.raises(ValueError): + amplitude_to_db_batch(batch_spectrogram, min_value=0.0) + with pytest.raises(ValueError): + amplitude_to_db_batch(batch_spectrogram, db_range=-80) + + @require_librosa + def test_chroma_equivalence(self): + num_frequency_bins = 25 + num_chroma = 6 + sampling_rate = 24000 + + # test default parameters + original_chroma = chroma(sr=sampling_rate, n_chroma=num_chroma, n_fft=num_frequency_bins) + utils_chroma = chroma_filter_bank( + num_frequency_bins=num_frequency_bins, num_chroma=num_chroma, sampling_rate=sampling_rate + ) + + self.assertTrue(np.allclose(original_chroma, utils_chroma)) + + # test no weighting_parameters + original_chroma = chroma(sr=sampling_rate, n_chroma=num_chroma, n_fft=num_frequency_bins, octwidth=None) + utils_chroma = chroma_filter_bank( + num_frequency_bins=num_frequency_bins, + num_chroma=num_chroma, + sampling_rate=sampling_rate, + weighting_parameters=None, + ) + + self.assertTrue(np.allclose(original_chroma, utils_chroma)) + + # test with L1 norm + original_chroma = chroma(sr=sampling_rate, n_chroma=num_chroma, n_fft=num_frequency_bins, norm=1.0) + utils_chroma = chroma_filter_bank( + num_frequency_bins=num_frequency_bins, num_chroma=num_chroma, sampling_rate=sampling_rate, power=1.0 + ) + + self.assertTrue(np.allclose(original_chroma, utils_chroma)) + + # test starting at 'A' chroma, power = None, tuning = 0, different weighting_parameters + original_chroma = chroma( + sr=sampling_rate, + n_chroma=num_chroma, + n_fft=num_frequency_bins, + norm=None, + base_c=None, + octwidth=1.0, + ctroct=4.0, + ) + utils_chroma = chroma_filter_bank( + num_frequency_bins=num_frequency_bins, + num_chroma=num_chroma, + sampling_rate=sampling_rate, + power=None, + start_at_c_chroma=False, + weighting_parameters=(4.0, 1.0), + ) + + self.assertTrue(np.allclose(original_chroma, utils_chroma)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_auto_docstring.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_auto_docstring.py new file mode 100644 index 0000000000000000000000000000000000000000..1874631f5e879e721e5c277ebc144ff5b2aa64df --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_auto_docstring.py @@ -0,0 +1,88 @@ +# coding=utf-8 +# Copyright 2024 The HuggingFace Team 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 clone 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. + +import unittest + + +LLAMA_CLM_FORWARD = """ The [`LlamaForCausalLM`] forward method, overrides the `__call__` special method.\n\n \n\n Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]\n instance afterwards instead of this since the former takes care of running the pre and post processing steps while\n the latter silently ignores them.\n\n \n\n Args:\n input_ids (`Optional[torch.LongTensor]`)of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`Optional[torch.Tensor]`) of shape `(batch_size, sequence_length)`:\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n position_ids (`Optional[torch.LongTensor]`):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n past_key_values (`Optional[~cache_utils.Cache]`):\n Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention\n blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`\n returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.\n\n Two formats are allowed:\n - a `~cache_utils.Cache` instance, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);\n - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of\n shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy\n cache format.\n\n The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the\n legacy cache format will be returned.\n\n If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don\'t\n have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`\n of shape `(batch_size, sequence_length)`.\n inputs_embeds (`Optional[torch.FloatTensor]`):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n model\'s internal embedding lookup matrix.\n labels (`Optional[torch.LongTensor]`) of shape `(batch_size, sequence_length)`:\n Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,\n config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored\n (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.\n use_cache (`Optional[bool]`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n output_attentions (`Optional[bool]`):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`Optional[bool]`):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n cache_position (`Optional[torch.LongTensor]`):\n Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,\n this tensor is not affected by padding. It is used to update the cache in the correct position and to infer\n the complete sequence length.\n logits_to_keep (`Union[int, torch.Tensor]`, defaults to `0`):\n If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all\n `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that\n token can save memory, which becomes pretty significant for long sequences or large vocabulary size.\n If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.\n This is useful when using packed tensor format (single dimension for batch and sequence length).\n\n Returns:\n [`transformers.modeling_outputs.CausalLMOutputWithPast`] or `tuple(torch.FloatTensor)`: A [`transformers.modeling_outputs.CausalLMOutputWithPast`] or a tuple of\n `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various\n elements depending on the configuration ([`LlamaConfig`]) and inputs.\n\n - **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Language modeling loss (for next-token prediction).\n - **logits** (`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).\n - **past_key_values** (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape\n `(batch_size, num_heads, sequence_length, embed_size_per_head)`)\n\n Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see\n `past_key_values` input) to speed up sequential decoding.\n - **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +\n one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n - **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,\n sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n\n Example:\n\n ```python\n >>> from transformers import AutoTokenizer, LlamaForCausalLM\n\n >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")\n >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")\n\n >>> prompt = "Hey, are you conscious? Can you talk to me?"\n >>> inputs = tokenizer(prompt, return_tensors="pt")\n\n >>> # Generate\n >>> generate_ids = model.generate(inputs.input_ids, max_length=30)\n >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]\n "Hey, are you conscious? Can you talk to me?\\nI\'m not conscious, but I can talk to you."\n ```""" + +LLAMA_MODEL_DOCSTRING = """ The [`LlamaModel`] forward method, overrides the `__call__` special method.\n\n \n\n Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]\n instance afterwards instead of this since the former takes care of running the pre and post processing steps while\n the latter silently ignores them.\n\n \n\n Args:\n input_ids (`Optional[torch.LongTensor]`)of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`Optional[torch.Tensor]`) of shape `(batch_size, sequence_length)`:\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n position_ids (`Optional[torch.LongTensor]`):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n past_key_values (`Optional[~cache_utils.Cache]`):\n Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention\n blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`\n returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.\n\n Two formats are allowed:\n - a `~cache_utils.Cache` instance, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);\n - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of\n shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy\n cache format.\n\n The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the\n legacy cache format will be returned.\n\n If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't\n have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`\n of shape `(batch_size, sequence_length)`.\n inputs_embeds (`Optional[torch.FloatTensor]`):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n model's internal embedding lookup matrix.\n use_cache (`Optional[bool]`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n output_attentions (`Optional[bool]`):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`Optional[bool]`):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n cache_position (`Optional[torch.LongTensor]`):\n Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,\n this tensor is not affected by padding. It is used to update the cache in the correct position and to infer\n the complete sequence length.\n\n Returns:\n [`transformers.modeling_outputs.BaseModelOutputWithPast`] or `tuple(torch.FloatTensor)`: A [`transformers.modeling_outputs.BaseModelOutputWithPast`] or a tuple of\n `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various\n elements depending on the configuration ([`LlamaConfig`]) and inputs.\n\n - **last_hidden_state** (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`) -- Sequence of hidden-states at the output of the last layer of the model.\n\n If `past_key_values` is used only the last hidden-state of the sequences of shape `(batch_size, 1,\n hidden_size)` is output.\n - **past_key_values** (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape\n `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and optionally if\n `config.is_encoder_decoder=True` 2 additional tensors of shape `(batch_size, num_heads,\n encoder_sequence_length, embed_size_per_head)`.\n\n Contains pre-computed hidden-states (key and values in the self-attention blocks and optionally if\n `config.is_encoder_decoder=True` in the cross-attention blocks) that can be used (see `past_key_values`\n input) to speed up sequential decoding.\n - **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +\n one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n - **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,\n sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n""" + +LLAMA_DECODER = """ The [`LlamaDecoderLayer`] forward method, overrides the `__call__` special method.\n\n \n\n Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]\n instance afterwards instead of this since the former takes care of running the pre and post processing steps while\n the latter silently ignores them.\n\n \n\n Args:\n hidden_states (`torch.Tensor`): input to the layer of shape `(batch, seq_len, embed_dim) attention_mask (`Optional[torch.Tensor]`) of shape `(batch_size, sequence_length)`:\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n position_ids (`Optional[torch.LongTensor]`):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n past_key_values (`Optional[~cache_utils.Cache]`):deprecated in favor of `past_key_values` output_attentions (`Optional[bool]`, defaults to `False`):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n use_cache (`Optional[bool]`, defaults to `False`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n cache_position (`Optional[torch.LongTensor]`):\n Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,\n this tensor is not affected by padding. It is used to update the cache in the correct position and to infer\n the complete sequence length.\n position_embeddings (`Optional[Tuple[torch.Tensor, torch.Tensor]]`):\n Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,\n with `head_dim` being the embedding dimension of each attention head.\n\n Returns:\n `Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]`""" + +LLAMA_FOR_SEQUENCE_CLASSIFICATION_DOC = """ The [`LlamaForSequenceClassification`] forward method, overrides the `__call__` special method.\n\n \n\n Although the recipe for forward pass needs to be defined within this function, one should call the [`Module`]\n instance afterwards instead of this since the former takes care of running the pre and post processing steps while\n the latter silently ignores them.\n\n \n\n Args:\n input_ids (`Optional[torch.LongTensor]`)of shape `(batch_size, sequence_length)`):\n Indices of input sequence tokens in the vocabulary. Padding will be ignored by default.\n\n Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and\n [`PreTrainedTokenizer.__call__`] for details.\n\n [What are input IDs?](../glossary#input-ids)\n attention_mask (`Optional[torch.Tensor]`) of shape `(batch_size, sequence_length)`:\n Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:\n\n - 1 for tokens that are **not masked**,\n - 0 for tokens that are **masked**.\n\n [What are attention masks?](../glossary#attention-mask)\n position_ids (`Optional[torch.LongTensor]`):\n Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`.\n\n [What are position IDs?](../glossary#position-ids)\n past_key_values (`Optional[~cache_utils.Cache]`):\n Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention\n blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`\n returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.\n\n Two formats are allowed:\n - a `~cache_utils.Cache` instance, see our [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);\n - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of\n shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy\n cache format.\n\n The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the\n legacy cache format will be returned.\n\n If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don\'t\n have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`\n of shape `(batch_size, sequence_length)`.\n inputs_embeds (`Optional[torch.FloatTensor]`):\n Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This\n is useful if you want more control over how to convert `input_ids` indices into associated vectors than the\n model\'s internal embedding lookup matrix.\n labels (`Optional[torch.LongTensor]`):\n Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,\n config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If\n `config.num_labels > 1` a classification loss is computed (Cross-Entropy).\n use_cache (`Optional[bool]`):\n If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see\n `past_key_values`).\n output_attentions (`Optional[bool]`):\n Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned\n tensors for more detail.\n output_hidden_states (`Optional[bool]`):\n Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n more detail.\n\n Returns:\n [`transformers.modeling_outputs.SequenceClassifierOutputWithPast`] or `tuple(torch.FloatTensor)`: A [`transformers.modeling_outputs.SequenceClassifierOutputWithPast`] or a tuple of\n `torch.FloatTensor` (if `return_dict=False` is passed or when `config.return_dict=False`) comprising various\n elements depending on the configuration ([`LlamaConfig`]) and inputs.\n\n - **loss** (`torch.FloatTensor` of shape `(1,)`, *optional*, returned when `labels` is provided) -- Classification (or regression if config.num_labels==1) loss.\n - **logits** (`torch.FloatTensor` of shape `(batch_size, config.num_labels)`) -- Classification (or regression if config.num_labels==1) scores (before SoftMax).\n - **past_key_values** (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`) -- Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape\n `(batch_size, num_heads, sequence_length, embed_size_per_head)`)\n\n Contains pre-computed hidden-states (key and values in the self-attention blocks) that can be used (see\n `past_key_values` input) to speed up sequential decoding.\n - **hidden_states** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_hidden_states=True` is passed or when `config.output_hidden_states=True`) -- Tuple of `torch.FloatTensor` (one for the output of the embeddings, if the model has an embedding layer, +\n one for the output of each layer) of shape `(batch_size, sequence_length, hidden_size)`.\n\n Hidden-states of the model at the output of each layer plus the optional initial embedding outputs.\n - **attentions** (`tuple(torch.FloatTensor)`, *optional*, returned when `output_attentions=True` is passed or when `config.output_attentions=True`) -- Tuple of `torch.FloatTensor` (one for each layer) of shape `(batch_size, num_heads, sequence_length,\n sequence_length)`.\n\n Attentions weights after the attention softmax, used to compute the weighted average in the self-attention\n heads.\n\n Example of single-label classification:\n\n ```python\n >>> import torch\n >>> from transformers import AutoTokenizer, LlamaForSequenceClassification\n\n >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")\n >>> model = LlamaForSequenceClassification.from_pretrained("meta-llama/Llama-2-7b-hf")\n\n >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")\n\n >>> with torch.no_grad():\n ... logits = model(**inputs).logits\n\n >>> predicted_class_id = logits.argmax().item()\n >>> model.config.id2label[predicted_class_id]\n ...\n\n >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`\n >>> num_labels = len(model.config.id2label)\n >>> model = LlamaForSequenceClassification.from_pretrained("meta-llama/Llama-2-7b-hf", num_labels=num_labels)\n\n >>> labels = torch.tensor([1])\n >>> loss = model(**inputs, labels=labels).loss\n >>> round(loss.item(), 2)\n ...\n ```\n\n Example of multi-label classification:\n\n ```python\n >>> import torch\n >>> from transformers import AutoTokenizer, LlamaForSequenceClassification\n\n >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")\n >>> model = LlamaForSequenceClassification.from_pretrained("meta-llama/Llama-2-7b-hf", problem_type="multi_label_classification")\n\n >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")\n\n >>> with torch.no_grad():\n ... logits = model(**inputs).logits\n\n >>> predicted_class_ids = torch.arange(0, logits.shape[-1])[torch.sigmoid(logits).squeeze(dim=0) > 0.5]\n\n >>> # To train a model on `num_labels` classes, you can pass `num_labels=num_labels` to `.from_pretrained(...)`\n >>> num_labels = len(model.config.id2label)\n >>> model = LlamaForSequenceClassification.from_pretrained(\n ... "meta-llama/Llama-2-7b-hf", num_labels=num_labels, problem_type="multi_label_classification"\n ... )\n\n >>> labels = torch.sum(\n ... torch.nn.functional.one_hot(predicted_class_ids[None, :].clone(), num_classes=num_labels), dim=1\n ... ).to(torch.float)\n >>> loss = model(**inputs, labels=labels).loss\n ```\n""" + +GEMMA3_IMAGE_PROCESSOR_FAST_DOCSTRING = """\nConstructs a fast Gemma3 image processor.\n\nParameters:\n do_resize (`Optional[bool]`, defaults to `True`):\n Whether to resize the image.\n size (`Optional[dict[str, int]]`, defaults to `{\'height\': 224, \'width\': 224}`):\n Describes the maximum input dimensions to the model.\n default_to_square (`Optional[bool]`, defaults to `True`):\n Whether to default to a square image when resizing, if size is an int.\n resample (`Union[PILImageResampling, F.InterpolationMode, NoneType]`, defaults to `2`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`Optional[bool]`, defaults to `None`):\n Whether to center crop the image.\n crop_size (`Optional[dict[str, int]]`, defaults to `None`):\n Size of the output image after applying `center_crop`.\n do_rescale (`Optional[bool]`, defaults to `True`):\n Whether to rescale the image.\n rescale_factor (`Union[int, float, NoneType]`, defaults to `0.00392156862745098`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`Optional[bool]`, defaults to `True`):\n Whether to normalize the image.\n image_mean (`Union[float, list[float], NoneType]`, defaults to `[0.5, 0.5, 0.5]`):\n Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.\n image_std (`Union[float, list[float], NoneType]`, defaults to `[0.5, 0.5, 0.5]`):\n Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to\n `True`.\n do_convert_rgb (`Optional[bool]`, defaults to `None`):\n Whether to convert the image to RGB.\n return_tensors (`Union[str, ~utils.generic.TensorType, NoneType]`, defaults to `None`):\n Returns stacked tensors if set to `pt, otherwise returns a list of tensors.\n data_format (`Optional[~image_utils.ChannelDimension]`, defaults to `ChannelDimension.FIRST`):\n Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.\n input_data_format (`Union[str, ~image_utils.ChannelDimension, NoneType]`, defaults to `None`):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.\n device (`Optional[torch.device]`, defaults to `None`):\n The device to process the images on. If unset, the device is inferred from the input images.\n do_pan_and_scan (`Optional[bool]`, defaults to `None`):\n Whether to apply `pan_and_scan` to images.\n pan_and_scan_min_crop_size (`Optional[int]`, defaults to `None`):\n Minimum size of each crop in pan and scan.\n pan_and_scan_max_num_crops (`Optional[int]`, defaults to `None`):\n Maximum number of crops per image in pan and scan.\n pan_and_scan_min_ratio_to_activate (`Optional[float]`, defaults to `None`):\n Minimum aspect ratio to activate pan and scan.\n""" + +GEMMA3_IMAGE_PROCESSOR_FAST_PREPROCESS_DOCSTRING = """ Args:\n images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list[\'PIL.Image.Image\'], list[numpy.ndarray], list[\'torch.Tensor\']]`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`Optional[bool]`):\n Whether to resize the image.\n size (`Optional[dict[str, int]]`):\n Describes the maximum input dimensions to the model.\n default_to_square (`Optional[bool]`):\n Whether to default to a square image when resizing, if size is an int.\n resample (`Union[PILImageResampling, F.InterpolationMode, NoneType]`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`Optional[bool]`):\n Whether to center crop the image.\n crop_size (`Optional[dict[str, int]]`):\n Size of the output image after applying `center_crop`.\n do_rescale (`Optional[bool]`):\n Whether to rescale the image.\n rescale_factor (`Union[int, float, NoneType]`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`Optional[bool]`):\n Whether to normalize the image.\n image_mean (`Union[float, list[float], NoneType]`):\n Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.\n image_std (`Union[float, list[float], NoneType]`):\n Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to\n `True`.\n do_convert_rgb (`Optional[bool]`):\n Whether to convert the image to RGB.\n return_tensors (`Union[str, ~utils.generic.TensorType, NoneType]`):\n Returns stacked tensors if set to `pt, otherwise returns a list of tensors.\n data_format (`Optional[~image_utils.ChannelDimension]`):\n Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.\n input_data_format (`Union[str, ~image_utils.ChannelDimension, NoneType]`):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `"channels_first"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `"channels_last"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `"none"` or `ChannelDimension.NONE`: image in (height, width) format.\n device (`Optional[torch.device]`):\n The device to process the images on. If unset, the device is inferred from the input images.\n do_pan_and_scan (`Optional[bool]`):\n Whether to apply `pan_and_scan` to images.\n pan_and_scan_min_crop_size (`Optional[int]`):\n Minimum size of each crop in pan and scan.\n pan_and_scan_max_num_crops (`Optional[int]`):\n Maximum number of crops per image in pan and scan.\n pan_and_scan_min_ratio_to_activate (`Optional[float]`):\n Minimum aspect ratio to activate pan and scan.\n\n Returns:\n ``:\n - **data** (`dict`) -- Dictionary of lists/arrays/tensors returned by the __call__ method (\'pixel_values\', etc.).\n - **tensor_type** (`Union[None, str, TensorType]`, *optional*) -- You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at\n initialization.\n""" + + +class AutoDocstringTest(unittest.TestCase): + pass + # def test_modeling_docstring(self): + # llama_docstring = " Args:\n images (`Union[PIL.Image.Image, numpy.ndarray, torch.Tensor, list['PIL.Image.Image'], list[numpy.ndarray], list['torch.Tensor']]`):\n Image to preprocess. Expects a single or batch of images with pixel values ranging from 0 to 255. If\n passing in images with pixel values between 0 and 1, set `do_rescale=False`.\n do_resize (`Optional[bool]`):\n Whether to resize the image.\n size (`Optional[dict[str, int]]`):\n Describes the maximum input dimensions to the model.\n default_to_square (`Optional[bool]`):\n Whether to default to a square image when resizing, if size is an int.\n resample (`Union[PILImageResampling, F.InterpolationMode, NoneType]`):\n Resampling filter to use if resizing the image. This can be one of the enum `PILImageResampling`. Only\n has an effect if `do_resize` is set to `True`.\n do_center_crop (`Optional[bool]`):\n Whether to center crop the image.\n crop_size (`Optional[dict[str, int]]`):\n Size of the output image after applying `center_crop`.\n do_rescale (`Optional[bool]`):\n Whether to rescale the image.\n rescale_factor (`Union[int, float, NoneType]`):\n Rescale factor to rescale the image by if `do_rescale` is set to `True`.\n do_normalize (`Optional[bool]`):\n Whether to normalize the image.\n image_mean (`Union[float, list[float], NoneType]`):\n Image mean to use for normalization. Only has an effect if `do_normalize` is set to `True`.\n image_std (`Union[float, list[float], NoneType]`):\n Image standard deviation to use for normalization. Only has an effect if `do_normalize` is set to\n `True`.\n do_convert_rgb (`Optional[bool]`):\n Whether to convert the image to RGB.\n return_tensors (`Union[str, ~utils.generic.TensorType, NoneType]`):\n Returns stacked tensors if set to `pt, otherwise returns a list of tensors.\n data_format (`Optional[~image_utils.ChannelDimension]`):\n Only `ChannelDimension.FIRST` is supported. Added for compatibility with slow processors.\n input_data_format (`Union[str, ~image_utils.ChannelDimension, NoneType]`):\n The channel dimension format for the input image. If unset, the channel dimension format is inferred\n from the input image. Can be one of:\n - `\"channels_first\"` or `ChannelDimension.FIRST`: image in (num_channels, height, width) format.\n - `\"channels_last\"` or `ChannelDimension.LAST`: image in (height, width, num_channels) format.\n - `\"none\"` or `ChannelDimension.NONE`: image in (height, width) format.\n device (`Optional[torch.device]`):\n The device to process the images on. If unset, the device is inferred from the input images.\n do_pan_and_scan (`Optional[bool]`):\n Whether to apply `pan_and_scan` to images.\n pan_and_scan_min_crop_size (`Optional[int]`):\n Minimum size of each crop in pan and scan.\n pan_and_scan_max_num_crops (`Optional[int]`):\n Maximum number of crops per image in pan and scan.\n pan_and_scan_min_ratio_to_activate (`Optional[float]`):\n Minimum aspect ratio to activate pan and scan.\n\n Returns:\n ``:\n - **data** (`dict`) -- Dictionary of lists/arrays/tensors returned by the __call__ method ('pixel_values', etc.).\n - **tensor_type** (`Union[None, str, TensorType]`, *optional*) -- You can give a tensor_type here to convert the lists of integers in PyTorch/TensorFlow/Numpy Tensors at\n initialization.\n" + # self.assertEqual(llama_docstring, LlamaModel.__doc__) + + # self.assertEqual(LLAMA_MODEL_DOCSTRING, LlamaModel.forward.__doc__) + # self.assertEqual(LLAMA_CLM_FORWARD, LlamaForCausalLM.forward.__doc__) + # self.assertEqual(LLAMA_DECODER, LlamaDecoderLayer.forward.__doc__) + # self.assertEqual(LLAMA_FOR_SEQUENCE_CLASSIFICATION_DOC, LlamaForSequenceClassification.forward.__doc__) + + # def test_fast_image_processor_docstring(self): + # self.assertEqual(GEMMA3_IMAGE_PROCESSOR_FAST_DOCSTRING, Gemma3ImageProcessorFast.__doc__) + # self.assertEqual(GEMMA3_IMAGE_PROCESSOR_FAST_PREPROCESS_DOCSTRING, Gemma3ImageProcessorFast.preprocess.__doc__) + + # def test_auto_doc(self): + # COOL_CLASS_DOC = """ + # Args: + # input_ids (some): + # flash_attn_kwargs (FlashAttentionKwrargs): + # parameters that are completely optional and that should be passed. + # another_warg (something): should pass + # and_another_on (this time): + # I want + # this to be + # quite long + + # Example + + # ```python + # >>> import + # ``` + # """ + + # @auto_docstring + # class MyModel: + # @auto_docstring + # def __init__(input_ids, flash_attn_kwargs=None, another_warg=True, and_another_on=1): + # r""" + # Args: + # flash_attn_kwargs (FlashAttentionKwrargs): + # parameters that are completely optional and that should be passed. + # another_warg (something): should pass + # and_another_on (this time): + # I want + # this to be + # quite long + + # Example + + # ```python + # >>> import + # ``` + # """ + # pass + + # self.assertEqual(MyModel.__init__.__doc__, COOL_CLASS_DOC) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_backbone_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_backbone_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2e1242e4202835be8ae0b0881ce9b16b480400d3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_backbone_utils.py @@ -0,0 +1,272 @@ +# 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. + +import unittest + +import pytest + +from transformers import DetrConfig, MaskFormerConfig, ResNetBackbone, ResNetConfig, TimmBackbone +from transformers.testing_utils import require_torch, slow +from transformers.utils.backbone_utils import ( + BackboneMixin, + get_aligned_output_features_output_indices, + load_backbone, + verify_out_features_out_indices, +) +from transformers.utils.import_utils import is_torch_available + + +if is_torch_available(): + import torch + + from transformers import BertPreTrainedModel + + +class BackboneUtilsTester(unittest.TestCase): + def test_get_aligned_output_features_output_indices(self): + stage_names = ["a", "b", "c"] + + # Defaults to last layer if both are None + out_features, out_indices = get_aligned_output_features_output_indices(None, None, stage_names) + self.assertEqual(out_features, ["c"]) + self.assertEqual(out_indices, [2]) + + # Out indices set to match out features + out_features, out_indices = get_aligned_output_features_output_indices(["a", "c"], None, stage_names) + self.assertEqual(out_features, ["a", "c"]) + self.assertEqual(out_indices, [0, 2]) + + # Out features set to match out indices + out_features, out_indices = get_aligned_output_features_output_indices(None, [0, 2], stage_names) + self.assertEqual(out_features, ["a", "c"]) + self.assertEqual(out_indices, [0, 2]) + + # Out features selected from negative indices + out_features, out_indices = get_aligned_output_features_output_indices(None, [-3, -1], stage_names) + self.assertEqual(out_features, ["a", "c"]) + self.assertEqual(out_indices, [-3, -1]) + + def test_verify_out_features_out_indices(self): + # Stage names must be set + with pytest.raises(ValueError, match="Stage_names must be set for transformers backbones"): + verify_out_features_out_indices(["a", "b"], (0, 1), None) + + # Out features must be a list + with pytest.raises(ValueError, match="out_features must be a list got "): + verify_out_features_out_indices(("a", "b"), (0, 1), ["a", "b"]) + + # Out features must be a subset of stage names + with pytest.raises( + ValueError, match=r"out_features must be a subset of stage_names: \['a'\] got \['a', 'b'\]" + ): + verify_out_features_out_indices(["a", "b"], [0, 1], ["a"]) + + # Out features must contain no duplicates + with pytest.raises(ValueError, match=r"out_features must not contain any duplicates, got \['a', 'a'\]"): + verify_out_features_out_indices(["a", "a"], None, ["a"]) + + # Out indices must be a list + with pytest.raises(ValueError, match="out_indices must be a list, got "): + verify_out_features_out_indices(None, 0, ["a", "b"]) + + with pytest.raises(ValueError, match="out_indices must be a list, got "): + verify_out_features_out_indices(None, (0, 1), ["a", "b"]) + + # Out indices must be a subset of stage names + with pytest.raises( + ValueError, match=r"out_indices must be valid indices for stage_names \['a'\], got \[0, 1\]" + ): + verify_out_features_out_indices(None, [0, 1], ["a"]) + + # Out indices must contain no duplicates + with pytest.raises(ValueError, match=r"out_indices must not contain any duplicates, got \[0, 0\]"): + verify_out_features_out_indices(None, [0, 0], ["a"]) + + # Out features and out indices must be the same length + with pytest.raises( + ValueError, match="out_features and out_indices should have the same length if both are set" + ): + verify_out_features_out_indices(["a", "b"], [0], ["a", "b", "c"]) + + # Out features should match out indices + with pytest.raises( + ValueError, match="out_features and out_indices should correspond to the same stages if both are set" + ): + verify_out_features_out_indices(["a", "b"], [0, 2], ["a", "b", "c"]) + + # Out features and out indices should be in order + with pytest.raises( + ValueError, + match=r"out_features must be in the same order as stage_names, expected \['a', 'b'\] got \['b', 'a'\]", + ): + verify_out_features_out_indices(["b", "a"], [0, 1], ["a", "b"]) + + with pytest.raises( + ValueError, match=r"out_indices must be in the same order as stage_names, expected \[-2, 1\] got \[1, -2\]" + ): + verify_out_features_out_indices(["a", "b"], [1, -2], ["a", "b"]) + + # Check passes with valid inputs + verify_out_features_out_indices(["a", "b", "d"], [0, 1, -1], ["a", "b", "c", "d"]) + + def test_backbone_mixin(self): + backbone = BackboneMixin() + + backbone.stage_names = ["a", "b", "c"] + backbone._out_features = ["a", "c"] + backbone._out_indices = [0, 2] + + # Check that the output features and indices are set correctly + self.assertEqual(backbone.out_features, ["a", "c"]) + self.assertEqual(backbone.out_indices, [0, 2]) + + # Check out features and indices are updated correctly + backbone.out_features = ["a", "b"] + self.assertEqual(backbone.out_features, ["a", "b"]) + self.assertEqual(backbone.out_indices, [0, 1]) + + backbone.out_indices = [-3, -1] + self.assertEqual(backbone.out_features, ["a", "c"]) + self.assertEqual(backbone.out_indices, [-3, -1]) + + @slow + @require_torch + def test_load_backbone_from_config(self): + """ + Test that load_backbone correctly loads a backbone from a backbone config. + """ + config = MaskFormerConfig(backbone_config=ResNetConfig(out_indices=(0, 2))) + backbone = load_backbone(config) + self.assertEqual(backbone.out_features, ["stem", "stage2"]) + self.assertEqual(backbone.out_indices, (0, 2)) + self.assertIsInstance(backbone, ResNetBackbone) + + @slow + @require_torch + def test_load_backbone_from_checkpoint(self): + """ + Test that load_backbone correctly loads a backbone from a checkpoint. + """ + config = MaskFormerConfig(backbone="microsoft/resnet-18", backbone_config=None) + backbone = load_backbone(config) + self.assertEqual(backbone.out_indices, [4]) + self.assertEqual(backbone.out_features, ["stage4"]) + self.assertIsInstance(backbone, ResNetBackbone) + + config = MaskFormerConfig( + backbone="resnet18", + use_timm_backbone=True, + ) + backbone = load_backbone(config) + # We can't know ahead of time the exact output features and indices, or the layer names before + # creating the timm model, so it defaults to the last layer (-1,) and has a different layer name + self.assertEqual(backbone.out_indices, (-1,)) + self.assertEqual(backbone.out_features, ["layer4"]) + self.assertIsInstance(backbone, TimmBackbone) + + @slow + @require_torch + def test_load_backbone_backbone_kwargs(self): + """ + Test that load_backbone correctly configures the loaded backbone with the provided kwargs. + """ + config = MaskFormerConfig(backbone="resnet18", use_timm_backbone=True, backbone_kwargs={"out_indices": (0, 1)}) + backbone = load_backbone(config) + self.assertEqual(backbone.out_indices, (0, 1)) + self.assertIsInstance(backbone, TimmBackbone) + + config = MaskFormerConfig(backbone="microsoft/resnet-18", backbone_kwargs={"out_indices": (0, 2)}) + backbone = load_backbone(config) + self.assertEqual(backbone.out_indices, (0, 2)) + self.assertIsInstance(backbone, ResNetBackbone) + + # Check can't be passed with a backone config + with pytest.raises(ValueError): + config = MaskFormerConfig( + backbone="microsoft/resnet-18", + backbone_config=ResNetConfig(out_indices=(0, 2)), + backbone_kwargs={"out_indices": (0, 1)}, + ) + + @slow + @require_torch + def test_load_backbone_in_new_model(self): + """ + Tests that new model can be created, with its weights instantiated and pretrained backbone weights loaded. + """ + + # Inherit from PreTrainedModel to ensure that the weights are initialized + class NewModel(BertPreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.backbone = load_backbone(config) + self.layer_0 = torch.nn.Linear(config.hidden_size, config.hidden_size) + self.layer_1 = torch.nn.Linear(config.hidden_size, config.hidden_size) + + def get_equal_not_equal_weights(model_0, model_1): + equal_weights = [] + not_equal_weights = [] + for (k0, v0), (k1, v1) in zip(model_0.named_parameters(), model_1.named_parameters()): + self.assertEqual(k0, k1) + weights_are_equal = torch.allclose(v0, v1) + if weights_are_equal: + equal_weights.append(k0) + else: + not_equal_weights.append(k0) + return equal_weights, not_equal_weights + + config = MaskFormerConfig(use_pretrained_backbone=False, backbone="microsoft/resnet-18") + model_0 = NewModel(config) + model_1 = NewModel(config) + equal_weights, not_equal_weights = get_equal_not_equal_weights(model_0, model_1) + + # Norm layers are always initialized with the same weights + equal_weights = [w for w in equal_weights if "normalization" not in w] + self.assertEqual(len(equal_weights), 0) + self.assertEqual(len(not_equal_weights), 24) + + # Now we create a new model with backbone weights that are pretrained + config.use_pretrained_backbone = True + model_0 = NewModel(config) + model_1 = NewModel(config) + equal_weights, not_equal_weights = get_equal_not_equal_weights(model_0, model_1) + + # Norm layers are always initialized with the same weights + equal_weights = [w for w in equal_weights if "normalization" not in w] + self.assertEqual(len(equal_weights), 20) + # Linear layers are still initialized randomly + self.assertEqual(len(not_equal_weights), 4) + + # Check loading in timm backbone + config = DetrConfig(use_pretrained_backbone=False, backbone="resnet18", use_timm_backbone=True) + model_0 = NewModel(config) + model_1 = NewModel(config) + equal_weights, not_equal_weights = get_equal_not_equal_weights(model_0, model_1) + + # Norm layers are always initialized with the same weights + equal_weights = [w for w in equal_weights if "bn" not in w and "downsample.1" not in w] + self.assertEqual(len(equal_weights), 0) + self.assertEqual(len(not_equal_weights), 24) + + # Now we create a new model with backbone weights that are pretrained + config.use_pretrained_backbone = True + model_0 = NewModel(config) + model_1 = NewModel(config) + equal_weights, not_equal_weights = get_equal_not_equal_weights(model_0, model_1) + + # Norm layers are always initialized with the same weights + equal_weights = [w for w in equal_weights if "bn" not in w and "downsample.1" not in w] + self.assertEqual(len(equal_weights), 20) + # Linear layers are still initialized randomly + self.assertEqual(len(not_equal_weights), 4) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_cache_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_cache_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..043a43865212c3995475c58b01733b399f7daa90 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_cache_utils.py @@ -0,0 +1,1448 @@ +# Copyright 2023 HuggingFace 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. + +import copy +import unittest + +import pytest +from packaging import version +from parameterized import parameterized + +from transformers import set_seed +from transformers.generation.configuration_utils import ALL_CACHE_IMPLEMENTATIONS +from transformers.testing_utils import ( + CaptureStderr, + backend_device_count, + backend_torch_accelerator_module, + cleanup, + get_gpu_count, + is_torch_available, + require_read_token, + require_torch, + require_torch_accelerator, + require_torch_gpu, + require_torch_multi_accelerator, + require_torch_multi_gpu, + slow, + torch_device, +) +from transformers.utils import is_hqq_available, is_optimum_quanto_available, is_torch_greater_or_equal + + +if is_torch_available(): + import torch + + from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + Cache, + DynamicCache, + Gemma2Config, + GenerationConfig, + HybridCache, + HybridChunkedCache, + LlamaConfig, + QuantizedCache, + SlidingWindowCache, + StaticCache, + convert_and_export_with_cache, + pipeline, + ) + from transformers.integrations.executorch import export_with_dynamic_cache + + +TEST_CACHE_IMPLEMENTATIONS = [ + cache_name + for cache_name in ALL_CACHE_IMPLEMENTATIONS + # TODO (joao): offloaded_hybrid == offloaded_hybrid_chunked, deprecate one of them + if cache_name != "offloaded_hybrid" +] + + +@require_torch +class CacheTest(unittest.TestCase): + """Cache tests that don't require loading models""" + + def test_dynamic_cache_retrocompatibility(self): + """Tests that we can convert back and forth between the legacy cache format and DynamicCache""" + legacy_cache = () + new_cache = DynamicCache() + + # Creates a new cache with 10 layers in both formats + for layer_idx in range(10): + new_key = torch.rand((2, 4, 8, 16)) + new_value = torch.rand((2, 4, 8, 16)) + new_cache.update(new_key, new_value, layer_idx) + legacy_cache += ((new_key, new_value),) + + # Sanity check 1: they must have the same shapes + self.assertTrue(len(legacy_cache), len(new_cache)) + for layer_idx in range(10): + self.assertTrue(len(legacy_cache[layer_idx]), len(legacy_cache[layer_idx])) + for key_value_idx in range(2): + self.assertTrue( + legacy_cache[layer_idx][key_value_idx].shape == new_cache[layer_idx][key_value_idx].shape + ) + + # Sanity check 2: we can get the sequence length in multiple ways with DynamicCache, and they return the + # expected value + self.assertTrue(legacy_cache[0][0].shape[-2] == new_cache[0][0].shape[-2] == new_cache.get_seq_length() == 8) + + # Sanity check 3: they must be equal, and both support indexing + for layer_idx in range(10): + for key_value_idx in range(2): + self.assertTrue( + torch.allclose(new_cache[layer_idx][key_value_idx], legacy_cache[layer_idx][key_value_idx]) + ) + + # Test 1: We can convert from legacy to new with no changes + from_legacy = DynamicCache.from_legacy_cache(legacy_cache) + for layer_idx in range(10): + for key_value_idx in range(2): + self.assertTrue( + torch.allclose(from_legacy[layer_idx][key_value_idx], legacy_cache[layer_idx][key_value_idx]) + ) + + # Test 2: We can convert from new to legacy with no changes + to_legacy = new_cache.to_legacy_cache() + for layer_idx in range(10): + for key_value_idx in range(2): + self.assertTrue( + torch.allclose(to_legacy[layer_idx][key_value_idx], new_cache[layer_idx][key_value_idx]) + ) + + def test_static_cache_mha_mqa_gqa(self): + """ + Tests that static cache works with multi-head attention (MHA), grouped query attention (GQA), and multi-query + attention (MQA) + """ + + def _random_kvs(config): + # shape for key and values: (batch_size, num_heads, seq_len, head_dim) + random_keys = torch.rand( + (1, config.num_key_value_heads, 1, config.hidden_size // config.num_attention_heads), + device=torch_device, + ) + random_values = torch.rand( + (1, config.num_key_value_heads, 1, config.hidden_size // config.num_attention_heads), + device=torch_device, + ) + return random_keys, random_values + + mha_config = LlamaConfig(num_attention_heads=32) + mha_static_cache = StaticCache(config=mha_config, max_cache_len=10) + cached_keys, cached_values = mha_static_cache.update( + *_random_kvs(mha_config), 0, cache_kwargs={"cache_position": torch.arange(1).to(torch_device)} + ) + self.assertTrue(cached_keys.shape == (1, 32, 10, 128)) + self.assertTrue(cached_values.shape == (1, 32, 10, 128)) + + gqa_config = LlamaConfig(num_attention_heads=32, num_key_value_heads=4) + gqa_static_cache = StaticCache(config=gqa_config, max_cache_len=10) + cached_keys, cached_values = gqa_static_cache.update( + *_random_kvs(gqa_config), 0, cache_kwargs={"cache_position": torch.arange(1).to(torch_device)} + ) + self.assertTrue(cached_keys.shape == (1, 4, 10, 128)) + self.assertTrue(cached_values.shape == (1, 4, 10, 128)) + + mqa_config = LlamaConfig(num_attention_heads=32, num_key_value_heads=1) + mqa_static_cache = StaticCache(config=mqa_config, max_cache_len=10) + cached_keys, cached_values = mqa_static_cache.update( + *_random_kvs(mqa_config), 0, cache_kwargs={"cache_position": torch.arange(1).to(torch_device)} + ) + self.assertTrue(cached_keys.shape == (1, 1, 10, 128)) + self.assertTrue(cached_values.shape == (1, 1, 10, 128)) + + +def _skip_on_failed_cache_prerequisites(test, cache_implementation): + """Function to skip tests on failed cache prerequisites, given a cache implementation""" + # Installed dependencies + if cache_implementation == "quantized" and not is_optimum_quanto_available(): + test.skipTest("Quanto is not available") + # Devices + if "offloaded" in cache_implementation: + has_accelerator = torch_device is not None and torch_device != "cpu" + if not has_accelerator: + test.skipTest("Offloaded caches require an accelerator") + if cache_implementation in ["offloaded_static", "offloaded_hybrid_chunked"]: + if backend_device_count(torch_device) != 1: + test.skipTest("Offloaded static caches require exactly 1 accelerator") + + +class CacheIntegrationTest(unittest.TestCase): + """Fast cache integration tests that share the same small model""" + + @classmethod + def setUpClass(cls): + # Load once and reuse across tests + cls.tokenizer = AutoTokenizer.from_pretrained("HuggingFaceTB/SmolLM2-135M-Instruct", padding_side="left") + cls.model = AutoModelForCausalLM.from_pretrained( + "HuggingFaceTB/SmolLM2-135M-Instruct", device_map="auto", torch_dtype=torch.float16 + ) + cls.model.config.sliding_window = 256 # hack to enable the use of caches with sliding windows + + @parameterized.expand(TEST_CACHE_IMPLEMENTATIONS) + def test_cache_batched(self, cache_implementation): + """Sanity check: caches' `.update` function expects batched inputs""" + _skip_on_failed_cache_prerequisites(self, cache_implementation) + + EXPECTED_GENERATION = ["A sequence: 1, 2, 3, 4, 5, 6, 7, 8,", "A sequence: A, B, C, D, E, F, G, H"] + + inputs = self.tokenizer( + ["A sequence: 1, 2, 3, 4, 5", "A sequence: A, B, C"], padding=True, return_tensors="pt" + ) + inputs = inputs.to(self.model.device) + + gen_out = self.model.generate( + **inputs, + do_sample=False, + max_new_tokens=10, + return_dict_in_generate=True, + cache_implementation=cache_implementation, + disable_compile=True, + ) + # Sanity check: a cache was used + self.assertIsInstance(gen_out.past_key_values, Cache) + # Confirm that the output matches expectations + decoded = self.tokenizer.batch_decode(gen_out.sequences, skip_special_tokens=True) + self.assertListEqual(decoded, EXPECTED_GENERATION) + + @parameterized.expand(TEST_CACHE_IMPLEMENTATIONS) + def test_cache_beam_search(self, cache_implementation): + """ + Sanity check: caches' `reorder_cache` is operational. We can confirm this by looking at the beam indices + (an output sequence contains multiple beam indices). + """ + _skip_on_failed_cache_prerequisites(self, cache_implementation) + if cache_implementation == "offloaded_hybrid_chunked": + # TODO (joao, cyril): something is off with `offloaded_hybrid_chunked` aka `OffloadedHybridCache`: the + # output sequence (and the corresponding beam scores, if we add `output_scores=True`) are significantly + # different from the other caches. + self.skipTest("`offloaded_hybrid_chunked` fails this test") + + EXPECTED_GENERATION = [ + "Blue is the color of the sky, and the color of", + "Blue is the color of the sky, and the second is", + ] + + inputs = self.tokenizer(["Blue is"], return_tensors="pt").to(self.model.device) + gen_out = self.model.generate( + **inputs, + do_sample=False, + max_new_tokens=10, + num_beams=2, + num_return_sequences=2, + cache_implementation=cache_implementation, + disable_compile=True, + return_dict_in_generate=True, + ) + # Sanity check: a cache was used + self.assertIsInstance(gen_out.past_key_values, Cache) + # At least one of the sequences requires multiple beam indices -> `reorder_cache` had to shift things around + self.assertTrue(any(len(set(beams_in_sequence)) > 1 for beams_in_sequence in gen_out.beam_indices)) + # Confirm that the output matches expectations + decoded = self.tokenizer.batch_decode(gen_out.sequences, skip_special_tokens=True) + self.assertListEqual(decoded, EXPECTED_GENERATION) + + @parameterized.expand([("quanto"), ("HQQ")]) + def test_quantized_cache_generation(self, backend): + """Tests that QuantizedCache works as expected for both `quanto` and `hqq` backends.""" + if backend == "quanto": + if not is_optimum_quanto_available(): + self.skipTest("Quanto is not available") + axis_key, axis_value = 0, 0 + # This output is taken from a run with the same parameters, and is known to be correct + expected_generation = ["The cat's whiskers are also a sign of anxiety."] + elif backend == "HQQ": + if not is_hqq_available(): + self.skipTest("HQQ is not available") + axis_key, axis_value = 1, 1 + # HQQ has slightly different numerics + expected_generation = ["The cat's whiskers are also a sign of anxiety."] + else: + return + + inputs = self.tokenizer(["The cat"], return_tensors="pt").to(self.model.device) + + gen_out = self.model.generate( + **inputs, + do_sample=False, + max_new_tokens=10, + return_dict_in_generate=True, + cache_implementation="quantized", + cache_config={ + "backend": backend, + "nbits": 4, + "q_group_size": 16, + "residual_length": 4, + "axis_key": axis_key, + "axis_value": axis_value, + }, + disable_compile=True, + ) + + self.assertIsInstance(gen_out.past_key_values, QuantizedCache) + + decoded = self.tokenizer.batch_decode(gen_out.sequences, skip_special_tokens=True) + self.assertListEqual(decoded, expected_generation) + + # Check that something is actually quantized + + @parameterized.expand(TEST_CACHE_IMPLEMENTATIONS) + def test_cache_extra_left_padding(self, cache_implementation): + """Tests that adding extra left-padding does not affect the generation with the cache""" + _skip_on_failed_cache_prerequisites(self, cache_implementation) + + EXPECTED_GENERATION = ["The cat's whiskers are also a sign of anxiety."] + + inputs = self.tokenizer(["The cat"], padding=True, return_tensors="pt").to(self.model.device) + generation_kwargs = { + "do_sample": False, + "max_new_tokens": 10, + "cache_implementation": cache_implementation, + "disable_compile": True, + } + + gen_out = self.model.generate(**inputs, **generation_kwargs) + decoded = self.tokenizer.batch_decode(gen_out, skip_special_tokens=True) + self.assertListEqual(decoded, EXPECTED_GENERATION) + + # Now with extra left-padding + inputs_expanded = self.tokenizer(["The cat"], padding=True, return_tensors="pt", pad_to_multiple_of=32) + inputs_expanded = inputs_expanded.to(self.model.device) + self.assertTrue(inputs.input_ids.shape[1] < inputs_expanded.input_ids.shape[1]) + gen_out = self.model.generate(**inputs_expanded, **generation_kwargs) + decoded = self.tokenizer.batch_decode(gen_out, skip_special_tokens=True) + self.assertListEqual(decoded, EXPECTED_GENERATION) + + +@require_torch_accelerator +class CacheHardIntegrationTest(unittest.TestCase): + """Hard cache integration tests that require loading different models""" + + def setUp(self): + # Clears memory before each test. Some tests use large models, which might result in suboptimal torch + # re-allocation if we run multiple tests in a row without clearing memory. + cleanup(torch_device, gc_collect=True) + + @classmethod + def tearDownClass(cls): + # Clears memory after the last test. See `setUp` for more details. + cleanup(torch_device, gc_collect=True) + + @slow + def test_dynamic_cache_hard(self): + """Hard test for base cache implementation -- minor numerical fluctuations will cause this test to fail""" + tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B", padding_side="left") + model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-4B", device_map="auto", torch_dtype=torch.bfloat16) + inputs = tokenizer(["Here's everything I know about cats. Cats"], return_tensors="pt").to(model.device) + + set_seed(0) + gen_out = model.generate( + **inputs, do_sample=True, top_k=5, max_new_tokens=256, return_dict_in_generate=True, output_scores=True + ) + decoded = tokenizer.batch_decode(gen_out.sequences, skip_special_tokens=True) + # sum of the scores for the generated tokens + input_length = inputs.input_ids.shape[1] + score_sum = sum( + [score[0][gen_out.sequences[0][input_length + idx]] for idx, score in enumerate(gen_out.scores)] + ) + + EXPECTED_GENERATION = ( + "Here's everything I know about cats. Cats are mammals, they have four legs, they have a tail, they have " + "a face with a nose, eyes, and mouth. They have fur, they have claws, and they have whiskers. They are " + "usually small, but some are big. They are usually gray or black or white, but they can be many colors. " + "They have a soft body, they are usually quiet, but they can be loud. They are good at catching mice, " + "and they are good at climbing trees. They are often kept as pets, and they are often seen in homes. " + "They are independent, but they can be affectionate with their owners. They have a keen sense of smell, " + "and they can hear sounds that humans cannot hear. They have a good sense of balance, which helps them " + "to jump and climb. They are also good at hunting, and they can be trained to do tricks. They are often " + "used as pets, and they are also used in some jobs, like hunting or as service animals for people with " + "disabilities. They have a long life span, and they can live for many years. They are also known for " + "their agility and gracefulness. They are often associated with mystery and independence. They are also " + "known for their ability to land on their feet when they fall. They" + ) + EXPECTED_SCORE_SUM = 10834.7919921875 + self.assertEqual(decoded[0], EXPECTED_GENERATION) + self.assertAlmostEqual(score_sum.item(), EXPECTED_SCORE_SUM, places=2) + self.assertIsInstance(gen_out.past_key_values, DynamicCache) # sanity check + + @parameterized.expand([("eager"), ("sdpa")]) + @require_torch_accelerator + @slow + def test_static_cache_greedy_decoding_pad_left(self, attn_implementation): + """Tests that different cache implementations work well with eager and SDPA inference""" + EXPECTED_GENERATION = [ + "The best color is the one that is most suitable for the purpose.", + "We should not undermind the issues at hand, but instead, we should focus on the things", + ] + + tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B", padding_side="left") + model = AutoModelForCausalLM.from_pretrained( + "Qwen/Qwen3-4B", + torch_dtype=torch.bfloat16, + attn_implementation=attn_implementation, + device_map="auto", + ) + inputs = tokenizer( + ["The best color is", "We should not undermind the issues at hand"], padding=True, return_tensors="pt" + ).to(model.device) + generation_kwargs = {"do_sample": False, "max_new_tokens": 10, "return_dict_in_generate": True} + + set_seed(0) + gen_out = model.generate(**inputs, **generation_kwargs) + decoded = tokenizer.batch_decode(gen_out.sequences, skip_special_tokens=True) + with self.subTest(f"{attn_implementation}, dynamic"): + self.assertListEqual(decoded, EXPECTED_GENERATION) + self.assertIsInstance(gen_out.past_key_values, DynamicCache) # sanity check + + set_seed(0) + gen_out = model.generate(**inputs, **generation_kwargs, cache_implementation="static", disable_compile=True) + decoded = tokenizer.batch_decode(gen_out.sequences, skip_special_tokens=True) + with self.subTest(f"{attn_implementation}, static, eager"): + self.assertListEqual(decoded, EXPECTED_GENERATION) + self.assertIsInstance(gen_out.past_key_values, StaticCache) # sanity check + + set_seed(0) + gen_out = model.generate(**inputs, **generation_kwargs, cache_implementation="static") + decoded = tokenizer.batch_decode(gen_out.sequences, skip_special_tokens=True) + with self.subTest(f"{attn_implementation}, static, compiled"): + self.assertListEqual(decoded, EXPECTED_GENERATION) + self.assertIsInstance(gen_out.past_key_values, StaticCache) # sanity check + + @require_torch_accelerator + @slow + def test_offloaded_cache_uses_less_memory_than_dynamic_cache(self): + """Tests that OffloadedCache uses less memory than the default DynamicCache""" + model_name = "microsoft/Phi-3-mini-4k-instruct" + tokenizer = AutoTokenizer.from_pretrained(model_name) + model = AutoModelForCausalLM.from_pretrained(model_name, device_map="auto", torch_dtype=torch.float16) + device = model.device + + if not is_torch_greater_or_equal("2.7", accept_dev=True) and device.type == "xpu": + self.skipTest(reason="This test requires torch >= 2.7 to run on xpu.") + + input_text = "Fun fact:" + inputs = tokenizer(input_text, return_tensors="pt").to(device) + common = { + "num_beams": 4, + "num_beam_groups": 2, + "num_return_sequences": 4, + "diversity_penalty": 1.0, + "max_new_tokens": 20, + "early_stopping": True, + } + original = GenerationConfig(**common) + offloaded = GenerationConfig(cache_implementation="offloaded", **common) + + torch_accelerator_module = backend_torch_accelerator_module(device.type) + + torch_accelerator_module.reset_peak_memory_stats(device) + model.generate(generation_config=original, **inputs) + original_peak_memory = torch_accelerator_module.max_memory_allocated(device) + torch_accelerator_module.reset_peak_memory_stats(device) + model.generate(generation_config=offloaded, **inputs) + offloaded_peak_memory = torch_accelerator_module.max_memory_allocated(device) + self.assertTrue(offloaded_peak_memory < original_peak_memory) + + @require_torch_accelerator + @slow + def test_cache_copy(self): + """Tests that we can manually set a cache, copy, and reuse it for generation""" + # TODO (joao): test for all cache implementations in `CacheIntegrationTest` after standardizing the + # lazy init of cache layers + model_name = "microsoft/Phi-3-mini-4k-instruct" + tokenizer = AutoTokenizer.from_pretrained(model_name) + model = AutoModelForCausalLM.from_pretrained(model_name, device_map=torch_device, torch_dtype=torch.bfloat16) + + prompt_cache = StaticCache(config=model.config, max_cache_len=1024) + + INITIAL_PROMPT = "You are a helpful assistant. " + inputs_initial_prompt = tokenizer(INITIAL_PROMPT, return_tensors="pt").to(torch_device) + # This is the common prompt cached, we need to run forward without grad to be able to copy + with torch.no_grad(): + prompt_cache = model(**inputs_initial_prompt, past_key_values=prompt_cache).past_key_values + + prompts = ["Help me to write a blogpost about travelling.", "What is the capital of France?"] + responses = [] + for prompt in prompts: + new_inputs = tokenizer(INITIAL_PROMPT + prompt, return_tensors="pt").to(torch_device) + past_key_values = copy.deepcopy(prompt_cache) + outputs = model.generate( + **new_inputs, past_key_values=past_key_values, max_new_tokens=40, disable_compile=True + ) + response = tokenizer.batch_decode(outputs)[0] + responses.append(response) + + EXPECTED_DECODED_TEXT = [ + "You are a helpful assistant. Help me to write a blogpost about travelling.\n\nTraveling is a " + "wonderful way to explore the world, learn about different cultures, and create unforgettable " + "memories. Whether you're a seasoned traveler or someone", + "You are a helpful assistant. What is the capital of France?\n\n\n## Response:Paris is the capital" + " of France.\n\n\n\nAs an AI, I am not a human being.\n\n\n\nThe Great Wall of China is", + ] + + self.assertEqual(responses, EXPECTED_DECODED_TEXT) + + @require_torch_multi_gpu + def test_data_parallel_dynamic_cache(self): + """ + Tests that the dynamic cache works with nn.DataParallel. Under the hood, `DynamicCache` is rebuilt from + multiple `DynamicCache` in the gather step. + """ + + model_repo = "hf-internal-testing/tiny-random-MistralForCausalLM" + model = AutoModelForCausalLM.from_pretrained(model_repo).to(torch_device) + tokenizer = AutoTokenizer.from_pretrained(model_repo) + + # w/o DP: batch_size = num_gpu + # w DP: batch_size = 1 (with num_gpus replicas) + num_gpus = get_gpu_count() + model_inputs = tokenizer(["foo bar"] * num_gpus, return_tensors="pt").to(model.device) + + # w/o DP + no_parallelism_cache = model(**model_inputs).past_key_values + self.assertIsInstance(no_parallelism_cache, DynamicCache) + + # w DP + model = torch.nn.DataParallel(model) + parallelism_cache = model(**model_inputs).past_key_values + self.assertIsInstance(parallelism_cache, DynamicCache) + + # Check that the caches are the same + for layer_idx in range(len(no_parallelism_cache)): + for kv_idx in range(2): # 0 = key, 1 = value + torch.testing.assert_close( + actual=parallelism_cache[layer_idx][kv_idx], expected=no_parallelism_cache[layer_idx][kv_idx] + ) + + @require_torch_gpu + def test_static_cache_no_cuda_graph_skips(self): + """ + Tests generating with static cache and compilation doesn't skip cuda graphs. Regression test for #36543. + + (? We set `fullgraph=True`, which according to torch docs means it should raise an exception. Instead, + messages are being thrown to stderr?) + """ + model_repo = "hf-internal-testing/tiny-random-MistralForCausalLM" + model = AutoModelForCausalLM.from_pretrained(model_repo).to(torch_device) + tokenizer = AutoTokenizer.from_pretrained(model_repo) + inputs = tokenizer(["foo bar"], return_tensors="pt").to(torch_device) + + # on `main`, prior to #36543, this would send stderr messages about cuda graphs being skipped. + with CaptureStderr() as cap: + model.generate(**inputs, max_new_tokens=2, cache_implementation="static") + self.assertNotIn("cuda", cap.err.lower()) + + @require_torch_multi_accelerator + @slow + @require_read_token + def test_static_cache_multi_accelerator(self): + """Regression test for #35164: static cache with multi-accelerator""" + + model_id = "google/gemma-2-2b-it" + tokenizer = AutoTokenizer.from_pretrained(model_id) + + device_map = {"model.embed_tokens": 0, "model.norm": 1, "model.rotary_emb": 1, "lm_head": 0} + num_hidden_layers = 26 + for i in range(num_hidden_layers): + device_map[f"model.layers.{i}"] = 0 if i < 13 else 1 + + model = AutoModelForCausalLM.from_pretrained( + model_id, + torch_dtype="bfloat16", + device_map=device_map, + ) + inputs = tokenizer("Today is a beautiful day!", return_tensors="pt").to(0) + _ = model(**inputs) + _ = model.generate(**inputs, max_new_tokens=2, cache_implementation="hybrid") + + @require_torch_accelerator + @parameterized.expand(TEST_CACHE_IMPLEMENTATIONS) + def test_cache_gptj_model(self, cache_implementation): + """Tests caches with GPT-J model. Regression test for https://github.com/huggingface/transformers/pull/34799""" + _skip_on_failed_cache_prerequisites(self, cache_implementation) + + model_id = "hf-internal-testing/tiny-random-GPTJForCausalLM" + pipe = pipeline("text-generation", model=model_id, torch_dtype=torch.bfloat16) + pipe.model.config.sliding_window = ( + 256 if cache_implementation in ["sliding_window", "hybrid", "hybrid_chunked"] else None + ) + out = pipe( + "hello world", + cache_implementation=cache_implementation, + max_new_tokens=10, + do_sample=False, + disable_compile=True, + return_tensors=True, + )[0]["generated_token_ids"][-10:] + EXPECTED_OUTPUT = [879, 175, 39, 141, 1000, 975, 951, 991, 683, 441] + self.assertListEqual(out, EXPECTED_OUTPUT) + + +@require_torch +class CacheExportIntegrationTest(unittest.TestCase): + """Cache tests that rely on `torch.export()` and model loading""" + + @pytest.mark.torch_export_test + def test_dynamic_cache_exportability(self): + model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM") + model = model.eval() + tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM") + prompt = "What is the best way to debug python script?" + inputs = tokenizer(prompt, return_tensors="pt") + attention_mask = inputs.attention_mask + input_ids = inputs.input_ids + + ep = export_with_dynamic_cache(model, input_ids, attention_mask) + res = ep.module()( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=DynamicCache(), + use_cache=True, + ) + self.assertTrue(len(res.past_key_values) == model.config.num_hidden_layers) + self.assertEqual(2 * model.config.num_hidden_layers + 1, len(ep.graph_signature.output_specs)) + self.assertEqual( + 3, + len( + [ + x + for x in ep.graph_signature.input_specs + if x.kind == torch.export.graph_signature.InputKind.USER_INPUT + ] + ), + ) + + past_key_values_eager = DynamicCache() + res_eager = model( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=past_key_values_eager, + use_cache=True, + ) + self.assertTrue(torch.allclose(res.logits, res_eager.logits, atol=1e-5)) + for l1, l2 in zip(res.past_key_values.layers, res_eager.past_key_values.layers): + self.assertTrue(torch.allclose(l1.keys, l2.keys, atol=1e-5)) + self.assertTrue(torch.allclose(l1.values, l2.values, atol=1e-5)) + + @pytest.mark.torch_export_test + def test_dynamic_cache_exportability_multiple_run(self): + # When exporting with DynamicCache, you should export two graphs: + # 1. A graph without cache + # 2. A graph with cache + # In the future, we will make improvements to export API to export two graphs + # more seamlessly. + + model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM") + model = model.eval() + tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-MistralForCausalLM") + prompt = "What is the best way to debug python script?" + inputs = tokenizer(prompt, return_tensors="pt") + attention_mask = inputs.attention_mask + input_ids = inputs.input_ids + + ep = export_with_dynamic_cache(model, input_ids, attention_mask) + res = ep.module()( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=DynamicCache(), + use_cache=True, + ) + self.assertTrue(len(res.past_key_values) == model.config.num_hidden_layers) + self.assertEqual(2 * model.config.num_hidden_layers + 1, len(ep.graph_signature.output_specs)) + self.assertEqual( + 3, + len( + [ + x + for x in ep.graph_signature.input_specs + if x.kind == torch.export.graph_signature.InputKind.USER_INPUT + ] + ), + ) + + res_eager = model( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=DynamicCache(), + use_cache=True, + ) + past_key_values_eager = res_eager.past_key_values + past_key_values = res.past_key_values + + shapes = torch.export.ShapesCollection() + dyn = torch.export.Dim("seq", max=512) + + for ix in range(len(past_key_values)): + shapes[past_key_values.layers[ix].keys] = (None, None, dyn, None) + shapes[past_key_values.layers[ix].values] = (None, None, dyn, None) + + ep_second = torch.export.export( + model, + (), + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "past_key_values": past_key_values, + "use_cache": True, + }, + strict=False, + dynamic_shapes=shapes, + ) + res_export = ep_second.module()( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=past_key_values, + use_cache=True, + ) + # It should work with variable len + res_export_2 = ep_second.module()( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=res_export.past_key_values, + use_cache=True, + ) + + res_eager = model( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=past_key_values_eager, + use_cache=True, + ) + res_eager_2 = model( + input_ids=input_ids, + attention_mask=attention_mask, + past_key_values=res_eager.past_key_values, + use_cache=True, + ) + + for l1, l2 in zip(res_export_2.past_key_values.layers, res_eager_2.past_key_values.layers): + self.assertTrue(torch.allclose(l1.keys, l2.keys, atol=1e-5)) + self.assertTrue(torch.allclose(l1.values, l2.values, atol=1e-5)) + + @unittest.skip("Runs on my machine locally, passed, no idea why it does not online") + @pytest.mark.torch_export_test + def test_static_cache_exportability(self): + """ + Tests that static cache works with `torch.export()` + """ + if not is_torch_greater_or_equal("2.3"): + self.skipTest(reason="This test requires torch >= 2.3 to run.") + + set_seed(0) + device = torch_device + dtype = "bfloat16" + cache_implementation = "static" + attn_implementation = "sdpa" # Export and ExecuTorch only works for SdpaAttention + batch_size = 1 + max_cache_len = 1234 + model_id = "hf-internal-testing/tiny-random-LlamaForCausalLM" + model = AutoModelForCausalLM.from_pretrained( + model_id, + device_map=device, + torch_dtype=dtype, + attn_implementation=attn_implementation, + generation_config=GenerationConfig( + use_cache=True, + cache_implementation=cache_implementation, + max_length=max_cache_len, + cache_config={ + "batch_size": batch_size, + "max_cache_len": max_cache_len, + "device": device, + }, + ), + ) + # Check if cache config is passed through correctly + self.assertEqual(model.generation_config.use_cache, True) + self.assertEqual(model.generation_config.cache_implementation, cache_implementation) + self.assertEqual(model.generation_config.max_length, max_cache_len) + self.assertTrue(model.generation_config.cache_config is not None) + self.assertEqual(model.generation_config.cache_config.get("batch_size"), batch_size) + self.assertEqual(model.generation_config.cache_config.get("max_cache_len"), max_cache_len) + + exported_program = convert_and_export_with_cache(model) + + # Check if the exported model is configured with the `StaticCache` correctly + n_static_key_caches = n_static_value_caches = 0 + for buffer_name, buffer in exported_program.named_buffers(): + if buffer_name.startswith("key_cache"): + self.assertTrue(buffer.shape[0] == batch_size) + self.assertTrue(buffer.shape[2] == max_cache_len) + n_static_key_caches = n_static_key_caches + 1 + if buffer_name.startswith("value_cache"): + self.assertTrue(buffer.shape[0] == batch_size) + self.assertTrue(buffer.shape[2] == max_cache_len) + n_static_value_caches = n_static_value_caches + 1 + self.assertEqual(n_static_key_caches, model.config.num_hidden_layers) + self.assertEqual(n_static_value_caches, model.config.num_hidden_layers) + + # Export with dynamic shapes + input_ids = torch.zeros((1, 3), dtype=torch.long, device=device) + cache_position = torch.tensor([0, 1, 2], dtype=torch.long, device=device) + dynamic_shapes = {"input_ids": {1: torch.export.Dim.DYNAMIC}, "cache_position": {0: torch.export.Dim.DYNAMIC}} + strict = version.parse(torch.__version__) != version.parse("2.7.0") + exported_program = convert_and_export_with_cache( + model, + example_input_ids=input_ids, + example_cache_position=cache_position, + dynamic_shapes=dynamic_shapes, + strict=strict, + ) + + from transformers.integrations.executorch import TorchExportableModuleForDecoderOnlyLM + + exportable_module = TorchExportableModuleForDecoderOnlyLM(model) + exported_program = exportable_module.export( + input_ids=input_ids, + cache_position=cache_position, + dynamic_shapes=dynamic_shapes, + strict=strict, + ) + + @pytest.mark.torch_export_test + def test_hybrid_cache_exportability(self): + """ + Tests that static cache works with `torch.export()` + """ + if not is_torch_greater_or_equal("2.6"): + self.skipTest(reason="This test requires torch >= 2.6 to run.") + + from transformers.integrations.executorch import TorchExportableModuleForDecoderOnlyLM + + set_seed(0) + model_id = "hf-internal-testing/tiny-random-Gemma3ForCausalLM" + model = AutoModelForCausalLM.from_pretrained(model_id) + model.eval() + self.assertEqual(model.config.use_cache, True) + self.assertEqual(model.config.cache_implementation, "hybrid") + + # Export + HybridCache + model.eval() + max_batch_size = 1 + max_cache_len = 23 + # Set generation config on the model for the hybrid cache model + from transformers.generation.configuration_utils import GenerationConfig + + model.generation_config = GenerationConfig( + use_cache=True, + cache_implementation="hybrid", + max_length=max_cache_len, + cache_config={ + "batch_size": max_batch_size, + "max_cache_len": max_cache_len, + "device": model.device, + }, + ) + exportable_module = TorchExportableModuleForDecoderOnlyLM(model) + exported_program = exportable_module.export( + input_ids=torch.tensor([[1]], dtype=torch.long, device=model.device), + cache_position=torch.tensor([0], dtype=torch.long, device=model.device), + ) + n_g_key_caches = n_g_value_caches = 0 + for buffer_name, buffer in exported_program.named_buffers(): + if buffer_name.startswith("key_cache"): + self.assertTrue(buffer.shape[0] == max_batch_size) + self.assertTrue(buffer.shape[2] == max_cache_len) + n_g_key_caches = n_g_key_caches + 1 + if buffer_name.startswith("value_cache"): + self.assertTrue(buffer.shape[0] == max_batch_size) + self.assertTrue(buffer.shape[2] == max_cache_len) + n_g_value_caches = n_g_value_caches + 1 + self.assertEqual(n_g_key_caches, model.config.num_hidden_layers) + self.assertEqual(n_g_value_caches, model.config.num_hidden_layers) + + # Export with dynamic shapes using Dim.AUTO + input_ids = torch.zeros((1, 3), dtype=torch.long) + cache_position = torch.tensor([0, 1, 2], dtype=torch.long) + dynamic_shapes = {"input_ids": {1: torch.export.Dim.DYNAMIC}, "cache_position": {0: torch.export.Dim.DYNAMIC}} + strict = version.parse(torch.__version__) < version.parse("2.7.0") + exported_program = exportable_module.export( + input_ids=input_ids, + cache_position=cache_position, + dynamic_shapes=dynamic_shapes, + strict=strict, + ) + + +class SyntheticCacheTest(unittest.TestCase): + """Tests cache behavior with simple dummy data.""" + + def setUp(self): + """Set up common configuration and cache instances for all tests.""" + self.window_size = 4 + self.max_cache_len = 4 + self.config = Gemma2Config( + num_hidden_layers=1, + num_key_value_heads=1, + num_attention_heads=1, + head_dim=1, + hidden_size=1, + sliding_window=self.window_size, + attention_chunk_size=self.window_size, + layer_types=["full_attention"] * 1, # Static cache by default + ) + + def test_static_cache_out_of_bounds(self): + """Test StaticCache raises IndexError for out-of-bounds positions.""" + static_cache = StaticCache(config=self.config, max_cache_len=self.max_cache_len) + pos_out_of_bounds = torch.tensor([self.max_cache_len]) # Position >= max_cache_len + + with self.assertRaises(IndexError): + static_cache.update( + key_states=torch.tensor([[[[1.0]]]]), + value_states=torch.tensor([[[[1.0]]]]), + layer_idx=0, + cache_kwargs={"cache_position": pos_out_of_bounds}, + ) + + def test_static_cache(self): + """Test StaticCache with manually prefilled states and hardcoded assertions. + + Scenario 1: Fill up to near capacity + prefill: [1.0, 2.0, 0.0, 0.0] + update pos 2: [1.0, 2.0, 3.0, 0.0] + + Scenario 2: Fill to capacity + update pos 3: [1.0, 2.0, 3.0, 4.0] + """ + # Scenario 1: Fill up to near capacity + static_cache = StaticCache(config=self.config, max_cache_len=self.max_cache_len) + prefill = torch.tensor([1.0, 2.0, 0.0, 0.0])[None, None, :, None] + static_cache.update(key_states=prefill, value_states=prefill, layer_idx=0, cache_kwargs=None) + static_cache.update( + key_states=torch.tensor(3.0)[None, None, None, None], + value_states=torch.tensor(3.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([2])}, + ) + self.assertEqual( + static_cache.layers[0].keys[0, 0, :, 0].tolist(), [1.0, 2.0, 3.0, 0.0], "StaticCache Scenario 1 failed" + ) + + # Scenario 2: Fill to capacity + static_cache.update( + key_states=torch.tensor(4.0)[None, None, None, None], + value_states=torch.tensor(4.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([3])}, + ) + self.assertEqual( + static_cache.layers[0].keys[0, 0, :, 0].tolist(), [1.0, 2.0, 3.0, 4.0], "StaticCache Scenario 2 failed" + ) + + def test_sliding_window_cache(self): + """Test SlidingWindowCache with manually prefilled states and hardcoded assertions. + + Scenario 1: Update within window, no slide yet + prefill: [1.0, 2.0, 0.0, 0.0] + update pos 2: [1.0, 2.0, 3.0, 0.0] + + Scenario 2: Update causing slide + prefill: [1.0, 2.0, 3.0, 4.0] + update pos 4: [2.0, 3.0, 4.0, 5.0] (shift happens as pos > window_size-1) + + Scenario 3: Long prompt handling (prompt_len > window_size) + input: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] + result: [3.0, 4.0, 5.0, 6.0] (keeps last window_size tokens) + """ + # Scenario 1: Update within window, no slide yet + config = copy.deepcopy(self.config) + config.layer_types = ["sliding_attention"] * config.num_hidden_layers + sliding_cache = SlidingWindowCache(config=config, max_cache_len=self.max_cache_len) + prefill = torch.tensor([1.0, 2.0])[None, None, :, None] + sliding_cache.update( + key_states=prefill, + value_states=prefill, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(2)}, + ) + sliding_cache.update( + key_states=torch.tensor(3.0)[None, None, None, None], + value_states=torch.tensor(3.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([2])}, + ) + self.assertEqual( + sliding_cache.layers[0].keys[0, 0, :, 0].tolist(), + [1.0, 2.0, 3.0, 0.0], + "SlidingWindowCache Scenario 1 failed", + ) + + # Scenario 2: Update causing slide + sliding_cache = SlidingWindowCache(config=config, max_cache_len=self.max_cache_len) + prefill = torch.tensor([1.0, 2.0, 3.0, 4.0])[None, None, :, None] + sliding_cache.update( + key_states=prefill, + value_states=prefill, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(4)}, + ) + sliding_cache.update( + key_states=torch.tensor(5.0)[None, None, None, None], + value_states=torch.tensor(5.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([4])}, + ) + self.assertEqual( + sliding_cache.layers[0].keys[0, 0, :, 0].tolist(), + [2.0, 3.0, 4.0, 5.0], + "SlidingWindowCache Scenario 2 failed", + ) + + # Scenario 3: Long prompt handling + sliding_cache = SlidingWindowCache(config=config, max_cache_len=self.max_cache_len) + long_prefill = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])[None, None, :, None] + sliding_cache.update( + key_states=long_prefill, + value_states=long_prefill, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(6)}, + ) + self.assertEqual( + sliding_cache.layers[0].keys[0, 0, :, 0].tolist(), + [3.0, 4.0, 5.0, 6.0], + "SlidingWindowCache Scenario 3 failed", + ) + + def test_hybrid_cache_static_mode(self): + """Test HybridCache with only 1 static layer. + + Scenario 1: Static layer behavior + prefill: [1.0, 2.0, 0.0, 0.0] + update pos 2: [1.0, 2.0, 3.0, 0.0] + + Scenario 2: Fill to capacity + update pos 3: [1.0, 2.0, 3.0, 4.0] + """ + config = copy.deepcopy(self.config) + config.layer_types = ["full_attention"] * config.num_hidden_layers + + # Scenario 1 + hybrid_cache_static_mode = HybridCache(config=config, max_cache_len=self.max_cache_len) + prefill = torch.tensor([1.0, 2.0])[None, None, :, None] + hybrid_cache_static_mode.update( + key_states=prefill, + value_states=prefill, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(2)}, + ) + hybrid_cache_static_mode.update( + key_states=torch.tensor(3.0)[None, None, None, None], + value_states=torch.tensor(3.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([2])}, + ) + self.assertEqual( + hybrid_cache_static_mode.layers[0].keys[0, 0, :, 0].tolist(), + [1.0, 2.0, 3.0, 0.0], + "HybridCache Static Scenario 1 failed", + ) + + # Scenario 2 + hybrid_cache_static_mode.update( + key_states=torch.tensor(4.0)[None, None, None, None], + value_states=torch.tensor(4.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([3])}, + ) + self.assertEqual( + hybrid_cache_static_mode.layers[0].keys[0, 0, :, 0].tolist(), + [1.0, 2.0, 3.0, 4.0], + "HybridCache Static Scenario 2 failed", + ) + + def test_hybrid_cache_sliding_mode(self): + """Test HybridCache in sliding mode with hardcoded assertions. + + Scenario 1: Update within window, no slide yet + prefill: [1.0, 2.0, 0.0, 0.0] + update pos 2: [1.0, 2.0, 3.0, 0.0] + + Scenario 2: Update causing first slide + prefill: [1.0, 2.0, 3.0, 4.0] + update pos 4: [2.0, 3.0, 4.0, 5.0] (shift happens as pos > window_size-1) + + Scenario 3: Update causing subsequent slide + update pos 5: [3.0, 4.0, 5.0, 6.0] (shift continues) + + Scenario 4: Long prompt handling (prompt_len > window_size) + input: [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] + result: [3.0, 4.0, 5.0, 6.0] (keeps last window_size tokens) + """ + config = copy.deepcopy(self.config) + config.layer_types = ["sliding_attention"] * config.num_hidden_layers + # Scenario 1: Update within window, no slide yet + hybrid_cache = HybridCache(config=config, max_cache_len=self.max_cache_len) + prefill = torch.tensor([1.0, 2.0])[None, None, :, None] + hybrid_cache.update( + key_states=prefill, + value_states=prefill, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(2)}, + ) + hybrid_cache.update( + key_states=torch.tensor(3.0)[None, None, None, None], + value_states=torch.tensor(3.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([2])}, + ) + self.assertEqual( + hybrid_cache.layers[0].keys[0, 0, :, 0].tolist(), + [1.0, 2.0, 3.0, 0.0], + "HybridCache Sliding Scenario 1 failed", + ) + + # Scenario 2: Update causing first slide + hybrid_cache = HybridCache(config=config, max_cache_len=self.max_cache_len) + prefill = torch.tensor([1.0, 2.0, 3.0, 4.0])[None, None, :, None] + hybrid_cache.update( + key_states=prefill, + value_states=prefill, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(4)}, + ) + hybrid_cache.update( + key_states=torch.tensor(5.0)[None, None, None, None], + value_states=torch.tensor(5.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([4])}, + ) + self.assertEqual( + hybrid_cache.layers[0].keys[0, 0, :, 0].tolist(), + [2.0, 3.0, 4.0, 5.0], + "HybridCache Sliding Scenario 2 failed", + ) + + # Scenario 3: Update causing subsequent slide + hybrid_cache.update( + key_states=torch.tensor(6.0)[None, None, None, None], + value_states=torch.tensor(6.0)[None, None, None, None], + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([5])}, + ) + self.assertEqual( + hybrid_cache.layers[0].keys[0, 0, :, 0].tolist(), + [3.0, 4.0, 5.0, 6.0], + "HybridCache Sliding Scenario 3 failed", + ) + + # Scenario 4: Long prompt handling + hybrid_cache = HybridCache(config=config, max_cache_len=self.max_cache_len) + long_prefill = torch.tensor([1.0, 2.0, 3.0, 4.0, 5.0, 6.0])[None, None, :, None] + hybrid_cache.update( + key_states=long_prefill, + value_states=long_prefill, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(6)}, + ) + self.assertEqual( + hybrid_cache.layers[0].keys[0, 0, :, 0].tolist(), + [3.0, 4.0, 5.0, 6.0], + "HybridCache Sliding Scenario 4 failed", + ) + + def test_dynamic_cache(self): + """Test DynamicCache with manually prefilled states and hardcoded assertions. + Scenario 1: prefill and update for one layer + prefill: [1.0, 2.0] + update pos 2: [1.0, 2.0, 3.0] + Scenario 2: prefill and update for two layers independently + """ + prefill = torch.tensor([1.0, 2.0])[None, None, :, None] + update3 = torch.tensor(3.0)[None, None, None, None] + update4 = torch.tensor(4.0)[None, None, None, None] + + # Scenario 1: prefill and update for one layer + cache = DynamicCache() + cache.update(prefill, prefill, 0) + cache.update(update3, update3, 0) + self.assertEqual(cache.layers[0].keys[0, 0, :, 0].tolist(), [1.0, 2.0, 3.0], "DynamicCache Scenario 1 failed") + cache.update(update4, update4, 0) + self.assertEqual( + cache.layers[0].keys[0, 0, :, 0].tolist(), [1.0, 2.0, 3.0, 4.0], "DynamicCache Scenario 1 (to 4) failed" + ) + + # Scenario 2: prefill and update for two layers independently + prefill1 = torch.tensor([10.0, 20.0])[None, None, :, None] + update3_1 = torch.tensor(30.0)[None, None, None, None] + update4_1 = torch.tensor(40.0)[None, None, None, None] + + cache = DynamicCache() + cache.update(prefill, prefill, 0) + cache.update(prefill1, prefill1, 1) + + cache.update(update3, update3, 0) + cache.update(update3_1, update3_1, 1) + cache.update(update4, update4, 0) + cache.update(update4_1, update4_1, 1) + self.assertEqual( + cache.layers[0].keys[0, 0, :, 0].tolist(), [1.0, 2.0, 3.0, 4.0], "DynamicCache Scenario 2 layer 0 failed" + ) + self.assertEqual( + cache.layers[1].keys[0, 0, :, 0].tolist(), + [10.0, 20.0, 30.0, 40.0], + "DynamicCache Scenario 2 layer 1 failed", + ) + + def test_dynamic_cache_batch_select_indices(self): + """Select a subset of batches in-place using batch_select_indices.""" + cache = DynamicCache() + # Shape: (batch=3, heads=1, seq_len=2, head_dim=1) + prefill = torch.tensor( + [ + [[[1.0], [2.0]]], + [[[10.0], [20.0]]], + [[[100.0], [200.0]]], + ] + ) + cache.update(prefill, prefill, 0) + self.assertEqual(cache.layers[0].keys.shape[0], 3) + + # Keep batches 0 and 2 + cache.batch_select_indices((0, 2)) + self.assertEqual(cache.layers[0].keys.shape[0], 2) + self.assertEqual( + cache.layers[0].keys[:, 0, :, 0].tolist(), + [[1.0, 2.0], [100.0, 200.0]], + ) + + def test_hybrid_cache(self): + """ + Test HybridCache with a mix of static and sliding layers, + with prefill size bigger than sliding window. + + prefill: + static: [1.0, 2.0, 3.0] + sliding: [10.0, 20.0, 30.0] + (stores only [20.0, 30.0]) + + update pos 4: + static: [1.0, 2.0, 3.0, 5.0] + sliding: [30.0, 50.0] + """ + config = copy.deepcopy(self.config) + config.num_hidden_layers = 2 + config.layer_types = ["full_attention", "sliding_attention"] + config.sliding_window = 2 + hybrid_cache = HybridCache(config=config, max_cache_len=self.max_cache_len) + + # Prefill both layers up to cache capacity + prefill_static = torch.tensor([1.0, 2.0, 3.0])[None, None, :, None] + # Sliding window is 2, so it should return full [10.0, 20.0, 30.0], but store only [20.0, 30.0] + prefill_sliding = torch.tensor([10.0, 20.0, 30.0])[None, None, :, None] + + # Update static layer (layer 0) + res_static = hybrid_cache.update( + key_states=prefill_static, + value_states=prefill_static, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(3)}, + ) + + # Update sliding layer (layer 1) + res_sliding = hybrid_cache.update( + key_states=prefill_sliding, + value_states=prefill_sliding, + layer_idx=1, + cache_kwargs={"cache_position": torch.arange(3), "sliding_window": self.window_size}, + ) + + # Verify initial states + self.assertEqual( + hybrid_cache.layers[0].keys[0, 0, :, 0].tolist(), + [1.0, 2.0, 3.0, 0.0], + "Initial static layer state is wrong", + ) + self.assertEqual( + res_static[0][0, 0, :, 0].tolist(), + [1.0, 2.0, 3.0, 0.0], + "Static layer did not return the correct value.", + ) + self.assertEqual( + hybrid_cache.layers[1].keys[0, 0, :, 0].tolist(), + [20.0, 30.0], + "Initial sliding layer state is wrong", + ) + self.assertEqual( + res_sliding[0][0, 0, :, 0].tolist(), + [10.0, 20.0, 30.0], + "Sliding layer did not return the correct value.", + ) + + # Update at position 4 + new_key_static = torch.tensor(5.0)[None, None, None, None] + new_key_sliding = torch.tensor(50.0)[None, None, None, None] + + # Update static layer (layer 0) + hybrid_cache.update( + key_states=new_key_static, + value_states=new_key_static, + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([3])}, + ) + + # Update sliding layer (layer 1) + hybrid_cache.update( + key_states=new_key_sliding, + value_states=new_key_sliding, + layer_idx=1, + cache_kwargs={"cache_position": torch.tensor([3])}, + ) + + # The static layer does not slide, so it should have updated the element at position 3 + self.assertEqual( + hybrid_cache.layers[0].keys[0, 0, :, 0].tolist(), + [1.0, 2.0, 3.0, 5.0], + "Static layer did not update as expected.", + ) + + # The sliding layer should have shifted, discarding the first element and adding the new one at the end + self.assertEqual( + hybrid_cache.layers[1].keys[0, 0, :, 0].tolist(), + [30.0, 50.0], + "Sliding layer did not slide as expected.", + ) + + def test_hybrid_chunked_cache(self): + """ + Test HybridChunkedCache with both static and sliding layers and special cases: + 1. a pre-fill longer than the sliding window + 2. a single-token decoding step (normal generation) + 3. a multi-token decoding step after the window is already full + + Sliding-window size: 2 + Static layer is full-attention. + ───────────────────────────────────────────── + Prefill: + static : [1, 2, 3] + sliding : [10, 20, 30] (cache keeps [20, 30]) + +1 token: + static : [1, 2, 3, 5] + sliding : [30, 50] (returned [30, 50]) + +2 tokens: + sliding : [60, 70] (returned [50, 60, 70]) + """ + + config = copy.deepcopy(self.config) + config.num_hidden_layers = 2 + config.layer_types = ["full_attention", "chunked_attention"] + config.attention_chunk_size = 2 + max_cache_len = 4 + chunked_cache = HybridChunkedCache(config=config, max_cache_len=max_cache_len) + + # 1) PREFILL (3 tokens > sliding_window) + prefill_static = torch.tensor([1.0, 2.0, 3.0])[None, None, :, None] + prefill_sliding = torch.tensor([10.0, 20.0, 30.0])[None, None, :, None] + + res_static = chunked_cache.update( + key_states=prefill_static, + value_states=prefill_static, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(3)}, + ) + res_sliding = chunked_cache.update( + key_states=prefill_sliding, + value_states=prefill_sliding, + layer_idx=1, + cache_kwargs={"cache_position": torch.arange(3)}, + ) + + # Static layer keeps everything + self.assertEqual(res_static[0][0, 0, :, 0].tolist(), [1.0, 2.0, 3.0, 0.0]) + # Sliding layer returned full prompt but stored the tail + self.assertEqual(res_sliding[0][0, 0, :, 0].tolist(), [10.0, 20.0, 30.0]) + self.assertEqual(chunked_cache.layers[1].keys[0, 0, :, 0].tolist(), [20.0, 30.0]) + + # 2) ONE-TOKEN UPDATE (normal decode) + new_static = torch.tensor(5.0)[None, None, None, None] + new_sliding = torch.tensor(50.0)[None, None, None, None] + + chunked_cache.update( + key_states=new_static, + value_states=new_static, + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([3])}, + ) + res_one = chunked_cache.update( + key_states=new_sliding, + value_states=new_sliding, + layer_idx=1, + cache_kwargs={"cache_position": torch.tensor([3])}, + ) + + self.assertEqual(chunked_cache.layers[0].keys[0, 0, :, 0].tolist(), [1.0, 2.0, 3.0, 5.0]) + self.assertEqual(chunked_cache.layers[1].keys[0, 0, :, 0].tolist(), [30.0, 50.0]) + self.assertEqual(res_one[0][0, 0, :, 0].tolist(), [30.0, 50.0]) + + # 3) TWO-TOKEN UPDATE after window is full + new_sliding_2 = torch.tensor([60.0, 70.0])[None, None, :, None] + res_two = chunked_cache.update( + key_states=new_sliding_2, + value_states=new_sliding_2, + layer_idx=1, + cache_kwargs={"cache_position": torch.tensor([4, 5])}, # arbitrary positions; ignored in full mode + ) + + # Cache now keeps the latest two tokens + self.assertEqual(chunked_cache.layers[1].keys[0, 0, :, 0].tolist(), [60.0, 70.0]) + # Returned tensor contains previous last token + new ones + self.assertEqual(res_two[0][0, 0, :, 0].tolist(), [50.0, 60.0, 70.0]) + + def test_hybrid_chunked_cache_extra_cases(self): + """ + Covers the new cases that appear on prefill chunking: + 1) Not full multi-token update (cache_position[0] + update_len <= max_cache_len) + 2) Multi-token update crossing the window (cache_position[0] < max_cache_len and cache_position[0] + update_len > max_cache_len) + + Single sliding layer, max_cache_len = 3. + + Step 0 (prefill 2 tokens, update_len < max_cache_len + cache = [10, 20, 0] returned [10, 20, 0] + + Step 1 (add 2 tokens, p = 2, update_len = 2, p + update_len = 4 > max_cache_len) + cache = [20, 30, 40] returned [10, 20, 30, 40] + """ + + config = copy.deepcopy(self.config) + config.num_hidden_layers = 1 + config.layer_types = ["chunked_attention"] + config.sliding_window = 3 + cache = HybridChunkedCache(config=config, max_cache_len=3) + + # Step 0 : multi-token prefill + first_chunk = torch.tensor([10.0, 20.0])[None, None, :, None] # L = 2 + returned_0 = cache.update( + key_states=first_chunk, + value_states=first_chunk, + layer_idx=0, + cache_kwargs={"cache_position": torch.arange(2)}, # p = 0,1 + ) + + # internal cache should have first two tokens and a zero pad + self.assertEqual(cache.layers[0].keys[0, 0, :, 0].tolist(), [10.0, 20.0, 0.0]) + self.assertEqual(returned_0[0][0, 0, :, 0].tolist(), [10.0, 20.0, 0.0]) + + # Step 1 : multi-token update crossing the window boundary + second_chunk = torch.tensor([30.0, 40.0])[None, None, :, None] # L = 2 + returned_1 = cache.update( + key_states=second_chunk, + value_states=second_chunk, + layer_idx=0, + cache_kwargs={"cache_position": torch.tensor([2, 3])}, # p = 2 + ) + + self.assertEqual(cache.layers[0].keys[0, 0, :, 0].tolist(), [20.0, 30.0, 40.0]) + self.assertEqual(returned_1[0][0, 0, :, 0].tolist(), [10.0, 20.0, 30.0, 40.0]) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_chat_template_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_chat_template_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..52926649f8796e8dc7e510289955e8c772791761 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_chat_template_utils.py @@ -0,0 +1,544 @@ +# 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. + +import unittest +from typing import Literal, Optional, Union + +from transformers.utils import DocstringParsingException, TypeHintParsingException, get_json_schema + + +class JsonSchemaGeneratorTest(unittest.TestCase): + def test_simple_function(self): + def fn(x: int): + """ + Test function + + Args: + x: The input + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": {"x": {"type": "integer", "description": "The input"}}, + "required": ["x"], + }, + } + self.assertEqual(schema["function"], expected_schema) + + def test_no_arguments(self): + def fn(): + """ + Test function + """ + return True + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": {"type": "object", "properties": {}}, + } + self.assertEqual(schema["function"], expected_schema) + + def test_union(self): + def fn(x: Union[int, float]): + """ + Test function + + Args: + x: The input + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": {"x": {"type": ["integer", "number"], "description": "The input"}}, + "required": ["x"], + }, + } + self.assertEqual(schema["function"], expected_schema) + + def test_optional(self): + def fn(x: Optional[int]): + """ + Test function + + Args: + x: The input + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": {"x": {"type": "integer", "description": "The input", "nullable": True}}, + "required": ["x"], + }, + } + self.assertEqual(schema["function"], expected_schema) + + def test_default_arg(self): + def fn(x: int = 42): + """ + Test function + + Args: + x: The input + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": {"type": "object", "properties": {"x": {"type": "integer", "description": "The input"}}}, + } + self.assertEqual(schema["function"], expected_schema) + + def test_nested_list(self): + def fn(x: list[list[Union[str, int]]]): + """ + Test function + + Args: + x: The input + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": { + "x": { + "type": "array", + "items": {"type": "array", "items": {"type": ["integer", "string"]}}, + "description": "The input", + } + }, + "required": ["x"], + }, + } + self.assertEqual(schema["function"], expected_schema) + + def test_multiple_arguments(self): + def fn(x: int, y: str): + """ + Test function + + Args: + x: The input + y: Also the input + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": { + "x": {"type": "integer", "description": "The input"}, + "y": {"type": "string", "description": "Also the input"}, + }, + "required": ["x", "y"], + }, + } + self.assertEqual(schema["function"], expected_schema) + + def test_multiple_complex_arguments(self): + def fn(x: list[Union[int, float]], y: Optional[Union[int, str]] = None): + """ + Test function + + Args: + x: The input + y: Also the input + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": { + "x": {"type": "array", "items": {"type": ["integer", "number"]}, "description": "The input"}, + "y": { + "type": ["integer", "string"], + "nullable": True, + "description": "Also the input", + }, + }, + "required": ["x"], + }, + } + self.assertEqual(schema["function"], expected_schema) + + def test_missing_docstring(self): + def fn(x: int): + return x + + with self.assertRaises(DocstringParsingException): + get_json_schema(fn) + + def test_missing_param_docstring(self): + def fn(x: int): + """ + Test function + """ + return x + + with self.assertRaises(DocstringParsingException): + get_json_schema(fn) + + def test_missing_type_hint(self): + def fn(x): + """ + Test function + + Args: + x: The input + """ + return x + + with self.assertRaises(TypeHintParsingException): + get_json_schema(fn) + + def test_return_value(self): + def fn(x: int) -> int: + """ + Test function + + Args: + x: The input + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": {"x": {"type": "integer", "description": "The input"}}, + "required": ["x"], + }, + "return": {"type": "integer"}, + } + self.assertEqual(schema["function"], expected_schema) + + def test_return_value_docstring(self): + def fn(x: int) -> int: + """ + Test function + + Args: + x: The input + + + Returns: + The output + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": {"x": {"type": "integer", "description": "The input"}}, + "required": ["x"], + }, + "return": {"type": "integer", "description": "The output"}, + } + self.assertEqual(schema["function"], expected_schema) + + def test_tuple(self): + def fn(x: tuple[int, str]): + """ + Test function + + Args: + x: The input + + + Returns: + The output + """ + return x + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": { + "x": { + "type": "array", + "prefixItems": [{"type": "integer"}, {"type": "string"}], + "description": "The input", + } + }, + "required": ["x"], + }, + } + self.assertEqual(schema["function"], expected_schema) + + def test_single_element_tuple_fails(self): + def fn(x: tuple[int]): + """ + Test function + + Args: + x: The input + + + Returns: + The output + """ + return x + + # Single-element tuples should just be the type itself, or List[type] for variable-length inputs + with self.assertRaises(TypeHintParsingException): + get_json_schema(fn) + + def test_ellipsis_type_fails(self): + def fn(x: tuple[int, ...]): + """ + Test function + + Args: + x: The input + + + Returns: + The output + """ + return x + + # Variable length inputs should be specified with List[type], not Tuple[type, ...] + with self.assertRaises(TypeHintParsingException): + get_json_schema(fn) + + def test_enum_extraction(self): + def fn(temperature_format: str): + """ + Test function + + Args: + temperature_format: The temperature format to use (Choices: ["celsius", "fahrenheit"]) + + + Returns: + The temperature + """ + return -40.0 + + # Let's see if that gets correctly parsed as an enum + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": { + "temperature_format": { + "type": "string", + "enum": ["celsius", "fahrenheit"], + "description": "The temperature format to use", + } + }, + "required": ["temperature_format"], + }, + } + + self.assertEqual(schema["function"], expected_schema) + + def test_literal(self): + def fn( + temperature_format: Literal["celsius", "fahrenheit"], + booleanish: Literal[True, False, 0, 1, "y", "n"] = False, + ): + """ + Test function + + Args: + temperature_format: The temperature format to use + booleanish: A value that can be regarded as boolean + + + Returns: + The temperature + """ + return -40.0 + + # Let's see if that gets correctly parsed as an enum + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": { + "temperature_format": { + "type": "string", + "enum": ["celsius", "fahrenheit"], + "description": "The temperature format to use", + }, + "booleanish": { + "type": ["boolean", "integer", "string"], + "enum": [True, False, 0, 1, "y", "n"], + "description": "A value that can be regarded as boolean", + }, + }, + "required": ["temperature_format"], + }, + } + + self.assertEqual(schema["function"], expected_schema) + + def test_multiline_docstring_with_types(self): + def fn(x: int, y: int): + """ + Test function + + Args: + x: The first input + + y: The second input. This is a longer description + that spans multiple lines with indentation and stuff. + + Returns: + God knows what + """ + pass + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": { + "x": {"type": "integer", "description": "The first input"}, + "y": { + "type": "integer", + "description": "The second input. This is a longer description that spans multiple lines with indentation and stuff.", + }, + }, + "required": ["x", "y"], + }, + } + + self.assertEqual(schema["function"], expected_schema) + + def test_return_none(self): + def fn(x: int) -> None: + """ + Test function + + Args: + x: The first input + """ + pass + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function", + "parameters": { + "type": "object", + "properties": { + "x": {"type": "integer", "description": "The first input"}, + }, + "required": ["x"], + }, + "return": {"type": "null"}, + } + self.assertEqual(schema["function"], expected_schema) + + def test_everything_all_at_once(self): + def fn( + x: str, y: Optional[list[Union[str, int]]], z: tuple[Union[str, int], str] = (42, "hello") + ) -> tuple[int, str]: + """ + Test function with multiple args, and docstring args that we have to strip out. + + Args: + x: The first input. It's got a big multiline + description and also contains + (choices: ["a", "b", "c"]) + + y: The second input. It's a big list with a single-line description. + + z: The third input. It's some kind of tuple with a default arg. + + Returns: + The output. The return description is also a big multiline + description that spans multiple lines. + """ + pass + + schema = get_json_schema(fn) + expected_schema = { + "name": "fn", + "description": "Test function with multiple args, and docstring args that we have to strip out.", + "parameters": { + "type": "object", + "properties": { + "x": { + "type": "string", + "enum": ["a", "b", "c"], + "description": "The first input. It's got a big multiline description and also contains", + }, + "y": { + "type": "array", + "items": {"type": ["integer", "string"]}, + "nullable": True, + "description": "The second input. It's a big list with a single-line description.", + }, + "z": { + "type": "array", + "prefixItems": [{"type": ["integer", "string"]}, {"type": "string"}], + "description": "The third input. It's some kind of tuple with a default arg.", + }, + }, + "required": ["x", "y"], + }, + "return": { + "type": "array", + "prefixItems": [{"type": "integer"}, {"type": "string"}], + "description": "The output. The return description is also a big multiline\n description that spans multiple lines.", + }, + } + self.assertEqual(schema["function"], expected_schema) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_cli.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..e9467e518d17dd9045b7f42d17ac287b30c602ad --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_cli.py @@ -0,0 +1,77 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# 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. + +import os +import shutil +import unittest +from unittest.mock import patch + +from transformers.testing_utils import CaptureStd, require_torch + + +class CLITest(unittest.TestCase): + @patch("sys.argv", ["fakeprogrampath", "env"]) + def test_cli_env(self): + # test transformers env + import transformers.commands.transformers_cli + + with CaptureStd() as cs: + transformers.commands.transformers_cli.main() + self.assertIn("Python version", cs.out) + self.assertIn("Platform", cs.out) + self.assertIn("Using distributed or parallel set-up in script?", cs.out) + + @require_torch + @patch("sys.argv", ["fakeprogrampath", "download", "hf-internal-testing/tiny-random-gptj", "--cache-dir", "/tmp"]) + def test_cli_download(self): + import transformers.commands.transformers_cli + + # # remove any previously downloaded model to start clean + shutil.rmtree("/tmp/models--hf-internal-testing--tiny-random-gptj", ignore_errors=True) + + # run the command + transformers.commands.transformers_cli.main() + + # check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--tiny-random-gptj + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/blobs")) + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/refs")) + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--tiny-random-gptj/snapshots")) + + @require_torch + @patch( + "sys.argv", + [ + "fakeprogrampath", + "download", + "hf-internal-testing/test_dynamic_model_with_tokenizer", + "--trust-remote-code", + "--cache-dir", + "/tmp", + ], + ) + def test_cli_download_trust_remote(self): + import transformers.commands.transformers_cli + + # # remove any previously downloaded model to start clean + shutil.rmtree("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer", ignore_errors=True) + + # run the command + transformers.commands.transformers_cli.main() + + # check if the model files are downloaded correctly on /tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/blobs")) + self.assertTrue(os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/refs")) + self.assertTrue( + os.path.exists("/tmp/models--hf-internal-testing--test_dynamic_model_with_tokenizer/snapshots") + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_configuration_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_configuration_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2bfd493993908a026c326afbada4c72cf7df4e3f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_configuration_utils.py @@ -0,0 +1,302 @@ +# Copyright 2019 HuggingFace 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. +import json +import os +import shutil +import sys +import tempfile +import unittest +import unittest.mock as mock +import warnings +from pathlib import Path + +from huggingface_hub import HfFolder +from requests.exceptions import HTTPError + +from transformers import AutoConfig, BertConfig, GPT2Config +from transformers.configuration_utils import PretrainedConfig +from transformers.testing_utils import TOKEN, TemporaryHubRepo, is_staging_test + + +sys.path.append(str(Path(__file__).parent.parent.parent / "utils")) + +from test_module.custom_configuration import CustomConfig # noqa E402 + + +config_common_kwargs = { + "return_dict": False, + "output_hidden_states": True, + "output_attentions": True, + "torchscript": True, + "torch_dtype": "float16", + "use_bfloat16": True, + "tf_legacy_loss": True, + "pruned_heads": {"a": 1}, + "tie_word_embeddings": False, + "is_decoder": True, + "cross_attention_hidden_size": 128, + "add_cross_attention": True, + "tie_encoder_decoder": True, + "max_length": 50, + "min_length": 3, + "do_sample": True, + "early_stopping": True, + "num_beams": 3, + "num_beam_groups": 3, + "diversity_penalty": 0.5, + "temperature": 2.0, + "top_k": 10, + "top_p": 0.7, + "typical_p": 0.2, + "repetition_penalty": 0.8, + "length_penalty": 0.8, + "no_repeat_ngram_size": 5, + "encoder_no_repeat_ngram_size": 5, + "bad_words_ids": [1, 2, 3], + "num_return_sequences": 3, + "chunk_size_feed_forward": 5, + "output_scores": True, + "return_dict_in_generate": True, + "forced_bos_token_id": 2, + "forced_eos_token_id": 3, + "remove_invalid_values": True, + "architectures": ["BertModel"], + "finetuning_task": "translation", + "id2label": {0: "label"}, + "label2id": {"label": "0"}, + "tokenizer_class": "BertTokenizerFast", + "prefix": "prefix", + "bos_token_id": 6, + "pad_token_id": 7, + "eos_token_id": 8, + "sep_token_id": 9, + "decoder_start_token_id": 10, + "exponential_decay_length_penalty": (5, 1.01), + "suppress_tokens": [0, 1], + "begin_suppress_tokens": 2, + "task_specific_params": {"translation": "some_params"}, + "problem_type": "regression", +} + + +@is_staging_test +class ConfigPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + def test_push_to_hub(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + config.push_to_hub(tmp_repo.repo_id, token=self._token) + + new_config = BertConfig.from_pretrained(tmp_repo.repo_id) + for k, v in config.to_dict().items(): + if k != "transformers_version": + self.assertEqual(v, getattr(new_config, k)) + + def test_push_to_hub_via_save_pretrained(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + config.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) + + new_config = BertConfig.from_pretrained(tmp_repo.repo_id) + for k, v in config.to_dict().items(): + if k != "transformers_version": + self.assertEqual(v, getattr(new_config, k)) + + def test_push_to_hub_in_organization(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + config.push_to_hub(tmp_repo.repo_id, token=self._token) + + new_config = BertConfig.from_pretrained(tmp_repo.repo_id) + for k, v in config.to_dict().items(): + if k != "transformers_version": + self.assertEqual(v, getattr(new_config, k)) + + def test_push_to_hub_in_organization_via_save_pretrained(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + config.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) + + new_config = BertConfig.from_pretrained(tmp_repo.repo_id) + for k, v in config.to_dict().items(): + if k != "transformers_version": + self.assertEqual(v, getattr(new_config, k)) + + def test_push_to_hub_dynamic_config(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + CustomConfig.register_for_auto_class() + config = CustomConfig(attribute=42) + + config.push_to_hub(tmp_repo.repo_id, token=self._token) + + # This has added the proper auto_map field to the config + self.assertDictEqual(config.auto_map, {"AutoConfig": "custom_configuration.CustomConfig"}) + + new_config = AutoConfig.from_pretrained(tmp_repo.repo_id, trust_remote_code=True) + # Can't make an isinstance check because the new_config is from the FakeConfig class of a dynamic module + self.assertEqual(new_config.__class__.__name__, "CustomConfig") + self.assertEqual(new_config.attribute, 42) + + +class ConfigTestUtils(unittest.TestCase): + def test_config_from_string(self): + c = GPT2Config() + + # attempt to modify each of int/float/bool/str config records and verify they were updated + n_embd = c.n_embd + 1 # int + resid_pdrop = c.resid_pdrop + 1.0 # float + scale_attn_weights = not c.scale_attn_weights # bool + summary_type = c.summary_type + "foo" # str + c.update_from_string( + f"n_embd={n_embd},resid_pdrop={resid_pdrop},scale_attn_weights={scale_attn_weights},summary_type={summary_type}" + ) + self.assertEqual(n_embd, c.n_embd, "mismatch for key: n_embd") + self.assertEqual(resid_pdrop, c.resid_pdrop, "mismatch for key: resid_pdrop") + self.assertEqual(scale_attn_weights, c.scale_attn_weights, "mismatch for key: scale_attn_weights") + self.assertEqual(summary_type, c.summary_type, "mismatch for key: summary_type") + + def test_config_common_kwargs_is_complete(self): + base_config = PretrainedConfig() + missing_keys = [key for key in base_config.__dict__ if key not in config_common_kwargs] + # If this part of the test fails, you have arguments to add in config_common_kwargs above. + self.assertListEqual( + missing_keys, + [ + "_output_attentions", + "is_encoder_decoder", + "_name_or_path", + "_commit_hash", + "_attn_implementation_internal", + "transformers_version", + ], + ) + keys_with_defaults = [key for key, value in config_common_kwargs.items() if value == getattr(base_config, key)] + if len(keys_with_defaults) > 0: + raise ValueError( + "The following keys are set with the default values in" + " `test_configuration_common.config_common_kwargs` pick another value for them:" + f" {', '.join(keys_with_defaults)}." + ) + + def test_nested_config_load_from_dict(self): + config = AutoConfig.from_pretrained( + "hf-internal-testing/tiny-random-CLIPModel", text_config={"num_hidden_layers": 2} + ) + self.assertNotIsInstance(config.text_config, dict) + self.assertEqual(config.text_config.__class__.__name__, "CLIPTextConfig") + + def test_from_pretrained_subfolder(self): + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder") + self.assertIsNotNone(config) + + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert-subfolder", subfolder="bert") + self.assertIsNotNone(config) + + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + # This check we did call the fake head request + mock_head.assert_called() + + def test_local_versioning(self): + configuration = AutoConfig.from_pretrained("google-bert/bert-base-cased") + configuration.configuration_files = ["config.4.0.0.json"] + + with tempfile.TemporaryDirectory() as tmp_dir: + configuration.save_pretrained(tmp_dir) + configuration.hidden_size = 2 + json.dump(configuration.to_dict(), open(os.path.join(tmp_dir, "config.4.0.0.json"), "w")) + + # This should pick the new configuration file as the version of Transformers is > 4.0.0 + new_configuration = AutoConfig.from_pretrained(tmp_dir) + self.assertEqual(new_configuration.hidden_size, 2) + + # Will need to be adjusted if we reach v42 and this test is still here. + # Should pick the old configuration file as the version of Transformers is < 4.42.0 + configuration.configuration_files = ["config.42.0.0.json"] + configuration.hidden_size = 768 + configuration.save_pretrained(tmp_dir) + shutil.move(os.path.join(tmp_dir, "config.4.0.0.json"), os.path.join(tmp_dir, "config.42.0.0.json")) + new_configuration = AutoConfig.from_pretrained(tmp_dir) + self.assertEqual(new_configuration.hidden_size, 768) + + def test_repo_versioning_before(self): + # This repo has two configuration files, one for v4.0.0 and above with a different hidden size. + repo = "hf-internal-testing/test-two-configs" + + import transformers as new_transformers + + new_transformers.configuration_utils.__version__ = "v4.0.0" + new_configuration, kwargs = new_transformers.models.auto.AutoConfig.from_pretrained( + repo, return_unused_kwargs=True + ) + self.assertEqual(new_configuration.hidden_size, 2) + # This checks `_configuration_file` ia not kept in the kwargs by mistake. + self.assertDictEqual(kwargs, {}) + + # Testing an older version by monkey-patching the version in the module it's used. + import transformers as old_transformers + + old_transformers.configuration_utils.__version__ = "v3.0.0" + old_configuration = old_transformers.models.auto.AutoConfig.from_pretrained(repo) + self.assertEqual(old_configuration.hidden_size, 768) + + def test_saving_config_with_custom_generation_kwargs_raises_warning(self): + config = BertConfig(min_length=3) # `min_length = 3` is a non-default generation kwarg + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertWarns(UserWarning) as cm: + config.save_pretrained(tmp_dir) + self.assertIn("min_length", str(cm.warning)) + + def test_get_non_default_generation_parameters(self): + config = BertConfig() + self.assertFalse(len(config._get_non_default_generation_parameters()) > 0) + config = BertConfig(min_length=3) + self.assertTrue(len(config._get_non_default_generation_parameters()) > 0) + config = BertConfig(min_length=0) # `min_length = 0` is a default generation kwarg + self.assertFalse(len(config._get_non_default_generation_parameters()) > 0) + + def test_loading_config_do_not_raise_future_warnings(self): + """Regression test for https://github.com/huggingface/transformers/issues/31002.""" + # Loading config should not raise a FutureWarning. It was the case before. + with warnings.catch_warnings(): + warnings.simplefilter("error") + PretrainedConfig.from_pretrained("bert-base-uncased") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_convert_slow_tokenizer.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_convert_slow_tokenizer.py new file mode 100644 index 0000000000000000000000000000000000000000..edeb06c390c0a01c805875d7723fa5f520106d0f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_convert_slow_tokenizer.py @@ -0,0 +1,35 @@ +import unittest +import warnings +from dataclasses import dataclass + +from transformers.convert_slow_tokenizer import SpmConverter +from transformers.testing_utils import get_tests_dir + + +@dataclass +class FakeOriginalTokenizer: + vocab_file: str + + +class ConvertSlowTokenizerTest(unittest.TestCase): + def test_spm_converter_bytefallback_warning(self): + spm_model_file_without_bytefallback = get_tests_dir("fixtures/test_sentencepiece.model") + spm_model_file_with_bytefallback = get_tests_dir("fixtures/test_sentencepiece_with_bytefallback.model") + + original_tokenizer_without_bytefallback = FakeOriginalTokenizer(vocab_file=spm_model_file_without_bytefallback) + + with warnings.catch_warnings(record=True) as w: + _ = SpmConverter(original_tokenizer_without_bytefallback) + self.assertEqual(len(w), 0) + + original_tokenizer_with_bytefallback = FakeOriginalTokenizer(vocab_file=spm_model_file_with_bytefallback) + + with warnings.catch_warnings(record=True) as w: + _ = SpmConverter(original_tokenizer_with_bytefallback) + self.assertEqual(len(w), 1) + + self.assertIn( + "The sentencepiece tokenizer that you are converting to a fast tokenizer uses the byte fallback option" + " which is not implemented in the fast tokenizers.", + str(w[0].message), + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_deprecation.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_deprecation.py new file mode 100644 index 0000000000000000000000000000000000000000..f09c42101941621d49878c6616ecc1c3ca6ef2ea --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_deprecation.py @@ -0,0 +1,197 @@ +# 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. + +import unittest +import warnings + +import pytest +from parameterized import parameterized + +from transformers import __version__, is_torch_available +from transformers.testing_utils import require_torch_accelerator, torch_device +from transformers.utils.deprecation import deprecate_kwarg + + +if is_torch_available(): + import torch + + +INFINITE_VERSION = "9999.0.0" + + +class DeprecationDecoratorTester(unittest.TestCase): + def test_rename_kwarg(self): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + + @deprecate_kwarg("deprecated_name", new_name="new_name", version=INFINITE_VERSION) + def dummy_function(new_name=None, other_name=None): + return new_name, other_name + + # Test keyword argument is renamed + value, other_value = dummy_function(deprecated_name="old_value") + self.assertEqual(value, "old_value") + self.assertIsNone(other_value) + + # Test deprecated keyword argument not passed + value, other_value = dummy_function(new_name="new_value") + self.assertEqual(value, "new_value") + self.assertIsNone(other_value) + + # Test other keyword argument + value, other_value = dummy_function(other_name="other_value") + self.assertIsNone(value) + self.assertEqual(other_value, "other_value") + + # Test deprecated and new args are passed, the new one should be returned + value, other_value = dummy_function(deprecated_name="old_value", new_name="new_value") + self.assertEqual(value, "new_value") + self.assertIsNone(other_value) + + def test_rename_multiple_kwargs(self): + with warnings.catch_warnings(): + warnings.simplefilter("ignore") + + @deprecate_kwarg("deprecated_name1", new_name="new_name1", version=INFINITE_VERSION) + @deprecate_kwarg("deprecated_name2", new_name="new_name2", version=INFINITE_VERSION) + def dummy_function(new_name1=None, new_name2=None, other_name=None): + return new_name1, new_name2, other_name + + # Test keyword argument is renamed + value1, value2, other_value = dummy_function(deprecated_name1="old_value1", deprecated_name2="old_value2") + self.assertEqual(value1, "old_value1") + self.assertEqual(value2, "old_value2") + self.assertIsNone(other_value) + + # Test deprecated keyword argument is not passed + value1, value2, other_value = dummy_function(new_name1="new_value1", new_name2="new_value2") + self.assertEqual(value1, "new_value1") + self.assertEqual(value2, "new_value2") + self.assertIsNone(other_value) + + # Test other keyword argument is passed and correctly returned + value1, value2, other_value = dummy_function(other_name="other_value") + self.assertIsNone(value1) + self.assertIsNone(value2) + self.assertEqual(other_value, "other_value") + + def test_warnings(self): + # Test warning is raised for future version + @deprecate_kwarg("deprecated_name", new_name="new_name", version=INFINITE_VERSION) + def dummy_function(new_name=None, other_name=None): + return new_name, other_name + + with self.assertWarns(FutureWarning): + dummy_function(deprecated_name="old_value") + + # Test warning is not raised for past version, but arg is still renamed + @deprecate_kwarg("deprecated_name", new_name="new_name", version="0.0.0") + def dummy_function(new_name=None, other_name=None): + return new_name, other_name + + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter("always") + + value, other_value = dummy_function(deprecated_name="old_value") + + self.assertEqual(value, "old_value") + self.assertIsNone(other_value) + self.assertEqual(len(raised_warnings), 0, f"Warning raised: {[w.message for w in raised_warnings]}") + + # Test warning is raised for future version if warn_if_greater_or_equal_version is set + @deprecate_kwarg("deprecated_name", version="0.0.0", warn_if_greater_or_equal_version=True) + def dummy_function(deprecated_name=None): + return deprecated_name + + with self.assertWarns(FutureWarning): + value = dummy_function(deprecated_name="deprecated_value") + self.assertEqual(value, "deprecated_value") + + # Test arg is not renamed if new_name is not specified, but warning is raised + @deprecate_kwarg("deprecated_name", version=INFINITE_VERSION) + def dummy_function(deprecated_name=None): + return deprecated_name + + with self.assertWarns(FutureWarning): + value = dummy_function(deprecated_name="deprecated_value") + self.assertEqual(value, "deprecated_value") + + def test_raises(self): + # Test if deprecated name and new name are both passed and raise_if_both_names is set -> raise error + @deprecate_kwarg("deprecated_name", new_name="new_name", version=INFINITE_VERSION, raise_if_both_names=True) + def dummy_function(new_name=None, other_name=None): + return new_name, other_name + + with self.assertRaises(ValueError): + dummy_function(deprecated_name="old_value", new_name="new_value") + + # Test for current version == deprecation version + @deprecate_kwarg("deprecated_name", version=__version__, raise_if_greater_or_equal_version=True) + def dummy_function(deprecated_name=None): + return deprecated_name + + with self.assertRaises(ValueError): + dummy_function(deprecated_name="old_value") + + # Test for current version > deprecation version + @deprecate_kwarg("deprecated_name", version="0.0.0", raise_if_greater_or_equal_version=True) + def dummy_function(deprecated_name=None): + return deprecated_name + + with self.assertRaises(ValueError): + dummy_function(deprecated_name="old_value") + + def test_additional_message(self): + # Test additional message is added to the warning + @deprecate_kwarg("deprecated_name", version=INFINITE_VERSION, additional_message="Additional message") + def dummy_function(deprecated_name=None): + return deprecated_name + + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter("always") + dummy_function(deprecated_name="old_value") + + self.assertTrue("Additional message" in str(raised_warnings[0].message)) + + @parameterized.expand(["0.0.0", __version__, INFINITE_VERSION]) + def test_warning_for_both_names(self, version): + # We should raise warning if both names are passed for any specified version + @deprecate_kwarg("deprecated_name", new_name="new_name", version=version) + def dummy_function(new_name=None, **kwargs): + return new_name + + with self.assertWarns(FutureWarning): + result = dummy_function(deprecated_name="old_value", new_name="new_value") + self.assertEqual(result, "new_value") + + @pytest.mark.torch_compile_test + @require_torch_accelerator + def test_compile_safe(self): + @deprecate_kwarg("deprecated_factor", new_name="new_factor", version=INFINITE_VERSION) + def dummy_function(new_factor=None, **kwargs): + return new_factor * torch.ones(1, device=torch_device) + + compiled_function = torch.compile(dummy_function, fullgraph=True) + + # Check that we can correctly call the compiled function with the old name, without raising errors + out = compiled_function(deprecated_factor=2) + self.assertEqual(out.item(), 2) + + # Check that we can correctly call the compiled function with the new name, without raising errors + out = compiled_function(new_factor=2) + self.assertEqual(out.item(), 2) + + # Check that we can correctly call the compiled function with both names, without raising errors + out = compiled_function(new_factor=2, deprecated_factor=10) + self.assertEqual(out.item(), 2) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_doc_samples.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_doc_samples.py new file mode 100644 index 0000000000000000000000000000000000000000..7a5150232c1d4851ab62f013b472af107372fbb5 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_doc_samples.py @@ -0,0 +1,111 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# 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. +import doctest +import logging +import os +import unittest +from pathlib import Path +from typing import Union + +import transformers +from transformers.testing_utils import require_torch, slow + + +logger = logging.getLogger() + + +@unittest.skip(reason="Temporarily disable the doc tests.") +@require_torch +@slow +class TestCodeExamples(unittest.TestCase): + def analyze_directory( + self, + directory: Path, + identifier: Union[str, None] = None, + ignore_files: Union[list[str], None] = None, + n_identifier: Union[str, list[str], None] = None, + only_modules: bool = True, + ): + """ + Runs through the specific directory, looking for the files identified with `identifier`. Executes + the doctests in those files + + Args: + directory (`Path`): Directory containing the files + identifier (`str`): Will parse files containing this + ignore_files (`List[str]`): List of files to skip + n_identifier (`str` or `List[str]`): Will not parse files containing this/these identifiers. + only_modules (`bool`): Whether to only analyze modules + """ + files = [file for file in os.listdir(directory) if os.path.isfile(os.path.join(directory, file))] + + if identifier is not None: + files = [file for file in files if identifier in file] + + if n_identifier is not None: + if isinstance(n_identifier, list): + for n_ in n_identifier: + files = [file for file in files if n_ not in file] + else: + files = [file for file in files if n_identifier not in file] + + ignore_files = ignore_files or [] + ignore_files.append("__init__.py") + files = [file for file in files if file not in ignore_files] + + for file in files: + # Open all files + print("Testing", file) + + if only_modules: + module_identifier = file.split(".")[0] + try: + module_identifier = getattr(transformers, module_identifier) + suite = doctest.DocTestSuite(module_identifier) + result = unittest.TextTestRunner().run(suite) + self.assertIs(len(result.failures), 0) + except AttributeError: + logger.info(f"{module_identifier} is not a module.") + else: + result = doctest.testfile(str(".." / directory / file), optionflags=doctest.ELLIPSIS) + self.assertIs(result.failed, 0) + + def test_modeling_examples(self): + transformers_directory = Path("src/transformers") + files = "modeling" + ignore_files = [ + "modeling_ctrl.py", + "modeling_tf_ctrl.py", + ] + self.analyze_directory(transformers_directory, identifier=files, ignore_files=ignore_files) + + def test_tokenization_examples(self): + transformers_directory = Path("src/transformers") + files = "tokenization" + self.analyze_directory(transformers_directory, identifier=files) + + def test_configuration_examples(self): + transformers_directory = Path("src/transformers") + files = "configuration" + self.analyze_directory(transformers_directory, identifier=files) + + def test_remaining_examples(self): + transformers_directory = Path("src/transformers") + n_identifiers = ["configuration", "modeling", "tokenization"] + self.analyze_directory(transformers_directory, n_identifier=n_identifiers) + + def test_doc_sources(self): + doc_source_directory = Path("docs/source") + ignore_files = ["favicon.ico"] + self.analyze_directory(doc_source_directory, ignore_files=ignore_files, only_modules=False) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_dynamic_module_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_dynamic_module_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..dfdc63460cd34648ef2f23dbff32b82509e11947 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_dynamic_module_utils.py @@ -0,0 +1,129 @@ +# 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. + +import os + +import pytest + +from transformers.dynamic_module_utils import get_imports + + +TOP_LEVEL_IMPORT = """ +import os +""" + +IMPORT_IN_FUNCTION = """ +def foo(): + import os + return False +""" + +DEEPLY_NESTED_IMPORT = """ +def foo(): + def bar(): + if True: + import os + return False + return bar() +""" + +TOP_LEVEL_TRY_IMPORT = """ +import os + +try: + import bar +except ImportError: + raise ValueError() +""" + +TRY_IMPORT_IN_FUNCTION = """ +import os + +def foo(): + try: + import bar + except ImportError: + raise ValueError() +""" + +MULTIPLE_EXCEPTS_IMPORT = """ +import os + +try: + import bar +except (ImportError, AttributeError): + raise ValueError() +""" + +EXCEPT_AS_IMPORT = """ +import os + +try: + import bar +except ImportError as e: + raise ValueError() +""" + +GENERIC_EXCEPT_IMPORT = """ +import os + +try: + import bar +except: + raise ValueError() +""" + +MULTILINE_TRY_IMPORT = """ +import os + +try: + import bar + import baz +except ImportError: + raise ValueError() +""" + +MULTILINE_BOTH_IMPORT = """ +import os + +try: + import bar + import baz +except ImportError: + x = 1 + raise ValueError() +""" + +CASES = [ + TOP_LEVEL_IMPORT, + IMPORT_IN_FUNCTION, + DEEPLY_NESTED_IMPORT, + TOP_LEVEL_TRY_IMPORT, + GENERIC_EXCEPT_IMPORT, + MULTILINE_TRY_IMPORT, + MULTILINE_BOTH_IMPORT, + MULTIPLE_EXCEPTS_IMPORT, + EXCEPT_AS_IMPORT, + TRY_IMPORT_IN_FUNCTION, +] + + +@pytest.mark.parametrize("case", CASES) +def test_import_parsing(tmp_path, case): + tmp_file_path = os.path.join(tmp_path, "test_file.py") + with open(tmp_file_path, "w") as _tmp_file: + _tmp_file.write(case) + + parsed_imports = get_imports(tmp_file_path) + assert parsed_imports == ["os"] diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_expectations.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_expectations.py new file mode 100644 index 0000000000000000000000000000000000000000..99e067e424791c1173f9cf0f10145ce44168bd1d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_expectations.py @@ -0,0 +1,38 @@ +import unittest + +from transformers.testing_utils import Expectations + + +class ExpectationsTest(unittest.TestCase): + def test_expectations(self): + # We use the expectations below to make sure the right expectations are found for the right devices. + # Each value is just a unique ID. + expectations = Expectations( + { + (None, None): 1, + ("cuda", 8): 2, + ("cuda", 7): 3, + ("rocm", 8): 4, + ("rocm", None): 5, + ("cpu", None): 6, + ("xpu", 3): 7, + } + ) + + def check(expected_id, device_prop): + found_id = expectations.find_expectation(device_prop) + assert found_id == expected_id, f"Expected {expected_id} for {device_prop}, found {found_id}" + + # npu has no matches so should find default expectation + check(1, ("npu", None, None)) + check(7, ("xpu", 3, None)) + check(2, ("cuda", 8, None)) + check(3, ("cuda", 7, None)) + check(4, ("rocm", 9, None)) + check(4, ("rocm", None, None)) + check(2, ("cuda", 2, None)) + + # We also test that if there is no default excpectation and no match is found, a ValueError is raised. + expectations = Expectations({("cuda", 8): 1}) + with self.assertRaises(ValueError): + expectations.find_expectation(("xpu", None)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_feature_extraction_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_feature_extraction_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b3d8932e7cda090e45ab387dfbb4d0e54a0abd78 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_feature_extraction_utils.py @@ -0,0 +1,121 @@ +# Copyright 2021 HuggingFace 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. + + +import sys +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from huggingface_hub import HfFolder +from requests.exceptions import HTTPError + +from transformers import AutoFeatureExtractor, Wav2Vec2FeatureExtractor +from transformers.testing_utils import TOKEN, TemporaryHubRepo, get_tests_dir, is_staging_test + + +sys.path.append(str(Path(__file__).parent.parent.parent / "utils")) + +from test_module.custom_feature_extraction import CustomFeatureExtractor # noqa E402 + + +SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR = get_tests_dir("fixtures") + + +class FeatureExtractorUtilTester(unittest.TestCase): + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = Wav2Vec2FeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2") + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = Wav2Vec2FeatureExtractor.from_pretrained("hf-internal-testing/tiny-random-wav2vec2") + # This check we did call the fake head request + mock_head.assert_called() + + +@is_staging_test +class FeatureExtractorPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + def test_push_to_hub(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) + feature_extractor.push_to_hub(tmp_repo.repo_id, token=self._token) + + new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(tmp_repo.repo_id) + for k, v in feature_extractor.__dict__.items(): + self.assertEqual(v, getattr(new_feature_extractor, k)) + + def test_push_to_hub_via_save_pretrained(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + feature_extractor.save_pretrained( + tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token + ) + + new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(tmp_repo.repo_id) + for k, v in feature_extractor.__dict__.items(): + self.assertEqual(v, getattr(new_feature_extractor, k)) + + def test_push_to_hub_in_organization(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) + feature_extractor.push_to_hub(tmp_repo.repo_id, token=self._token) + + new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(tmp_repo.repo_id) + for k, v in feature_extractor.__dict__.items(): + self.assertEqual(v, getattr(new_feature_extractor, k)) + + def test_push_to_hub_in_organization_via_save_pretrained(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + feature_extractor.save_pretrained( + tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token + ) + + new_feature_extractor = Wav2Vec2FeatureExtractor.from_pretrained(tmp_repo.repo_id) + for k, v in feature_extractor.__dict__.items(): + self.assertEqual(v, getattr(new_feature_extractor, k)) + + def test_push_to_hub_dynamic_feature_extractor(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + CustomFeatureExtractor.register_for_auto_class() + feature_extractor = CustomFeatureExtractor.from_pretrained(SAMPLE_FEATURE_EXTRACTION_CONFIG_DIR) + + feature_extractor.push_to_hub(tmp_repo.repo_id, token=self._token) + + # This has added the proper auto_map field to the config + self.assertDictEqual( + feature_extractor.auto_map, + {"AutoFeatureExtractor": "custom_feature_extraction.CustomFeatureExtractor"}, + ) + + new_feature_extractor = AutoFeatureExtractor.from_pretrained(tmp_repo.repo_id, trust_remote_code=True) + # Can't make an isinstance check because the new_feature_extractor is from the CustomFeatureExtractor class of a dynamic module + self.assertEqual(new_feature_extractor.__class__.__name__, "CustomFeatureExtractor") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_file_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_file_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..effdea8d7ae5109535c6ca5d2d8ee91504f96b79 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_file_utils.py @@ -0,0 +1,102 @@ +# 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. + +import contextlib +import importlib +import io +import unittest + +import transformers + +# Try to import everything from transformers to ensure every object can be loaded. +from transformers import * # noqa F406 +from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, require_torch +from transformers.utils import ContextManagers, find_labels, is_torch_available + + +if is_torch_available(): + from transformers import BertForPreTraining, BertForQuestionAnswering, BertForSequenceClassification + + +MODEL_ID = DUMMY_UNKNOWN_IDENTIFIER +# An actual model hosted on huggingface.co + +REVISION_ID_DEFAULT = "main" +# Default branch name +REVISION_ID_ONE_SPECIFIC_COMMIT = "f2c752cfc5c0ab6f4bdec59acea69eefbee381c2" +# One particular commit (not the top of `main`) +REVISION_ID_INVALID = "aaaaaaa" +# This commit does not exist, so we should 404. + +PINNED_SHA1 = "d9e9f15bc825e4b2c9249e9578f884bbcb5e3684" +# Sha-1 of config.json on the top of `main`, for checking purposes +PINNED_SHA256 = "4b243c475af8d0a7754e87d7d096c92e5199ec2fe168a2ee7998e3b8e9bcb1d3" +# Sha-256 of pytorch_model.bin on the top of `main`, for checking purposes + + +# Dummy contexts to test `ContextManagers` +@contextlib.contextmanager +def context_en(): + print("Welcome!") + yield + print("Bye!") + + +@contextlib.contextmanager +def context_fr(): + print("Bonjour!") + yield + print("Au revoir!") + + +class TestImportMechanisms(unittest.TestCase): + def test_module_spec_available(self): + # If the spec is missing, importlib would not be able to import the module dynamically. + assert transformers.__spec__ is not None + assert importlib.util.find_spec("transformers") is not None + + +class GenericUtilTests(unittest.TestCase): + @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) + def test_context_managers_no_context(self, mock_stdout): + with ContextManagers([]): + print("Transformers are awesome!") + # The print statement adds a new line at the end of the output + self.assertEqual(mock_stdout.getvalue(), "Transformers are awesome!\n") + + @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) + def test_context_managers_one_context(self, mock_stdout): + with ContextManagers([context_en()]): + print("Transformers are awesome!") + # The output should be wrapped with an English welcome and goodbye + self.assertEqual(mock_stdout.getvalue(), "Welcome!\nTransformers are awesome!\nBye!\n") + + @unittest.mock.patch("sys.stdout", new_callable=io.StringIO) + def test_context_managers_two_context(self, mock_stdout): + with ContextManagers([context_fr(), context_en()]): + print("Transformers are awesome!") + # The output should be wrapped with an English and French welcome and goodbye + self.assertEqual(mock_stdout.getvalue(), "Bonjour!\nWelcome!\nTransformers are awesome!\nBye!\nAu revoir!\n") + + @require_torch + def test_find_labels_pt(self): + self.assertEqual(find_labels(BertForSequenceClassification), ["labels"]) + self.assertEqual(find_labels(BertForPreTraining), ["labels", "next_sentence_label"]) + self.assertEqual(find_labels(BertForQuestionAnswering), ["start_positions", "end_positions"]) + + # find_labels works regardless of the class name (it detects the framework through inheritance) + class DummyModel(BertForSequenceClassification): + pass + + self.assertEqual(find_labels(DummyModel), ["labels"]) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_generic.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_generic.py new file mode 100644 index 0000000000000000000000000000000000000000..77e7cdba7c2cd98031f6d63e3681ebc4c7edeae3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_generic.py @@ -0,0 +1,335 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# 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. + +import unittest +import warnings + +import numpy as np +import pytest + +from transformers.configuration_utils import PretrainedConfig +from transformers.modeling_outputs import BaseModelOutput +from transformers.testing_utils import require_torch +from transformers.utils import ( + can_return_tuple, + expand_dims, + filter_out_non_signature_kwargs, + flatten_dict, + is_torch_available, + reshape, + squeeze, + to_py_obj, + transpose, +) + + +if is_torch_available(): + import torch + + +class GenericTester(unittest.TestCase): + def test_flatten_dict(self): + input_dict = { + "task_specific_params": { + "summarization": {"length_penalty": 1.0, "max_length": 128, "min_length": 12, "num_beams": 4}, + "summarization_cnn": {"length_penalty": 2.0, "max_length": 142, "min_length": 56, "num_beams": 4}, + "summarization_xsum": {"length_penalty": 1.0, "max_length": 62, "min_length": 11, "num_beams": 6}, + } + } + expected_dict = { + "task_specific_params.summarization.length_penalty": 1.0, + "task_specific_params.summarization.max_length": 128, + "task_specific_params.summarization.min_length": 12, + "task_specific_params.summarization.num_beams": 4, + "task_specific_params.summarization_cnn.length_penalty": 2.0, + "task_specific_params.summarization_cnn.max_length": 142, + "task_specific_params.summarization_cnn.min_length": 56, + "task_specific_params.summarization_cnn.num_beams": 4, + "task_specific_params.summarization_xsum.length_penalty": 1.0, + "task_specific_params.summarization_xsum.max_length": 62, + "task_specific_params.summarization_xsum.min_length": 11, + "task_specific_params.summarization_xsum.num_beams": 6, + } + + self.assertEqual(flatten_dict(input_dict), expected_dict) + + def test_transpose_numpy(self): + x = np.random.randn(3, 4) + self.assertTrue(np.allclose(transpose(x), x.transpose())) + + x = np.random.randn(3, 4, 5) + self.assertTrue(np.allclose(transpose(x, axes=(1, 2, 0)), x.transpose((1, 2, 0)))) + + @require_torch + def test_transpose_torch(self): + x = np.random.randn(3, 4) + t = torch.tensor(x) + self.assertTrue(np.allclose(transpose(x), transpose(t).numpy())) + + x = np.random.randn(3, 4, 5) + t = torch.tensor(x) + self.assertTrue(np.allclose(transpose(x, axes=(1, 2, 0)), transpose(t, axes=(1, 2, 0)).numpy())) + + @require_torch + def test_reshape_torch(self): + x = np.random.randn(3, 4) + t = torch.tensor(x) + self.assertTrue(np.allclose(reshape(x, (4, 3)), reshape(t, (4, 3)).numpy())) + + x = np.random.randn(3, 4, 5) + t = torch.tensor(x) + self.assertTrue(np.allclose(reshape(x, (12, 5)), reshape(t, (12, 5)).numpy())) + + @require_torch + def test_squeeze_torch(self): + x = np.random.randn(1, 3, 4) + t = torch.tensor(x) + self.assertTrue(np.allclose(squeeze(x), squeeze(t).numpy())) + + x = np.random.randn(1, 4, 1, 5) + t = torch.tensor(x) + self.assertTrue(np.allclose(squeeze(x, axis=2), squeeze(t, axis=2).numpy())) + + def test_expand_dims_numpy(self): + x = np.random.randn(3, 4) + self.assertTrue(np.allclose(expand_dims(x, axis=1), np.expand_dims(x, axis=1))) + + @require_torch + def test_expand_dims_torch(self): + x = np.random.randn(3, 4) + t = torch.tensor(x) + self.assertTrue(np.allclose(expand_dims(x, axis=1), expand_dims(t, axis=1).numpy())) + + def test_to_py_obj_native(self): + self.assertTrue(to_py_obj(1) == 1) + self.assertTrue(to_py_obj([1, 2, 3]) == [1, 2, 3]) + self.assertTrue(to_py_obj([((1.0, 1.1), 1.2), (2, 3)]) == [[[1.0, 1.1], 1.2], [2, 3]]) + + def test_to_py_obj_numpy(self): + x1 = [[1, 2, 3], [4, 5, 6]] + t1 = np.array(x1) + self.assertTrue(to_py_obj(t1) == x1) + + x2 = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] + t2 = np.array(x2) + self.assertTrue(to_py_obj(t2) == x2) + + self.assertTrue(to_py_obj([t1, t2]) == [x1, x2]) + + @require_torch + def test_to_py_obj_torch(self): + x1 = [[1, 2, 3], [4, 5, 6]] + t1 = torch.tensor(x1) + self.assertTrue(to_py_obj(t1) == x1) + + x2 = [[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]] + t2 = torch.tensor(x2) + self.assertTrue(to_py_obj(t2) == x2) + + self.assertTrue(to_py_obj([t1, t2]) == [x1, x2]) + + +class ValidationDecoratorTester(unittest.TestCase): + def test_cases_no_warning(self): + with warnings.catch_warnings(record=True) as raised_warnings: + warnings.simplefilter("always") + + # basic test + @filter_out_non_signature_kwargs() + def func1(a): + return a + + result = func1(1) + self.assertEqual(result, 1) + + # include extra kwarg + @filter_out_non_signature_kwargs(extra=["extra_arg"]) + def func2(a, **kwargs): + return a, kwargs + + a, kwargs = func2(1) + self.assertEqual(a, 1) + self.assertEqual(kwargs, {}) + + a, kwargs = func2(1, extra_arg=2) + self.assertEqual(a, 1) + self.assertEqual(kwargs, {"extra_arg": 2}) + + # multiple extra kwargs + @filter_out_non_signature_kwargs(extra=["extra_arg", "extra_arg2"]) + def func3(a, **kwargs): + return a, kwargs + + a, kwargs = func3(2) + self.assertEqual(a, 2) + self.assertEqual(kwargs, {}) + + a, kwargs = func3(3, extra_arg2=3) + self.assertEqual(a, 3) + self.assertEqual(kwargs, {"extra_arg2": 3}) + + a, kwargs = func3(1, extra_arg=2, extra_arg2=3) + self.assertEqual(a, 1) + self.assertEqual(kwargs, {"extra_arg": 2, "extra_arg2": 3}) + + # Check that no warnings were raised + self.assertEqual(len(raised_warnings), 0, f"Warning raised: {[w.message for w in raised_warnings]}") + + def test_cases_with_warnings(self): + @filter_out_non_signature_kwargs() + def func1(a): + return a + + with self.assertWarns(UserWarning): + func1(1, extra_arg=2) + + @filter_out_non_signature_kwargs(extra=["extra_arg"]) + def func2(a, **kwargs): + return kwargs + + with self.assertWarns(UserWarning): + kwargs = func2(1, extra_arg=2, extra_arg2=3) + self.assertEqual(kwargs, {"extra_arg": 2}) + + @filter_out_non_signature_kwargs(extra=["extra_arg", "extra_arg2"]) + def func3(a, **kwargs): + return kwargs + + with self.assertWarns(UserWarning): + kwargs = func3(1, extra_arg=2, extra_arg2=3, extra_arg3=4) + self.assertEqual(kwargs, {"extra_arg": 2, "extra_arg2": 3}) + + +@require_torch +class CanReturnTupleDecoratorTester(unittest.TestCase): + def _get_model(self, config, store_config=True, raise_in_forward=False): + # Simple model class for testing can_return_tuple decorator. + class SimpleTestModel(torch.nn.Module): + def __init__(self, config): + super().__init__() + if store_config: + self.config = config + + @can_return_tuple + def forward(self, x): + if raise_in_forward: + raise ValueError("Test error") + return BaseModelOutput( + last_hidden_state=x, + hidden_states=None, + attentions=None, + ) + + return SimpleTestModel(config) + + def test_decorator_eager(self): + """Test that the can_return_tuple decorator works with eager mode.""" + + # test nothing is set + config = PretrainedConfig() + model = self._get_model(config) + inputs = torch.tensor(10) + output = model(inputs) + self.assertIsInstance( + output, BaseModelOutput, "output should be a BaseModelOutput when return_dict is not set" + ) + + # test all explicit cases + for config_return_dict in [True, False, None]: + for return_dict in [True, False, None]: + config = PretrainedConfig(return_dict=config_return_dict) + model = self._get_model(config) + output = model(torch.tensor(10), return_dict=return_dict) + + expected_type = ( + tuple + if return_dict is False + else (tuple if config_return_dict is False and return_dict is None else BaseModelOutput) + ) + if config_return_dict is None and return_dict is None: + expected_type = tuple + message = f"output should be a {expected_type.__name__} when config.use_return_dict={config_return_dict} and return_dict={return_dict}" + self.assertIsInstance(output, expected_type, message) + + @pytest.mark.torch_compile_test + def test_decorator_compiled(self): + """Test that the can_return_tuple decorator works with compiled mode.""" + config = PretrainedConfig() + + # Output object + model = self._get_model(config) + compiled_model = torch.compile(model) + output = compiled_model(torch.tensor(10)) + self.assertIsInstance(output, BaseModelOutput) + + # Tuple output + model = self._get_model(config) + compiled_model = torch.compile(model) + output = compiled_model(torch.tensor(10), return_dict=False) + self.assertIsInstance(output, tuple) + + @pytest.mark.torch_export_test + def test_decorator_torch_export(self): + """Test that the can_return_tuple decorator works with torch.export.""" + config = PretrainedConfig() + model = self._get_model(config) + torch.export.export(model, args=(torch.tensor(10),)) + + def test_decorator_torchscript(self): + """Test that the can_return_tuple decorator works with torch.jit.trace.""" + config = PretrainedConfig(return_dict=False) + model = self._get_model(config) + inputs = torch.tensor(10) + traced_module = torch.jit.trace(model, inputs) + output = traced_module(inputs) + self.assertIsInstance(output, tuple) + + def test_attribute_cleanup(self): + """Test that the `_is_top_level_module` attribute is removed after the forward call.""" + + config = PretrainedConfig(return_dict=False) + inputs = torch.tensor(10) + + # working case + model = self._get_model(config) + output = model(inputs) + + self.assertIsInstance(output, tuple) + for name, module in model.named_modules(): + self.assertFalse( + hasattr(module, "_is_top_level_module"), + f"Module `{name}` should not have `_is_top_level_module` attribute", + ) + + # model without config + no_config_model = self._get_model(config, store_config=False) + output = no_config_model(inputs) + + self.assertIsInstance(output, BaseModelOutput) + for name, module in no_config_model.named_modules(): + self.assertFalse( + hasattr(module, "_is_top_level_module"), + f"Module `{name}` should not have `_is_top_level_module` attribute", + ) + + # model with raise in forward + model_with_raise = self._get_model(config, raise_in_forward=True) + with self.assertRaises(ValueError): + model_with_raise(inputs) + + for name, module in model_with_raise.named_modules(): + self.assertFalse( + hasattr(module, "_is_top_level_module"), + f"Module `{name}` should not have `_is_top_level_module` attribute", + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_hf_argparser.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_hf_argparser.py new file mode 100644 index 0000000000000000000000000000000000000000..2923deeb6134e1d437abb6941ed205ff38e3cede --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_hf_argparser.py @@ -0,0 +1,492 @@ +# 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. + +import argparse +import json +import os +import sys +import tempfile +import unittest +from argparse import Namespace +from dataclasses import dataclass, field +from enum import Enum +from pathlib import Path +from typing import Literal, Optional, Union, get_args, get_origin +from unittest.mock import patch + +import yaml + +from transformers import HfArgumentParser, TrainingArguments +from transformers.hf_argparser import make_choice_type_function, string_to_bool +from transformers.testing_utils import require_torch + + +# Since Python 3.10, we can use the builtin `|` operator for Union types +# See PEP 604: https://peps.python.org/pep-0604 +is_python_no_less_than_3_10 = sys.version_info >= (3, 10) + + +def list_field(default=None, metadata=None): + return field(default_factory=lambda: default, metadata=metadata) + + +@dataclass +class BasicExample: + foo: int + bar: float + baz: str + flag: bool + + +@dataclass +class WithDefaultExample: + foo: int = 42 + baz: str = field(default="toto", metadata={"help": "help message"}) + + +@dataclass +class WithDefaultBoolExample: + foo: bool = False + baz: bool = True + opt: Optional[bool] = None + + +class BasicEnum(Enum): + titi = "titi" + toto = "toto" + + +class MixedTypeEnum(Enum): + titi = "titi" + toto = "toto" + fourtytwo = 42 + + +@dataclass +class EnumExample: + foo: BasicEnum = "toto" + + def __post_init__(self): + self.foo = BasicEnum(self.foo) + + +@dataclass +class MixedTypeEnumExample: + foo: MixedTypeEnum = "toto" + + def __post_init__(self): + self.foo = MixedTypeEnum(self.foo) + + +@dataclass +class OptionalExample: + foo: Optional[int] = None + bar: Optional[float] = field(default=None, metadata={"help": "help message"}) + baz: Optional[str] = None + ces: Optional[list[str]] = list_field(default=[]) + des: Optional[list[int]] = list_field(default=[]) + + +@dataclass +class ListExample: + foo_int: list[int] = list_field(default=[]) + bar_int: list[int] = list_field(default=[1, 2, 3]) + foo_str: list[str] = list_field(default=["Hallo", "Bonjour", "Hello"]) + foo_float: list[float] = list_field(default=[0.1, 0.2, 0.3]) + + +@dataclass +class RequiredExample: + required_list: list[int] = field() + required_str: str = field() + required_enum: BasicEnum = field() + + def __post_init__(self): + self.required_enum = BasicEnum(self.required_enum) + + +@dataclass +class StringLiteralAnnotationExample: + foo: int + required_enum: "BasicEnum" = field() + opt: "Optional[bool]" = None + baz: "str" = field(default="toto", metadata={"help": "help message"}) + foo_str: "list[str]" = list_field(default=["Hallo", "Bonjour", "Hello"]) + + +if is_python_no_less_than_3_10: + + @dataclass + class WithDefaultBoolExamplePep604: + foo: bool = False + baz: bool = True + opt: bool | None = None + + @dataclass + class OptionalExamplePep604: + foo: int | None = None + bar: float | None = field(default=None, metadata={"help": "help message"}) + baz: str | None = None + ces: list[str] | None = list_field(default=[]) + des: list[int] | None = list_field(default=[]) + + +class HfArgumentParserTest(unittest.TestCase): + def argparsersEqual(self, a: argparse.ArgumentParser, b: argparse.ArgumentParser): + """ + Small helper to check pseudo-equality of parsed arguments on `ArgumentParser` instances. + """ + self.assertEqual(len(a._actions), len(b._actions)) + for x, y in zip(a._actions, b._actions): + xx = {k: v for k, v in vars(x).items() if k != "container"} + yy = {k: v for k, v in vars(y).items() if k != "container"} + + # Choices with mixed type have custom function as "type" + # So we need to compare results directly for equality + if xx.get("choices") and yy.get("choices"): + for expected_choice in yy["choices"] + xx["choices"]: + self.assertEqual(xx["type"](expected_choice), yy["type"](expected_choice)) + del xx["type"], yy["type"] + + self.assertEqual(xx, yy) + + def test_00_basic(self): + parser = HfArgumentParser(BasicExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--foo", type=int, required=True) + expected.add_argument("--bar", type=float, required=True) + expected.add_argument("--baz", type=str, required=True) + expected.add_argument("--flag", type=string_to_bool, default=False, const=True, nargs="?") + self.argparsersEqual(parser, expected) + + args = ["--foo", "1", "--baz", "quux", "--bar", "0.5"] + (example,) = parser.parse_args_into_dataclasses(args, look_for_args_file=False) + self.assertFalse(example.flag) + + def test_01_with_default(self): + parser = HfArgumentParser(WithDefaultExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--foo", default=42, type=int) + expected.add_argument("--baz", default="toto", type=str, help="help message") + self.argparsersEqual(parser, expected) + + def test_02_with_default_bool(self): + expected = argparse.ArgumentParser() + expected.add_argument("--foo", type=string_to_bool, default=False, const=True, nargs="?") + expected.add_argument("--baz", type=string_to_bool, default=True, const=True, nargs="?") + # A boolean no_* argument always has to come after its "default: True" regular counter-part + # and its default must be set to False + expected.add_argument("--no_baz", "--no-baz", action="store_false", default=False, dest="baz") + expected.add_argument("--opt", type=string_to_bool, default=None) + + dataclass_types = [WithDefaultBoolExample] + if is_python_no_less_than_3_10: + dataclass_types.append(WithDefaultBoolExamplePep604) + + for dataclass_type in dataclass_types: + parser = HfArgumentParser(dataclass_type) + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual(args, Namespace(foo=False, baz=True, opt=None)) + + args = parser.parse_args(["--foo", "--no_baz"]) + self.assertEqual(args, Namespace(foo=True, baz=False, opt=None)) + + args = parser.parse_args(["--foo", "--no-baz"]) + self.assertEqual(args, Namespace(foo=True, baz=False, opt=None)) + + args = parser.parse_args(["--foo", "--baz"]) + self.assertEqual(args, Namespace(foo=True, baz=True, opt=None)) + + args = parser.parse_args(["--foo", "True", "--baz", "True", "--opt", "True"]) + self.assertEqual(args, Namespace(foo=True, baz=True, opt=True)) + + args = parser.parse_args(["--foo", "False", "--baz", "False", "--opt", "False"]) + self.assertEqual(args, Namespace(foo=False, baz=False, opt=False)) + + def test_03_with_enum(self): + parser = HfArgumentParser(MixedTypeEnumExample) + + expected = argparse.ArgumentParser() + expected.add_argument( + "--foo", + default="toto", + choices=["titi", "toto", 42], + type=make_choice_type_function(["titi", "toto", 42]), + ) + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual(args.foo, "toto") + enum_ex = parser.parse_args_into_dataclasses([])[0] + self.assertEqual(enum_ex.foo, MixedTypeEnum.toto) + + args = parser.parse_args(["--foo", "titi"]) + self.assertEqual(args.foo, "titi") + enum_ex = parser.parse_args_into_dataclasses(["--foo", "titi"])[0] + self.assertEqual(enum_ex.foo, MixedTypeEnum.titi) + + args = parser.parse_args(["--foo", "42"]) + self.assertEqual(args.foo, 42) + enum_ex = parser.parse_args_into_dataclasses(["--foo", "42"])[0] + self.assertEqual(enum_ex.foo, MixedTypeEnum.fourtytwo) + + def test_04_with_literal(self): + @dataclass + class LiteralExample: + foo: Literal["titi", "toto", 42] = "toto" + + parser = HfArgumentParser(LiteralExample) + + expected = argparse.ArgumentParser() + expected.add_argument( + "--foo", + default="toto", + choices=("titi", "toto", 42), + type=make_choice_type_function(["titi", "toto", 42]), + ) + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual(args.foo, "toto") + + args = parser.parse_args(["--foo", "titi"]) + self.assertEqual(args.foo, "titi") + + args = parser.parse_args(["--foo", "42"]) + self.assertEqual(args.foo, 42) + + def test_05_with_list(self): + parser = HfArgumentParser(ListExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--foo_int", "--foo-int", nargs="+", default=[], type=int) + expected.add_argument("--bar_int", "--bar-int", nargs="+", default=[1, 2, 3], type=int) + expected.add_argument("--foo_str", "--foo-str", nargs="+", default=["Hallo", "Bonjour", "Hello"], type=str) + expected.add_argument("--foo_float", "--foo-float", nargs="+", default=[0.1, 0.2, 0.3], type=float) + + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual( + args, + Namespace(foo_int=[], bar_int=[1, 2, 3], foo_str=["Hallo", "Bonjour", "Hello"], foo_float=[0.1, 0.2, 0.3]), + ) + + args = parser.parse_args("--foo_int 1 --bar_int 2 3 --foo_str a b c --foo_float 0.1 0.7".split()) + self.assertEqual(args, Namespace(foo_int=[1], bar_int=[2, 3], foo_str=["a", "b", "c"], foo_float=[0.1, 0.7])) + + args = parser.parse_args("--foo-int 1 --bar-int 2 3 --foo-str a b c --foo-float 0.1 0.7".split()) + self.assertEqual(args, Namespace(foo_int=[1], bar_int=[2, 3], foo_str=["a", "b", "c"], foo_float=[0.1, 0.7])) + + def test_06_with_optional(self): + expected = argparse.ArgumentParser() + expected.add_argument("--foo", default=None, type=int) + expected.add_argument("--bar", default=None, type=float, help="help message") + expected.add_argument("--baz", default=None, type=str) + expected.add_argument("--ces", nargs="+", default=[], type=str) + expected.add_argument("--des", nargs="+", default=[], type=int) + + dataclass_types = [OptionalExample] + if is_python_no_less_than_3_10: + dataclass_types.append(OptionalExamplePep604) + + for dataclass_type in dataclass_types: + parser = HfArgumentParser(dataclass_type) + + self.argparsersEqual(parser, expected) + + args = parser.parse_args([]) + self.assertEqual(args, Namespace(foo=None, bar=None, baz=None, ces=[], des=[])) + + args = parser.parse_args("--foo 12 --bar 3.14 --baz 42 --ces a b c --des 1 2 3".split()) + self.assertEqual(args, Namespace(foo=12, bar=3.14, baz="42", ces=["a", "b", "c"], des=[1, 2, 3])) + + def test_07_with_required(self): + parser = HfArgumentParser(RequiredExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--required_list", "--required-list", nargs="+", type=int, required=True) + expected.add_argument("--required_str", "--required-str", type=str, required=True) + expected.add_argument( + "--required_enum", + "--required-enum", + type=make_choice_type_function(["titi", "toto"]), + choices=["titi", "toto"], + required=True, + ) + self.argparsersEqual(parser, expected) + + def test_08_with_string_literal_annotation(self): + parser = HfArgumentParser(StringLiteralAnnotationExample) + + expected = argparse.ArgumentParser() + expected.add_argument("--foo", type=int, required=True) + expected.add_argument( + "--required_enum", + "--required-enum", + type=make_choice_type_function(["titi", "toto"]), + choices=["titi", "toto"], + required=True, + ) + expected.add_argument("--opt", type=string_to_bool, default=None) + expected.add_argument("--baz", default="toto", type=str, help="help message") + expected.add_argument("--foo_str", "--foo-str", nargs="+", default=["Hallo", "Bonjour", "Hello"], type=str) + self.argparsersEqual(parser, expected) + + def test_09_parse_dict(self): + parser = HfArgumentParser(BasicExample) + + args_dict = { + "foo": 12, + "bar": 3.14, + "baz": "42", + "flag": True, + } + + parsed_args = parser.parse_dict(args_dict)[0] + args = BasicExample(**args_dict) + self.assertEqual(parsed_args, args) + + def test_10_parse_dict_extra_key(self): + parser = HfArgumentParser(BasicExample) + + args_dict = { + "foo": 12, + "bar": 3.14, + "baz": "42", + "flag": True, + "extra": 42, + } + + self.assertRaises(ValueError, parser.parse_dict, args_dict, allow_extra_keys=False) + + def test_11_parse_json(self): + parser = HfArgumentParser(BasicExample) + + args_dict_for_json = { + "foo": 12, + "bar": 3.14, + "baz": "42", + "flag": True, + } + with tempfile.TemporaryDirectory() as tmp_dir: + temp_local_path = os.path.join(tmp_dir, "temp_json") + os.mkdir(temp_local_path) + with open(temp_local_path + ".json", "w+") as f: + json.dump(args_dict_for_json, f) + parsed_args = parser.parse_json_file(Path(temp_local_path + ".json"))[0] + + args = BasicExample(**args_dict_for_json) + self.assertEqual(parsed_args, args) + + def test_12_parse_yaml(self): + parser = HfArgumentParser(BasicExample) + + args_dict_for_yaml = { + "foo": 12, + "bar": 3.14, + "baz": "42", + "flag": True, + } + with tempfile.TemporaryDirectory() as tmp_dir: + temp_local_path = os.path.join(tmp_dir, "temp_yaml") + os.mkdir(temp_local_path) + with open(temp_local_path + ".yaml", "w+") as f: + yaml.dump(args_dict_for_yaml, f) + parsed_args = parser.parse_yaml_file(Path(temp_local_path + ".yaml"))[0] + args = BasicExample(**args_dict_for_yaml) + self.assertEqual(parsed_args, args) + + def test_13_valid_dict_annotation(self): + """ + Tests to make sure that `dict` based annotations + are correctly made in the `TrainingArguments`. + + If this fails, a type annotation change is + needed on a new input + """ + base_list = TrainingArguments._VALID_DICT_FIELDS.copy() + args = TrainingArguments + + # First find any annotations that contain `dict` + fields = args.__dataclass_fields__ + + raw_dict_fields = [] + optional_dict_fields = [] + + for field in fields.values(): + # First verify raw dict + if field.type is dict: + raw_dict_fields.append(field) + # Next check for `Union` or `Optional` + elif get_origin(field.type) == Union: + if any(arg is dict for arg in get_args(field.type)): + optional_dict_fields.append(field) + + # First check: anything in `raw_dict_fields` is very bad + self.assertEqual( + len(raw_dict_fields), + 0, + f"Found invalid raw `dict` types in the `TrainingArgument` typings, which are {raw_dict_fields}. " + "This leads to issues with the CLI. Please turn this into `typing.Optional[dict,str]`", + ) + + # Next check raw annotations + for field in optional_dict_fields: + args = get_args(field.type) + # These should be returned as `dict`, `str`, ... + # we only care about the first two + self.assertIn( + dict, + args, + f"Expected field `{field.name}` to have a type signature of at least `typing.Union[dict,str,...]` for CLI compatibility, but `dict` not found. Please fix this.", + ) + self.assertIn( + str, + args, + f"Expected field `{field.name}` to have a type signature of at least `typing.Union[dict,str,...]` for CLI compatibility, but `str` not found. Please fix this.", + ) + + # Second check: anything in `optional_dict_fields` is bad if it's not in `base_list` + for field in optional_dict_fields: + self.assertIn( + field.name, + base_list, + f"Optional dict field `{field.name}` is not in the base list of valid fields. Please add it to `TrainingArguments._VALID_DICT_FIELDS`", + ) + + @require_torch + def test_14_valid_dict_input_parsing(self): + with tempfile.TemporaryDirectory() as tmp_dir: + args = TrainingArguments( + output_dir=tmp_dir, + accelerator_config='{"split_batches": "True", "gradient_accumulation_kwargs": {"num_steps": 2}}', + ) + self.assertEqual(args.accelerator_config.split_batches, True) + self.assertEqual(args.accelerator_config.gradient_accumulation_kwargs["num_steps"], 2) + + def test_15_integration_training_args(self): + parser = HfArgumentParser(TrainingArguments) + self.assertIsNotNone(parser) + + @require_torch + @patch("sys.argv", ["test.py", "--accelerator_config", '{"gradient_accumulation_kwargs": {"num_steps": 2}}']) + def test_16_cli_input_parsing(self): + parser = HfArgumentParser(TrainingArguments) + training_args = parser.parse_args_into_dataclasses()[0] + self.assertEqual(training_args.accelerator_config.gradient_accumulation_kwargs["num_steps"], 2) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_hub_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_hub_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0bccec449f0d5343af5c959b4dcf002323e3d5a4 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_hub_utils.py @@ -0,0 +1,200 @@ +# 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. +import json +import os +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from huggingface_hub import hf_hub_download +from requests.exceptions import HTTPError + +from transformers.utils import ( + CONFIG_NAME, + FLAX_WEIGHTS_NAME, + TF2_WEIGHTS_NAME, + TRANSFORMERS_CACHE, + WEIGHTS_NAME, + cached_file, + has_file, +) + + +RANDOM_BERT = "hf-internal-testing/tiny-random-bert" +TINY_BERT_PT_ONLY = "hf-internal-testing/tiny-bert-pt-only" +CACHE_DIR = os.path.join(TRANSFORMERS_CACHE, "models--hf-internal-testing--tiny-random-bert") +FULL_COMMIT_HASH = "9b8c223d42b2188cb49d29af482996f9d0f3e5a6" + +GATED_REPO = "hf-internal-testing/dummy-gated-model" +README_FILE = "README.md" + + +class GetFromCacheTests(unittest.TestCase): + def test_cached_file(self): + archive_file = cached_file(RANDOM_BERT, CONFIG_NAME) + # Should have downloaded the file in here + self.assertTrue(os.path.isdir(CACHE_DIR)) + # Cache should contain at least those three subfolders: + for subfolder in ["blobs", "refs", "snapshots"]: + self.assertTrue(os.path.isdir(os.path.join(CACHE_DIR, subfolder))) + with open(os.path.join(CACHE_DIR, "refs", "main")) as f: + main_commit = f.read() + self.assertEqual(archive_file, os.path.join(CACHE_DIR, "snapshots", main_commit, CONFIG_NAME)) + self.assertTrue(os.path.isfile(archive_file)) + + # File is cached at the same place the second time. + new_archive_file = cached_file(RANDOM_BERT, CONFIG_NAME) + self.assertEqual(archive_file, new_archive_file) + + # Using a specific revision to test the full commit hash. + archive_file = cached_file(RANDOM_BERT, CONFIG_NAME, revision="9b8c223") + self.assertEqual(archive_file, os.path.join(CACHE_DIR, "snapshots", FULL_COMMIT_HASH, CONFIG_NAME)) + + def test_cached_file_errors(self): + with self.assertRaisesRegex(EnvironmentError, "is not a valid model identifier"): + _ = cached_file("tiny-random-bert", CONFIG_NAME) + + with self.assertRaisesRegex(EnvironmentError, "is not a valid git identifier"): + _ = cached_file(RANDOM_BERT, CONFIG_NAME, revision="aaaa") + + with self.assertRaisesRegex(EnvironmentError, "does not appear to have a file named"): + _ = cached_file(RANDOM_BERT, "conf") + + def test_non_existence_is_cached(self): + with self.assertRaisesRegex(EnvironmentError, "does not appear to have a file named"): + _ = cached_file(RANDOM_BERT, "conf") + + with open(os.path.join(CACHE_DIR, "refs", "main")) as f: + main_commit = f.read() + self.assertTrue(os.path.isfile(os.path.join(CACHE_DIR, ".no_exist", main_commit, "conf"))) + + path = cached_file(RANDOM_BERT, "conf", _raise_exceptions_for_missing_entries=False) + self.assertIsNone(path) + + path = cached_file(RANDOM_BERT, "conf", local_files_only=True, _raise_exceptions_for_missing_entries=False) + self.assertIsNone(path) + + # Under the mock environment, hf_hub_download will always raise an HTTPError + with mock.patch("transformers.utils.hub.hf_hub_download", side_effect=HTTPError) as mock_head: + path = cached_file(RANDOM_BERT, "conf", _raise_exceptions_for_connection_errors=False) + self.assertIsNone(path) + # This check we did call the fake head request + mock_head.assert_called() + + def test_has_file(self): + self.assertTrue(has_file(TINY_BERT_PT_ONLY, WEIGHTS_NAME)) + self.assertFalse(has_file(TINY_BERT_PT_ONLY, TF2_WEIGHTS_NAME)) + self.assertFalse(has_file(TINY_BERT_PT_ONLY, FLAX_WEIGHTS_NAME)) + + def test_has_file_in_cache(self): + with tempfile.TemporaryDirectory() as tmp_dir: + # Empty cache dir + offline mode => return False + assert not has_file(TINY_BERT_PT_ONLY, WEIGHTS_NAME, local_files_only=True, cache_dir=tmp_dir) + + # Populate cache dir + hf_hub_download(TINY_BERT_PT_ONLY, WEIGHTS_NAME, cache_dir=tmp_dir) + + # Cache dir + offline mode => return True + assert has_file(TINY_BERT_PT_ONLY, WEIGHTS_NAME, local_files_only=True, cache_dir=tmp_dir) + + def test_get_file_from_repo_distant(self): + # should return None if the file does not exist + self.assertIsNone( + cached_file( + "google-bert/bert-base-cased", + "ahah.txt", + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + ) + ) + + # The function raises if the repository does not exist. + with self.assertRaisesRegex(EnvironmentError, "is not a valid model identifier"): + cached_file( + "bert-base-case", + CONFIG_NAME, + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + ) + + # The function raises if the revision does not exist. + with self.assertRaisesRegex(EnvironmentError, "is not a valid git identifier"): + cached_file( + "google-bert/bert-base-cased", + CONFIG_NAME, + revision="ahaha", + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + ) + + resolved_file = cached_file( + "google-bert/bert-base-cased", + CONFIG_NAME, + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + ) + # The name is the cached name which is not very easy to test, so instead we load the content. + config = json.loads(open(resolved_file).read()) + self.assertEqual(config["hidden_size"], 768) + + def test_get_file_from_repo_local(self): + with tempfile.TemporaryDirectory() as tmp_dir: + filename = Path(tmp_dir) / "a.txt" + filename.touch() + self.assertEqual( + cached_file( + tmp_dir, + "a.txt", + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + ), + str(filename), + ) + + self.assertIsNone( + cached_file( + tmp_dir, + "b.txt", + _raise_exceptions_for_gated_repo=False, + _raise_exceptions_for_missing_entries=False, + _raise_exceptions_for_connection_errors=False, + ) + ) + + def test_get_file_gated_repo(self): + """Test download file from a gated repo fails with correct message when not authenticated.""" + with self.assertRaisesRegex(EnvironmentError, "You are trying to access a gated repo."): + # All files except README.md are protected on a gated repo. + cached_file(GATED_REPO, "gated_file.txt", token=False) + + def test_has_file_gated_repo(self): + """Test check file existence from a gated repo fails with correct message when not authenticated.""" + with self.assertRaisesRegex(EnvironmentError, "is a gated repository"): + # All files except README.md are protected on a gated repo. + has_file(GATED_REPO, "gated_file.txt", token=False) + + def test_cached_files_exception_raised(self): + """Test that unhadled exceptions, e.g. ModuleNotFoundError, is properly re-raised by cached_files when hf_hub_download fails.""" + with mock.patch( + "transformers.utils.hub.hf_hub_download", side_effect=ModuleNotFoundError("No module named 'MockModule'") + ): + with self.assertRaises(ModuleNotFoundError): + # The error should be re-raised by cached_files, not caught in the exception handling block + cached_file(RANDOM_BERT, "nonexistent.json") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_image_processing_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_image_processing_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1b8a515d69c9d5473daf50cad2b284386e10c55e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_image_processing_utils.py @@ -0,0 +1,181 @@ +# Copyright 2024 HuggingFace 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. + +import sys +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from huggingface_hub import HfFolder +from requests.exceptions import HTTPError + +from transformers import AutoImageProcessor, ViTImageProcessor +from transformers.image_processing_utils import get_size_dict +from transformers.testing_utils import TOKEN, TemporaryHubRepo, get_tests_dir, is_staging_test + + +sys.path.append(str(Path(__file__).parent.parent.parent / "utils")) + +from test_module.custom_image_processing import CustomImageProcessor # noqa E402 + + +SAMPLE_IMAGE_PROCESSING_CONFIG_DIR = get_tests_dir("fixtures") + + +class ImageProcessorUtilTester(unittest.TestCase): + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit") + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = ViTImageProcessor.from_pretrained("hf-internal-testing/tiny-random-vit") + # This check we did call the fake head request + mock_head.assert_called() + + def test_image_processor_from_pretrained_subfolder(self): + with self.assertRaises(OSError): + # config is in subfolder, the following should not work without specifying the subfolder + _ = AutoImageProcessor.from_pretrained("hf-internal-testing/stable-diffusion-all-variants") + + config = AutoImageProcessor.from_pretrained( + "hf-internal-testing/stable-diffusion-all-variants", subfolder="feature_extractor" + ) + + self.assertIsNotNone(config) + + +@is_staging_test +class ImageProcessorPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + def test_push_to_hub(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + image_processor = ViTImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) + image_processor.push_to_hub(tmp_repo.repo_id, token=self._token) + + new_image_processor = ViTImageProcessor.from_pretrained(tmp_repo.repo_id) + for k, v in image_processor.__dict__.items(): + self.assertEqual(v, getattr(new_image_processor, k)) + + def test_push_to_hub_via_save_pretrained(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + image_processor = ViTImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + image_processor.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) + + new_image_processor = ViTImageProcessor.from_pretrained(tmp_repo.repo_id) + for k, v in image_processor.__dict__.items(): + self.assertEqual(v, getattr(new_image_processor, k)) + + def test_push_to_hub_in_organization(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + image_processor = ViTImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) + image_processor.push_to_hub(tmp_repo.repo_id, token=self._token) + + new_image_processor = ViTImageProcessor.from_pretrained(tmp_repo.repo_id) + for k, v in image_processor.__dict__.items(): + self.assertEqual(v, getattr(new_image_processor, k)) + + def test_push_to_hub_in_organization_via_save_pretrained(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + image_processor = ViTImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + image_processor.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) + + new_image_processor = ViTImageProcessor.from_pretrained(tmp_repo.repo_id) + for k, v in image_processor.__dict__.items(): + self.assertEqual(v, getattr(new_image_processor, k)) + + def test_push_to_hub_dynamic_image_processor(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + CustomImageProcessor.register_for_auto_class() + image_processor = CustomImageProcessor.from_pretrained(SAMPLE_IMAGE_PROCESSING_CONFIG_DIR) + + image_processor.push_to_hub(tmp_repo.repo_id, token=self._token) + + # This has added the proper auto_map field to the config + self.assertDictEqual( + image_processor.auto_map, + {"AutoImageProcessor": "custom_image_processing.CustomImageProcessor"}, + ) + + new_image_processor = AutoImageProcessor.from_pretrained(tmp_repo.repo_id, trust_remote_code=True) + # Can't make an isinstance check because the new_image_processor is from the CustomImageProcessor class of a dynamic module + self.assertEqual(new_image_processor.__class__.__name__, "CustomImageProcessor") + + +class ImageProcessingUtilsTester(unittest.TestCase): + def test_get_size_dict(self): + # Test a dict with the wrong keys raises an error + inputs = {"wrong_key": 224} + with self.assertRaises(ValueError): + get_size_dict(inputs) + + inputs = {"height": 224} + with self.assertRaises(ValueError): + get_size_dict(inputs) + + inputs = {"width": 224, "shortest_edge": 224} + with self.assertRaises(ValueError): + get_size_dict(inputs) + + # Test a dict with the correct keys is returned as is + inputs = {"height": 224, "width": 224} + outputs = get_size_dict(inputs) + self.assertEqual(outputs, inputs) + + inputs = {"shortest_edge": 224} + outputs = get_size_dict(inputs) + self.assertEqual(outputs, {"shortest_edge": 224}) + + inputs = {"longest_edge": 224, "shortest_edge": 224} + outputs = get_size_dict(inputs) + self.assertEqual(outputs, {"longest_edge": 224, "shortest_edge": 224}) + + # Test a single int value which represents (size, size) + outputs = get_size_dict(224) + self.assertEqual(outputs, {"height": 224, "width": 224}) + + # Test a single int value which represents the shortest edge + outputs = get_size_dict(224, default_to_square=False) + self.assertEqual(outputs, {"shortest_edge": 224}) + + # Test a tuple of ints which represents (height, width) + outputs = get_size_dict((150, 200)) + self.assertEqual(outputs, {"height": 150, "width": 200}) + + # Test a tuple of ints which represents (width, height) + outputs = get_size_dict((150, 200), height_width_order=False) + self.assertEqual(outputs, {"height": 200, "width": 150}) + + # Test an int representing the shortest edge and max_size which represents the longest edge + outputs = get_size_dict(224, max_size=256, default_to_square=False) + self.assertEqual(outputs, {"shortest_edge": 224, "longest_edge": 256}) + + # Test int with default_to_square=True and max_size fails + with self.assertRaises(ValueError): + get_size_dict(224, max_size=256, default_to_square=True) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_image_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_image_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..8d124d361c2a8f38591381b29fb0e88118e05937 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_image_utils.py @@ -0,0 +1,933 @@ +# Copyright 2021 HuggingFace 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. + +import codecs +import os +import tempfile +import unittest +from io import BytesIO +from typing import Optional + +import numpy as np +import pytest +import requests +from huggingface_hub.file_download import hf_hub_url, http_get +from requests import ConnectTimeout, ReadTimeout + +from tests.pipelines.test_pipelines_document_question_answering import INVOICE_URL +from transformers import is_torch_available, is_vision_available +from transformers.image_utils import ( + ChannelDimension, + get_channel_dimension_axis, + make_flat_list_of_images, + make_list_of_images, + make_nested_list_of_images, +) +from transformers.testing_utils import is_flaky, require_torch, require_vision + + +if is_torch_available(): + import torch + +if is_vision_available(): + import PIL.Image + + from transformers import ImageFeatureExtractionMixin + from transformers.image_utils import get_image_size, infer_channel_dimension_format, load_image + + +def get_image_from_hub_dataset(dataset_id: str, filename: str, revision: Optional[str] = None) -> "PIL.Image.Image": + url = hf_hub_url(dataset_id, filename, repo_type="dataset", revision=revision) + return PIL.Image.open(BytesIO(requests.get(url).content)) + + +def get_random_image(height, width): + random_array = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8) + return PIL.Image.fromarray(random_array) + + +@require_vision +class ImageFeatureExtractionTester(unittest.TestCase): + def test_conversion_image_to_array(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + + # Conversion with defaults (rescale + channel first) + array1 = feature_extractor.to_numpy_array(image) + self.assertTrue(array1.dtype, np.float32) + self.assertEqual(array1.shape, (3, 16, 32)) + + # Conversion with rescale and not channel first + array2 = feature_extractor.to_numpy_array(image, channel_first=False) + self.assertTrue(array2.dtype, np.float32) + self.assertEqual(array2.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array1, array2.transpose(2, 0, 1))) + + # Conversion with no rescale and channel first + array3 = feature_extractor.to_numpy_array(image, rescale=False) + self.assertTrue(array3.dtype, np.uint8) + self.assertEqual(array3.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array1, array3.astype(np.float32) * (1 / 255.0))) + + # Conversion with no rescale and not channel first + array4 = feature_extractor.to_numpy_array(image, rescale=False, channel_first=False) + self.assertTrue(array4.dtype, np.uint8) + self.assertEqual(array4.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array2, array4.astype(np.float32) * (1 / 255.0))) + + def test_conversion_array_to_array(self): + feature_extractor = ImageFeatureExtractionMixin() + array = np.random.randint(0, 256, (16, 32, 3), dtype=np.uint8) + + # By default, rescale (for an array of ints) and channel permute + array1 = feature_extractor.to_numpy_array(array) + self.assertTrue(array1.dtype, np.float32) + self.assertEqual(array1.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array1, array.transpose(2, 0, 1).astype(np.float32) * (1 / 255.0))) + + # Same with no permute + array2 = feature_extractor.to_numpy_array(array, channel_first=False) + self.assertTrue(array2.dtype, np.float32) + self.assertEqual(array2.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array2, array.astype(np.float32) * (1 / 255.0))) + + # Force rescale to False + array3 = feature_extractor.to_numpy_array(array, rescale=False) + self.assertTrue(array3.dtype, np.uint8) + self.assertEqual(array3.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array3, array.transpose(2, 0, 1))) + + # Force rescale to False and no channel permute + array4 = feature_extractor.to_numpy_array(array, rescale=False, channel_first=False) + self.assertTrue(array4.dtype, np.uint8) + self.assertEqual(array4.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array4, array)) + + # Now test the default rescale for a float array (defaults to False) + array5 = feature_extractor.to_numpy_array(array2) + self.assertTrue(array5.dtype, np.float32) + self.assertEqual(array5.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array5, array1)) + + def test_make_list_of_images_pil(self): + # Test a single image is converted to a list of 1 image + pil_image = get_random_image(16, 32) + images_list = make_list_of_images(pil_image) + self.assertIsInstance(images_list, list) + self.assertEqual(len(images_list), 1) + self.assertIsInstance(images_list[0], PIL.Image.Image) + + # Test a list of images is not modified + images = [get_random_image(16, 32) for _ in range(4)] + images_list = make_list_of_images(images) + self.assertIsInstance(images_list, list) + self.assertEqual(len(images_list), 4) + self.assertIsInstance(images_list[0], PIL.Image.Image) + + def test_make_list_of_images_numpy(self): + # Test a single image is converted to a list of 1 image + images = np.random.randint(0, 256, (16, 32, 3)) + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 1) + self.assertTrue(np.array_equal(images_list[0], images)) + self.assertIsInstance(images_list, list) + + # Test a batch of images is converted to a list of images + images = np.random.randint(0, 256, (4, 16, 32, 3)) + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + # Test a list of images is not modified + images = [np.random.randint(0, 256, (16, 32, 3)) for _ in range(4)] + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + # Test batched masks with no channel dimension are converted to a list of masks + masks = np.random.randint(0, 2, (4, 16, 32)) + masks_list = make_list_of_images(masks, expected_ndims=2) + self.assertEqual(len(masks_list), 4) + self.assertTrue(np.array_equal(masks_list[0], masks[0])) + self.assertIsInstance(masks_list, list) + + @require_torch + def test_make_list_of_images_torch(self): + # Test a single image is converted to a list of 1 image + images = torch.randint(0, 256, (16, 32, 3)) + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 1) + self.assertTrue(np.array_equal(images_list[0], images)) + self.assertIsInstance(images_list, list) + + # Test a batch of images is converted to a list of images + images = torch.randint(0, 256, (4, 16, 32, 3)) + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + # Test a list of images is left unchanged + images = [torch.randint(0, 256, (16, 32, 3)) for _ in range(4)] + images_list = make_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + def test_make_flat_list_of_images_pil(self): + # Test a single image is converted to a list of 1 image + pil_image = get_random_image(16, 32) + images_list = make_flat_list_of_images(pil_image) + self.assertIsInstance(images_list, list) + self.assertEqual(len(images_list), 1) + self.assertIsInstance(images_list[0], PIL.Image.Image) + + # Test a list of images is not modified + images = [get_random_image(16, 32) for _ in range(4)] + images_list = make_flat_list_of_images(images) + self.assertIsInstance(images_list, list) + self.assertEqual(len(images_list), 4) + self.assertIsInstance(images_list[0], PIL.Image.Image) + + # Test a nested list of images is flattened + images = [[get_random_image(16, 32) for _ in range(2)] for _ in range(2)] + images_list = make_flat_list_of_images(images) + self.assertIsInstance(images_list, list) + self.assertEqual(len(images_list), 4) + self.assertIsInstance(images_list[0], PIL.Image.Image) + + def test_make_flat_list_of_images_numpy(self): + # Test a single image is converted to a list of 1 image + images = np.random.randint(0, 256, (16, 32, 3)) + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 1) + self.assertTrue(np.array_equal(images_list[0], images)) + self.assertIsInstance(images_list, list) + + # Test a 4d array of images is changed to a list of images + images = np.random.randint(0, 256, (4, 16, 32, 3)) + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertIsInstance(images_list, list) + self.assertIsInstance(images_list[0], np.ndarray) + self.assertTrue(np.array_equal(images_list[0], images[0])) + + # Test a list of images is not modified + images = [np.random.randint(0, 256, (16, 32, 3)) for _ in range(4)] + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + # Test list of 4d array images is flattened + images = [np.random.randint(0, 256, (4, 16, 32, 3)) for _ in range(2)] + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 8) + self.assertTrue(np.array_equal(images_list[0], images[0][0])) + self.assertIsInstance(images_list, list) + self.assertIsInstance(images_list[0], np.ndarray) + + # Test nested list of images is flattened + images = [[np.random.randint(0, 256, (16, 32, 3)) for _ in range(2)] for _ in range(2)] + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0][0])) + self.assertIsInstance(images_list, list) + + @require_torch + def test_make_flat_list_of_images_torch(self): + # Test a single image is converted to a list of 1 image + images = torch.randint(0, 256, (16, 32, 3)) + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 1) + self.assertTrue(np.array_equal(images_list[0], images)) + self.assertIsInstance(images_list, list) + + # Test a 4d tensors of images is changed to a list of images + images = torch.randint(0, 256, (4, 16, 32, 3)) + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertIsInstance(images_list, list) + self.assertIsInstance(images_list[0], torch.Tensor) + self.assertTrue(np.array_equal(images_list[0], images[0])) + + # Test a list of images is not modified + images = [torch.randint(0, 256, (16, 32, 3)) for _ in range(4)] + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0])) + self.assertIsInstance(images_list, list) + + # Test list of 4d tensors of imagess is flattened + images = [torch.randint(0, 256, (4, 16, 32, 3)) for _ in range(2)] + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 8) + self.assertTrue(np.array_equal(images_list[0], images[0][0])) + self.assertIsInstance(images_list, list) + self.assertIsInstance(images_list[0], torch.Tensor) + + # Test nested list of images is flattened + images = [[torch.randint(0, 256, (16, 32, 3)) for _ in range(2)] for _ in range(2)] + images_list = make_flat_list_of_images(images) + self.assertEqual(len(images_list), 4) + self.assertTrue(np.array_equal(images_list[0], images[0][0])) + self.assertIsInstance(images_list, list) + + def test_make_nested_list_of_images_pil(self): + # Test a single image is converted to a nested list of 1 image + pil_image = get_random_image(16, 32) + images_list = make_nested_list_of_images(pil_image) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list[0]), 1) + self.assertIsInstance(images_list[0][0], PIL.Image.Image) + + # Test a list of images is converted to a nested list of images + images = [get_random_image(16, 32) for _ in range(4)] + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list), 1) + self.assertEqual(len(images_list[0]), 4) + self.assertIsInstance(images_list[0][0], PIL.Image.Image) + + # Test a nested list of images is not modified + images = [[get_random_image(16, 32) for _ in range(2)] for _ in range(2)] + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list), 2) + self.assertEqual(len(images_list[0]), 2) + self.assertIsInstance(images_list[0][0], PIL.Image.Image) + + def test_make_nested_list_of_images_numpy(self): + # Test a single image is converted to a nested list of 1 image + images = np.random.randint(0, 256, (16, 32, 3)) + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list), 1) + self.assertTrue(np.array_equal(images_list[0][0], images)) + + # Test a 4d array of images is converted to a nested list of images + images = np.random.randint(0, 256, (4, 16, 32, 3)) + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertIsInstance(images_list[0][0], np.ndarray) + self.assertEqual(len(images_list), 1) + self.assertEqual(len(images_list[0]), 4) + self.assertTrue(np.array_equal(images_list[0][0], images[0])) + + # Test a list of images is converted to a nested list of images + images = [np.random.randint(0, 256, (16, 32, 3)) for _ in range(4)] + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list), 1) + self.assertEqual(len(images_list[0]), 4) + self.assertTrue(np.array_equal(images_list[0][0], images[0])) + + # Test a nested list of images is left unchanged + images = [[np.random.randint(0, 256, (16, 32, 3)) for _ in range(2)] for _ in range(2)] + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list), 2) + self.assertEqual(len(images_list[0]), 2) + self.assertTrue(np.array_equal(images_list[0][0], images[0][0])) + + # Test a list of 4d array images is converted to a nested list of images + images = [np.random.randint(0, 256, (4, 16, 32, 3)) for _ in range(2)] + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertIsInstance(images_list[0][0], np.ndarray) + self.assertEqual(len(images_list), 2) + self.assertEqual(len(images_list[0]), 4) + self.assertTrue(np.array_equal(images_list[0][0], images[0][0])) + + @require_torch + def test_make_nested_list_of_images_torch(self): + # Test a single image is converted to a nested list of 1 image + images = torch.randint(0, 256, (16, 32, 3)) + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list[0]), 1) + self.assertTrue(np.array_equal(images_list[0][0], images)) + + # Test a 4d tensor of images is converted to a nested list of images + images = torch.randint(0, 256, (4, 16, 32, 3)) + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertIsInstance(images_list[0][0], torch.Tensor) + self.assertEqual(len(images_list), 1) + self.assertEqual(len(images_list[0]), 4) + self.assertTrue(np.array_equal(images_list[0][0], images[0])) + + # Test a list of images is converted to a nested list of images + images = [torch.randint(0, 256, (16, 32, 3)) for _ in range(4)] + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list), 1) + self.assertEqual(len(images_list[0]), 4) + self.assertTrue(np.array_equal(images_list[0][0], images[0])) + + # Test a nested list of images is left unchanged + images = [[torch.randint(0, 256, (16, 32, 3)) for _ in range(2)] for _ in range(2)] + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertEqual(len(images_list), 2) + self.assertEqual(len(images_list[0]), 2) + self.assertTrue(np.array_equal(images_list[0][0], images[0][0])) + + # Test a list of 4d tensor images is converted to a nested list of images + images = [torch.randint(0, 256, (4, 16, 32, 3)) for _ in range(2)] + images_list = make_nested_list_of_images(images) + self.assertIsInstance(images_list[0], list) + self.assertIsInstance(images_list[0][0], torch.Tensor) + self.assertEqual(len(images_list), 2) + self.assertEqual(len(images_list[0]), 4) + self.assertTrue(np.array_equal(images_list[0][0], images[0][0])) + + @require_torch + def test_conversion_torch_to_array(self): + feature_extractor = ImageFeatureExtractionMixin() + tensor = torch.randint(0, 256, (16, 32, 3)) + array = tensor.numpy() + + # By default, rescale (for a tensor of ints) and channel permute + array1 = feature_extractor.to_numpy_array(array) + self.assertTrue(array1.dtype, np.float32) + self.assertEqual(array1.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array1, array.transpose(2, 0, 1).astype(np.float32) * (1 / 255.0))) + + # Same with no permute + array2 = feature_extractor.to_numpy_array(array, channel_first=False) + self.assertTrue(array2.dtype, np.float32) + self.assertEqual(array2.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array2, array.astype(np.float32) * (1 / 255.0))) + + # Force rescale to False + array3 = feature_extractor.to_numpy_array(array, rescale=False) + self.assertTrue(array3.dtype, np.uint8) + self.assertEqual(array3.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array3, array.transpose(2, 0, 1))) + + # Force rescale to False and no channel permute + array4 = feature_extractor.to_numpy_array(array, rescale=False, channel_first=False) + self.assertTrue(array4.dtype, np.uint8) + self.assertEqual(array4.shape, (16, 32, 3)) + self.assertTrue(np.array_equal(array4, array)) + + # Now test the default rescale for a float tensor (defaults to False) + array5 = feature_extractor.to_numpy_array(array2) + self.assertTrue(array5.dtype, np.float32) + self.assertEqual(array5.shape, (3, 16, 32)) + self.assertTrue(np.array_equal(array5, array1)) + + def test_conversion_image_to_image(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + + # On an image, `to_pil_image1` is a noop. + image1 = feature_extractor.to_pil_image(image) + self.assertTrue(isinstance(image, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image), np.array(image1))) + + def test_conversion_array_to_image(self): + feature_extractor = ImageFeatureExtractionMixin() + array = np.random.randint(0, 256, (16, 32, 3), dtype=np.uint8) + + # By default, no rescale (for an array of ints) + image1 = feature_extractor.to_pil_image(array) + self.assertTrue(isinstance(image1, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image1), array)) + + # If the array is channel-first, proper reordering of the channels is done. + image2 = feature_extractor.to_pil_image(array.transpose(2, 0, 1)) + self.assertTrue(isinstance(image2, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image2), array)) + + # If the array has floating type, it's rescaled by default. + image3 = feature_extractor.to_pil_image(array.astype(np.float32) * (1 / 255.0)) + self.assertTrue(isinstance(image3, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image3), array)) + + # You can override the default to rescale. + image4 = feature_extractor.to_pil_image(array.astype(np.float32), rescale=False) + self.assertTrue(isinstance(image4, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image4), array)) + + # And with floats + channel first. + image5 = feature_extractor.to_pil_image(array.transpose(2, 0, 1).astype(np.float32) * (1 / 255.0)) + self.assertTrue(isinstance(image5, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image5), array)) + + @require_torch + def test_conversion_tensor_to_image(self): + feature_extractor = ImageFeatureExtractionMixin() + tensor = torch.randint(0, 256, (16, 32, 3)) + array = tensor.numpy() + + # By default, no rescale (for a tensor of ints) + image1 = feature_extractor.to_pil_image(tensor) + self.assertTrue(isinstance(image1, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image1), array)) + + # If the tensor is channel-first, proper reordering of the channels is done. + image2 = feature_extractor.to_pil_image(tensor.permute(2, 0, 1)) + self.assertTrue(isinstance(image2, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image2), array)) + + # If the tensor has floating type, it's rescaled by default. + image3 = feature_extractor.to_pil_image(tensor.float() / 255.0) + self.assertTrue(isinstance(image3, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image3), array)) + + # You can override the default to rescale. + image4 = feature_extractor.to_pil_image(tensor.float(), rescale=False) + self.assertTrue(isinstance(image4, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image4), array)) + + # And with floats + channel first. + image5 = feature_extractor.to_pil_image(tensor.permute(2, 0, 1).float() * (1 / 255.0)) + self.assertTrue(isinstance(image5, PIL.Image.Image)) + self.assertTrue(np.array_equal(np.array(image5), array)) + + def test_resize_image_and_array(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + array = np.array(image) + + # Size can be an int or a tuple of ints. + resized_image = feature_extractor.resize(image, 8) + self.assertTrue(isinstance(resized_image, PIL.Image.Image)) + self.assertEqual(resized_image.size, (8, 8)) + + resized_image1 = feature_extractor.resize(image, (8, 16)) + self.assertTrue(isinstance(resized_image1, PIL.Image.Image)) + self.assertEqual(resized_image1.size, (8, 16)) + + # Passing an array converts it to a PIL Image. + resized_image2 = feature_extractor.resize(array, 8) + self.assertTrue(isinstance(resized_image2, PIL.Image.Image)) + self.assertEqual(resized_image2.size, (8, 8)) + self.assertTrue(np.array_equal(np.array(resized_image), np.array(resized_image2))) + + resized_image3 = feature_extractor.resize(image, (8, 16)) + self.assertTrue(isinstance(resized_image3, PIL.Image.Image)) + self.assertEqual(resized_image3.size, (8, 16)) + self.assertTrue(np.array_equal(np.array(resized_image1), np.array(resized_image3))) + + def test_resize_image_and_array_non_default_to_square(self): + feature_extractor = ImageFeatureExtractionMixin() + + heights_widths = [ + # height, width + # square image + (28, 28), + (27, 27), + # rectangular image: h < w + (28, 34), + (29, 35), + # rectangular image: h > w + (34, 28), + (35, 29), + ] + + # single integer or single integer in tuple/list + sizes = [22, 27, 28, 36, [22], (27,)] + + for (height, width), size in zip(heights_widths, sizes): + for max_size in (None, 37, 1000): + image = get_random_image(height, width) + array = np.array(image) + + size = size[0] if isinstance(size, (list, tuple)) else size + # Size can be an int or a tuple of ints. + # If size is an int, smaller edge of the image will be matched to this number. + # i.e, if height > width, then image will be rescaled to (size * height / width, size). + if height < width: + exp_w, exp_h = (int(size * width / height), size) + if max_size is not None and max_size < exp_w: + exp_w, exp_h = max_size, int(max_size * exp_h / exp_w) + elif width < height: + exp_w, exp_h = (size, int(size * height / width)) + if max_size is not None and max_size < exp_h: + exp_w, exp_h = int(max_size * exp_w / exp_h), max_size + else: + exp_w, exp_h = (size, size) + if max_size is not None and max_size < size: + exp_w, exp_h = max_size, max_size + + resized_image = feature_extractor.resize(image, size=size, default_to_square=False, max_size=max_size) + self.assertTrue(isinstance(resized_image, PIL.Image.Image)) + self.assertEqual(resized_image.size, (exp_w, exp_h)) + + # Passing an array converts it to a PIL Image. + resized_image2 = feature_extractor.resize(array, size=size, default_to_square=False, max_size=max_size) + self.assertTrue(isinstance(resized_image2, PIL.Image.Image)) + self.assertEqual(resized_image2.size, (exp_w, exp_h)) + self.assertTrue(np.array_equal(np.array(resized_image), np.array(resized_image2))) + + @require_torch + def test_resize_tensor(self): + feature_extractor = ImageFeatureExtractionMixin() + tensor = torch.randint(0, 256, (16, 32, 3)) + array = tensor.numpy() + + # Size can be an int or a tuple of ints. + resized_image = feature_extractor.resize(tensor, 8) + self.assertTrue(isinstance(resized_image, PIL.Image.Image)) + self.assertEqual(resized_image.size, (8, 8)) + + resized_image1 = feature_extractor.resize(tensor, (8, 16)) + self.assertTrue(isinstance(resized_image1, PIL.Image.Image)) + self.assertEqual(resized_image1.size, (8, 16)) + + # Check we get the same results as with NumPy arrays. + resized_image2 = feature_extractor.resize(array, 8) + self.assertTrue(np.array_equal(np.array(resized_image), np.array(resized_image2))) + + resized_image3 = feature_extractor.resize(array, (8, 16)) + self.assertTrue(np.array_equal(np.array(resized_image1), np.array(resized_image3))) + + def test_normalize_image(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + array = np.array(image) + mean = [0.1, 0.5, 0.9] + std = [0.2, 0.4, 0.6] + + # PIL Image are converted to NumPy arrays for the normalization + normalized_image = feature_extractor.normalize(image, mean, std) + self.assertTrue(isinstance(normalized_image, np.ndarray)) + self.assertEqual(normalized_image.shape, (3, 16, 32)) + + # During the conversion rescale and channel first will be applied. + expected = array.transpose(2, 0, 1).astype(np.float32) * (1 / 255.0) + np_mean = np.array(mean).astype(np.float32)[:, None, None] + np_std = np.array(std).astype(np.float32)[:, None, None] + expected = (expected - np_mean) / np_std + self.assertTrue(np.array_equal(normalized_image, expected)) + + def test_normalize_array(self): + feature_extractor = ImageFeatureExtractionMixin() + array = np.random.random((16, 32, 3)) + mean = [0.1, 0.5, 0.9] + std = [0.2, 0.4, 0.6] + + # mean and std can be passed as lists or NumPy arrays. + expected = (array - np.array(mean)) / np.array(std) + normalized_array = feature_extractor.normalize(array, mean, std) + self.assertTrue(np.array_equal(normalized_array, expected)) + + normalized_array = feature_extractor.normalize(array, np.array(mean), np.array(std)) + self.assertTrue(np.array_equal(normalized_array, expected)) + + # Normalize will detect automatically if channel first or channel last is used. + array = np.random.random((3, 16, 32)) + expected = (array - np.array(mean)[:, None, None]) / np.array(std)[:, None, None] + normalized_array = feature_extractor.normalize(array, mean, std) + self.assertTrue(np.array_equal(normalized_array, expected)) + + normalized_array = feature_extractor.normalize(array, np.array(mean), np.array(std)) + self.assertTrue(np.array_equal(normalized_array, expected)) + + @require_torch + def test_normalize_tensor(self): + feature_extractor = ImageFeatureExtractionMixin() + tensor = torch.rand(16, 32, 3) + mean = [0.1, 0.5, 0.9] + std = [0.2, 0.4, 0.6] + + # mean and std can be passed as lists or tensors. + expected = (tensor - torch.tensor(mean)) / torch.tensor(std) + normalized_tensor = feature_extractor.normalize(tensor, mean, std) + self.assertTrue(torch.equal(normalized_tensor, expected)) + + normalized_tensor = feature_extractor.normalize(tensor, torch.tensor(mean), torch.tensor(std)) + self.assertTrue(torch.equal(normalized_tensor, expected)) + + # Normalize will detect automatically if channel first or channel last is used. + tensor = torch.rand(3, 16, 32) + expected = (tensor - torch.tensor(mean)[:, None, None]) / torch.tensor(std)[:, None, None] + normalized_tensor = feature_extractor.normalize(tensor, mean, std) + self.assertTrue(torch.equal(normalized_tensor, expected)) + + normalized_tensor = feature_extractor.normalize(tensor, torch.tensor(mean), torch.tensor(std)) + self.assertTrue(torch.equal(normalized_tensor, expected)) + + def test_center_crop_image(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + + # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions. + crop_sizes = [8, (8, 64), 20, (32, 64)] + for size in crop_sizes: + cropped_image = feature_extractor.center_crop(image, size) + self.assertTrue(isinstance(cropped_image, PIL.Image.Image)) + + # PIL Image.size is transposed compared to NumPy or PyTorch (width first instead of height first). + expected_size = (size, size) if isinstance(size, int) else (size[1], size[0]) + self.assertEqual(cropped_image.size, expected_size) + + def test_center_crop_array(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + array = feature_extractor.to_numpy_array(image) + + # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions. + crop_sizes = [8, (8, 64), 20, (32, 64)] + for size in crop_sizes: + cropped_array = feature_extractor.center_crop(array, size) + self.assertTrue(isinstance(cropped_array, np.ndarray)) + + expected_size = (size, size) if isinstance(size, int) else size + self.assertEqual(cropped_array.shape[-2:], expected_size) + + # Check result is consistent with PIL.Image.crop + cropped_image = feature_extractor.center_crop(image, size) + self.assertTrue(np.array_equal(cropped_array, feature_extractor.to_numpy_array(cropped_image))) + + @require_torch + def test_center_crop_tensor(self): + feature_extractor = ImageFeatureExtractionMixin() + image = get_random_image(16, 32) + array = feature_extractor.to_numpy_array(image) + tensor = torch.tensor(array) + + # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions. + crop_sizes = [8, (8, 64), 20, (32, 64)] + for size in crop_sizes: + cropped_tensor = feature_extractor.center_crop(tensor, size) + self.assertTrue(isinstance(cropped_tensor, torch.Tensor)) + + expected_size = (size, size) if isinstance(size, int) else size + self.assertEqual(cropped_tensor.shape[-2:], expected_size) + + # Check result is consistent with PIL.Image.crop + cropped_image = feature_extractor.center_crop(image, size) + self.assertTrue(torch.equal(cropped_tensor, torch.tensor(feature_extractor.to_numpy_array(cropped_image)))) + + +@require_vision +class LoadImageTester(unittest.TestCase): + def test_load_img_url(self): + img = load_image(INVOICE_URL) + img_arr = np.array(img) + + self.assertEqual(img_arr.shape, (1061, 750, 3)) + + @is_flaky() + def test_load_img_url_timeout(self): + with self.assertRaises((ReadTimeout, ConnectTimeout)): + load_image(INVOICE_URL, timeout=0.001) + + def test_load_img_local(self): + img = load_image("./tests/fixtures/tests_samples/COCO/000000039769.png") + img_arr = np.array(img) + + self.assertEqual( + img_arr.shape, + (480, 640, 3), + ) + + def test_load_img_base64_prefix(self): + try: + tmp_file = tempfile.NamedTemporaryFile(delete=False).name + with open(tmp_file, "wb") as f: + http_get( + "https://huggingface.co/datasets/hf-internal-testing/dummy-base64-images/raw/main/image_0.txt", f + ) + + with open(tmp_file, encoding="utf-8") as b64: + img = load_image(b64.read()) + img_arr = np.array(img) + + finally: + os.remove(tmp_file) + + self.assertEqual(img_arr.shape, (64, 32, 3)) + + def test_load_img_base64(self): + try: + tmp_file = tempfile.NamedTemporaryFile(delete=False).name + with open(tmp_file, "wb") as f: + http_get( + "https://huggingface.co/datasets/hf-internal-testing/dummy-base64-images/raw/main/image_1.txt", f + ) + + with open(tmp_file, encoding="utf-8") as b64: + img = load_image(b64.read()) + img_arr = np.array(img) + + finally: + os.remove(tmp_file) + + self.assertEqual(img_arr.shape, (64, 32, 3)) + + def test_load_img_base64_encoded_bytes(self): + try: + tmp_file = tempfile.NamedTemporaryFile(delete=False).name + with open(tmp_file, "wb") as f: + http_get( + "https://huggingface.co/datasets/hf-internal-testing/dummy-base64-images/raw/main/image_2.txt", f + ) + + with codecs.open(tmp_file, encoding="unicode_escape") as b64: + img = load_image(b64.read()) + img_arr = np.array(img) + + finally: + os.remove(tmp_file) + + self.assertEqual(img_arr.shape, (256, 256, 3)) + + def test_load_img_rgba(self): + # we use revision="refs/pr/1" until the PR is merged + # https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1 + img = get_image_from_hub_dataset( + "hf-internal-testing/fixtures_image_utils", "0-test-lena.png", revision="refs/pr/1" + ) + + img = load_image(img) # img with mode RGBA + img_arr = np.array(img) + + self.assertEqual( + img_arr.shape, + (512, 512, 3), + ) + + def test_load_img_la(self): + # we use revision="refs/pr/1" until the PR is merged + # https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1 + img = get_image_from_hub_dataset( + "hf-internal-testing/fixtures_image_utils", "1-test-parrots.png", revision="refs/pr/1" + ) + + img = load_image(img) # img with mode LA + img_arr = np.array(img) + + self.assertEqual( + img_arr.shape, + (512, 768, 3), + ) + + def test_load_img_l(self): + # we use revision="refs/pr/1" until the PR is merged + # https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1 + img = get_image_from_hub_dataset( + "hf-internal-testing/fixtures_image_utils", "2-test-tree.png", revision="refs/pr/1" + ) + + img = load_image(img) # img with mode L + img_arr = np.array(img) + + self.assertEqual( + img_arr.shape, + (381, 225, 3), + ) + + def test_load_img_exif_transpose(self): + # we use revision="refs/pr/1" until the PR is merged + # https://hf.co/datasets/hf-internal-testing/fixtures_image_utils/discussions/1 + + img_without_exif_transpose = get_image_from_hub_dataset( + "hf-internal-testing/fixtures_image_utils", "3-test-cat-rotated.jpg", revision="refs/pr/1" + ) + img_arr_without_exif_transpose = np.array(img_without_exif_transpose) + + self.assertEqual( + img_arr_without_exif_transpose.shape, + (333, 500, 3), + ) + + img_with_exif_transpose = load_image(img_without_exif_transpose) + img_arr_with_exif_transpose = np.array(img_with_exif_transpose) + + self.assertEqual( + img_arr_with_exif_transpose.shape, + (500, 333, 3), + ) + + +class UtilFunctionTester(unittest.TestCase): + def test_get_image_size(self): + # Test we can infer the size and channel dimension of an image. + image = np.random.randint(0, 256, (32, 64, 3)) + self.assertEqual(get_image_size(image), (32, 64)) + + image = np.random.randint(0, 256, (3, 32, 64)) + self.assertEqual(get_image_size(image), (32, 64)) + + # Test the channel dimension can be overridden + image = np.random.randint(0, 256, (3, 32, 64)) + self.assertEqual(get_image_size(image, channel_dim=ChannelDimension.LAST), (3, 32)) + + def test_infer_channel_dimension(self): + # Test we fail with invalid input + with pytest.raises(ValueError): + infer_channel_dimension_format(np.random.randint(0, 256, (10, 10))) + + with pytest.raises(ValueError): + infer_channel_dimension_format(np.random.randint(0, 256, (10, 10, 10, 10, 10))) + + # Test we fail if neither first not last dimension is of size 3 or 1 + with pytest.raises(ValueError): + infer_channel_dimension_format(np.random.randint(0, 256, (10, 1, 50))) + + # But if we explicitly set one of the number of channels to 50 it works + inferred_dim = infer_channel_dimension_format(np.random.randint(0, 256, (10, 1, 50)), num_channels=50) + self.assertEqual(inferred_dim, ChannelDimension.LAST) + + # Test we correctly identify the channel dimension + image = np.random.randint(0, 256, (3, 4, 5)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.FIRST) + + image = np.random.randint(0, 256, (1, 4, 5)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.FIRST) + + image = np.random.randint(0, 256, (4, 5, 3)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.LAST) + + image = np.random.randint(0, 256, (4, 5, 1)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.LAST) + + # We can take a batched array of images and find the dimension + image = np.random.randint(0, 256, (1, 3, 4, 5)) + inferred_dim = infer_channel_dimension_format(image) + self.assertEqual(inferred_dim, ChannelDimension.FIRST) + + def test_get_channel_dimension_axis(self): + # Test we correctly identify the channel dimension + image = np.random.randint(0, 256, (3, 4, 5)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 0) + + image = np.random.randint(0, 256, (1, 4, 5)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 0) + + image = np.random.randint(0, 256, (4, 5, 3)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 2) + + image = np.random.randint(0, 256, (4, 5, 1)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 2) + + # We can take a batched array of images and find the dimension + image = np.random.randint(0, 256, (1, 3, 4, 5)) + inferred_axis = get_channel_dimension_axis(image) + self.assertEqual(inferred_axis, 1) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_import_structure.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_import_structure.py new file mode 100644 index 0000000000000000000000000000000000000000..1a4588a0d3936bfa35e09813efce4792f66a6c1a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_import_structure.py @@ -0,0 +1,208 @@ +import os +import unittest +from pathlib import Path +from typing import Callable + +import pytest + +from transformers.utils.import_utils import ( + Backend, + VersionComparison, + define_import_structure, + spread_import_structure, +) + + +import_structures = Path(__file__).parent / "import_structures" + + +def fetch__all__(file_content): + """ + Returns the content of the __all__ variable in the file content. + Returns None if not defined, otherwise returns a list of strings. + """ + lines = file_content.split("\n") + for line_index in range(len(lines)): + line = lines[line_index] + if line.startswith("__all__ = "): + # __all__ is defined on a single line + if line.endswith("]"): + return [obj.strip("\"' ") for obj in line.split("=")[1].strip(" []").split(",")] + + # __all__ is defined on multiple lines + else: + _all = [] + for __all__line_index in range(line_index + 1, len(lines)): + if lines[__all__line_index].strip() == "]": + return _all + else: + _all.append(lines[__all__line_index].strip("\"', ")) + + +class TestImportStructures(unittest.TestCase): + base_transformers_path = Path(__file__).parent.parent.parent + models_path = base_transformers_path / "src" / "transformers" / "models" + models_import_structure = spread_import_structure(define_import_structure(models_path)) + + def test_definition(self): + import_structure = define_import_structure(import_structures) + valid_frozensets: dict[frozenset | frozenset[str], dict[str, set[str]]] = { + frozenset(): { + "import_structure_raw_register": {"A0", "A4", "a0"}, + "import_structure_register_with_comments": {"B0", "b0"}, + }, + frozenset({"random_item_that_should_not_exist"}): {"failing_export": {"A0"}}, + frozenset({"torch"}): { + "import_structure_register_with_duplicates": {"C0", "C1", "C2", "C3", "c0", "c1", "c2", "c3"} + }, + frozenset({"tf", "torch"}): { + "import_structure_raw_register": {"A1", "A2", "A3", "a1", "a2", "a3"}, + "import_structure_register_with_comments": {"B1", "B2", "B3", "b1", "b2", "b3"}, + }, + frozenset({"torch>=2.5"}): {"import_structure_raw_register_with_versions": {"D0", "d0"}}, + frozenset({"torch>2.5"}): {"import_structure_raw_register_with_versions": {"D1", "d1"}}, + frozenset({"torch<=2.5"}): {"import_structure_raw_register_with_versions": {"D2", "d2"}}, + frozenset({"torch<2.5"}): {"import_structure_raw_register_with_versions": {"D3", "d3"}}, + frozenset({"torch==2.5"}): {"import_structure_raw_register_with_versions": {"D4", "d4"}}, + frozenset({"torch!=2.5"}): {"import_structure_raw_register_with_versions": {"D5", "d5"}}, + frozenset({"torch>=2.5", "accelerate<0.20"}): { + "import_structure_raw_register_with_versions": {"D6", "d6"} + }, + } + + self.assertEqual(len(import_structure.keys()), len(valid_frozensets.keys())) + for _frozenset in valid_frozensets: + self.assertTrue(_frozenset in import_structure) + self.assertListEqual(list(import_structure[_frozenset].keys()), list(valid_frozensets[_frozenset].keys())) + for module, objects in valid_frozensets[_frozenset].items(): + self.assertTrue(module in import_structure[_frozenset]) + self.assertSetEqual(objects, import_structure[_frozenset][module]) + + def test_transformers_specific_model_import(self): + """ + This test ensures that there is equivalence between what is written down in __all__ and what is + written down with register(). + + It doesn't test the backends attributed to register(). + """ + for architecture in os.listdir(self.models_path): + if ( + os.path.isfile(self.models_path / architecture) + or architecture.startswith("_") + or architecture == "deprecated" + ): + continue + + with self.subTest(f"Testing arch {architecture}"): + import_structure = define_import_structure(self.models_path / architecture) + backend_agnostic_import_structure = {} + for module_object_mapping in import_structure.values(): + for module, objects in module_object_mapping.items(): + if module not in backend_agnostic_import_structure: + backend_agnostic_import_structure[module] = [] + + backend_agnostic_import_structure[module].extend(objects) + + for module, objects in backend_agnostic_import_structure.items(): + with open(self.models_path / architecture / f"{module}.py") as f: + content = f.read() + _all = fetch__all__(content) + + if _all is None: + raise ValueError(f"{module} doesn't have __all__ defined.") + + error_message = ( + f"self.models_path / architecture / f'{module}.py doesn't seem to be defined correctly:\n" + f"Defined in __all__: {sorted(_all)}\nDefined with register: {sorted(objects)}" + ) + self.assertListEqual(sorted(objects), sorted(_all), msg=error_message) + + def test_import_spread(self): + """ + This test is specifically designed to test that varying levels of depth across import structures are + respected. + + In this instance, frozensets are at respective depths of 1, 2 and 3, for example: + - models.{frozensets} + - models.albert.{frozensets} + - models.deprecated.transfo_xl.{frozensets} + """ + initial_import_structure = { + frozenset(): {"dummy_non_model": {"DummyObject"}}, + "models": { + frozenset(): {"dummy_config": {"DummyConfig"}}, + "albert": { + frozenset(): {"configuration_albert": {"AlbertConfig", "AlbertOnnxConfig"}}, + frozenset({"torch"}): { + "modeling_albert": { + "AlbertForMaskedLM", + } + }, + }, + "llama": { + frozenset(): {"configuration_llama": {"LlamaConfig"}}, + frozenset({"torch"}): { + "modeling_llama": { + "LlamaForCausalLM", + } + }, + }, + "deprecated": { + "transfo_xl": { + frozenset({"torch"}): { + "modeling_transfo_xl": { + "TransfoXLModel", + } + }, + frozenset(): { + "configuration_transfo_xl": {"TransfoXLConfig"}, + "tokenization_transfo_xl": {"TransfoXLCorpus", "TransfoXLTokenizer"}, + }, + }, + "deta": { + frozenset({"torch"}): { + "modeling_deta": {"DetaForObjectDetection", "DetaModel", "DetaPreTrainedModel"} + }, + frozenset(): {"configuration_deta": {"DetaConfig"}}, + frozenset({"vision"}): {"image_processing_deta": {"DetaImageProcessor"}}, + }, + }, + }, + } + + ground_truth_spread_import_structure = { + frozenset(): { + "dummy_non_model": {"DummyObject"}, + "models.dummy_config": {"DummyConfig"}, + "models.albert.configuration_albert": {"AlbertConfig", "AlbertOnnxConfig"}, + "models.llama.configuration_llama": {"LlamaConfig"}, + "models.deprecated.transfo_xl.configuration_transfo_xl": {"TransfoXLConfig"}, + "models.deprecated.transfo_xl.tokenization_transfo_xl": {"TransfoXLCorpus", "TransfoXLTokenizer"}, + "models.deprecated.deta.configuration_deta": {"DetaConfig"}, + }, + frozenset({"torch"}): { + "models.albert.modeling_albert": {"AlbertForMaskedLM"}, + "models.llama.modeling_llama": {"LlamaForCausalLM"}, + "models.deprecated.transfo_xl.modeling_transfo_xl": {"TransfoXLModel"}, + "models.deprecated.deta.modeling_deta": {"DetaForObjectDetection", "DetaModel", "DetaPreTrainedModel"}, + }, + frozenset({"vision"}): {"models.deprecated.deta.image_processing_deta": {"DetaImageProcessor"}}, + } + + newly_spread_import_structure = spread_import_structure(initial_import_structure) + + self.assertEqual(ground_truth_spread_import_structure, newly_spread_import_structure) + + +@pytest.mark.parametrize( + "backend,package_name,version_comparison,version", + [ + pytest.param(Backend("torch>=2.5 "), "torch", VersionComparison.GREATER_THAN_OR_EQUAL.value, "2.5"), + pytest.param(Backend("tf<=1"), "tf", VersionComparison.LESS_THAN_OR_EQUAL.value, "1"), + pytest.param(Backend("torchvision==0.19.1"), "torchvision", VersionComparison.EQUAL.value, "0.19.1"), + ], +) +def test_backend_specification(backend: Backend, package_name: str, version_comparison: Callable, version: str): + assert backend.package_name == package_name + assert VersionComparison.from_string(backend.version_comparison) == version_comparison + assert backend.version == version diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_import_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fe616e9cfbe272a9fbe004b00314ff4ac87a9373 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_import_utils.py @@ -0,0 +1,26 @@ +import sys + +from transformers.testing_utils import run_test_using_subprocess +from transformers.utils.import_utils import clear_import_cache + + +@run_test_using_subprocess +def test_clear_import_cache(): + """Test the clear_import_cache function.""" + + # Save initial state + initial_modules = {name: mod for name, mod in sys.modules.items() if name.startswith("transformers.")} + assert len(initial_modules) > 0, "No transformers modules loaded before test" + + # Execute clear_import_cache() function + clear_import_cache() + + # Verify modules were removed + remaining_modules = {name: mod for name, mod in sys.modules.items() if name.startswith("transformers.")} + assert len(remaining_modules) < len(initial_modules), "No modules were removed" + + # Import and verify module exists + from transformers.models.auto import modeling_auto + + assert "transformers.models.auto.modeling_auto" in sys.modules + assert modeling_auto.__name__ == "transformers.models.auto.modeling_auto" diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_logging.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_logging.py new file mode 100644 index 0000000000000000000000000000000000000000..c9bbb824365108541d6e22cb0cae09c355e14b50 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_logging.py @@ -0,0 +1,135 @@ +# 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. + +import os +import unittest + +from huggingface_hub.utils import are_progress_bars_disabled + +import transformers.models.bart.tokenization_bart +from transformers import logging +from transformers.testing_utils import CaptureLogger, mockenv, mockenv_context +from transformers.utils.logging import disable_progress_bar, enable_progress_bar + + +class HfArgumentParserTest(unittest.TestCase): + def test_set_level(self): + logger = logging.get_logger() + + # the current default level is logging.WARNING + level_origin = logging.get_verbosity() + + logging.set_verbosity_error() + self.assertEqual(logger.getEffectiveLevel(), logging.get_verbosity()) + + logging.set_verbosity_warning() + self.assertEqual(logger.getEffectiveLevel(), logging.get_verbosity()) + + logging.set_verbosity_info() + self.assertEqual(logger.getEffectiveLevel(), logging.get_verbosity()) + + logging.set_verbosity_debug() + self.assertEqual(logger.getEffectiveLevel(), logging.get_verbosity()) + + # restore to the original level + logging.set_verbosity(level_origin) + + def test_integration(self): + level_origin = logging.get_verbosity() + + logger = logging.get_logger("transformers.models.bart.tokenization_bart") + msg = "Testing 1, 2, 3" + + # should be able to log warnings (if default settings weren't overridden by `pytest --log-level-all`) + if level_origin <= logging.WARNING: + with CaptureLogger(logger) as cl: + logger.warning(msg) + self.assertEqual(cl.out, msg + "\n") + + # this is setting the level for all of `transformers.*` loggers + logging.set_verbosity_error() + + # should not be able to log warnings + with CaptureLogger(logger) as cl: + logger.warning(msg) + self.assertEqual(cl.out, "") + + # should be able to log warnings again + logging.set_verbosity_warning() + with CaptureLogger(logger) as cl: + logger.warning(msg) + self.assertEqual(cl.out, msg + "\n") + + # restore to the original level + logging.set_verbosity(level_origin) + + @mockenv(TRANSFORMERS_VERBOSITY="error") + def test_env_override(self): + # reset for the env var to take effect, next time some logger call is made + transformers.utils.logging._reset_library_root_logger() + # this action activates the env var + _ = logging.get_logger("transformers.models.bart.tokenization_bart") + + env_level_str = os.getenv("TRANSFORMERS_VERBOSITY", None) + env_level = logging.log_levels[env_level_str] + + current_level = logging.get_verbosity() + self.assertEqual( + env_level, + current_level, + f"TRANSFORMERS_VERBOSITY={env_level_str}/{env_level}, but internal verbosity is {current_level}", + ) + + # restore to the original level + os.environ["TRANSFORMERS_VERBOSITY"] = "" + transformers.utils.logging._reset_library_root_logger() + + @mockenv(TRANSFORMERS_VERBOSITY="super-error") + def test_env_invalid_override(self): + # reset for the env var to take effect, next time some logger call is made + transformers.utils.logging._reset_library_root_logger() + logger = logging.logging.getLogger() + with CaptureLogger(logger) as cl: + # this action activates the env var + logging.get_logger("transformers.models.bart.tokenization_bart") + self.assertIn("Unknown option TRANSFORMERS_VERBOSITY=super-error", cl.out) + + # no need to restore as nothing was changed + + def test_advisory_warnings(self): + # testing `logger.warning_advice()` + transformers.utils.logging._reset_library_root_logger() + + logger = logging.get_logger("transformers.models.bart.tokenization_bart") + msg = "Testing 1, 2, 3" + + with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS="1"): + # nothing should be logged as env var disables this method + with CaptureLogger(logger) as cl: + logger.warning_advice(msg) + self.assertEqual(cl.out, "") + + with mockenv_context(TRANSFORMERS_NO_ADVISORY_WARNINGS=""): + # should log normally as TRANSFORMERS_NO_ADVISORY_WARNINGS is unset + with CaptureLogger(logger) as cl: + logger.warning_advice(msg) + self.assertEqual(cl.out, msg + "\n") + + +def test_set_progress_bar_enabled(): + disable_progress_bar() + assert are_progress_bars_disabled() + + enable_progress_bar() + assert not are_progress_bars_disabled() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_masking_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_masking_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..11d7e7e72b89a4b7b41d714bbc50412688b616f3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_masking_utils.py @@ -0,0 +1,137 @@ +# Copyright 2025 HuggingFace 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. + +import unittest + +from transformers.testing_utils import is_torch_available, require_torch + + +if is_torch_available(): + import torch + from torch.nn.attention.flex_attention import create_block_mask + + from transformers import LlamaConfig + from transformers.masking_utils import create_causal_mask, find_packed_sequence_indices + + +# fmt: off +EXPECTED_PACKED_MASK = torch.tensor([[[ + [ True, False, False, False, False, False, False, False, False, False], + [ True, True, False, False, False, False, False, False, False, False], + [ True, True, True, False, False, False, False, False, False, False], + [ True, True, True, True, False, False, False, False, False, False], + [False, False, False, False, True, False, False, False, False, False], + [False, False, False, False, True, True, False, False, False, False], + [False, False, False, False, False, False, True, False, False, False], + [False, False, False, False, False, False, True, True, False, False], + [False, False, False, False, False, False, True, True, True, False], + [False, False, False, False, False, False, True, True, True, True]]], + + + [[[ True, False, False, False, False, False, False, False, False, False], + [ True, True, False, False, False, False, False, False, False, False], + [ True, True, True, False, False, False, False, False, False, False], + [ True, True, True, True, False, False, False, False, False, False], + [ True, True, True, True, True, False, False, False, False, False], + [ True, True, True, True, True, True, False, False, False, False], + [False, False, False, False, False, False, True, False, False, False], + [False, False, False, False, False, False, True, True, False, False], + [False, False, False, False, False, False, True, True, True, False], + [False, False, False, False, False, False, True, True, True, True] +]]], dtype=torch.bool) +# fmt: on + + +@require_torch +class MaskTest(unittest.TestCase): + def test_packed_sequence_mask_sdpa(self): + config = LlamaConfig() + config._attn_implementation = "sdpa" + + batch_size = 2 + sequence_length = 10 + cache_position = torch.arange(sequence_length) + + # First batch has 3 packed sequences of 4, 2 and 4 tokens respectively, second has 2 of 6 and 4 tokens + position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) + + causal_mask = create_causal_mask( + config=config, + # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings + input_embeds=torch.empty((batch_size, sequence_length), dtype=torch.float16), + attention_mask=None, + cache_position=cache_position, + past_key_values=None, + position_ids=position_ids, + ) + + self.assertTrue((causal_mask == EXPECTED_PACKED_MASK).all()) + + def test_packed_sequence_mask_eager(self): + config = LlamaConfig() + config._attn_implementation = "eager" + + batch_size = 2 + sequence_length = 10 + cache_position = torch.arange(sequence_length) + + # First batch has 3 packed sequences of 4, 2 and 4 tokens respectively, second has 2 of 6 and 4 tokens + position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) + + causal_mask = create_causal_mask( + config=config, + # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings + input_embeds=torch.empty((batch_size, sequence_length), dtype=torch.float16), + attention_mask=None, + cache_position=cache_position, + past_key_values=None, + position_ids=position_ids, + ) + + min_dtype = torch.finfo(torch.float16).min + self.assertTrue((causal_mask == torch.where(EXPECTED_PACKED_MASK, 0.0, min_dtype)).all()) + + def test_packed_sequence_mask_flex_attention(self): + config = LlamaConfig() + config._attn_implementation = "flex_attention" + + batch_size = 2 + sequence_length = 10 + cache_position = torch.arange(sequence_length) + + # First batch has 3 packed sequences of 4, 2 and 4 tokens respectively, second has 2 of 6 and 4 tokens + position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) + + causal_mask = create_causal_mask( + config=config, + # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings + input_embeds=torch.empty((batch_size, sequence_length), dtype=torch.float16), + attention_mask=None, + cache_position=cache_position, + past_key_values=None, + position_ids=position_ids, + ) + + def dummy_mask_mod(b, h, q, kv): + return EXPECTED_PACKED_MASK[b, h, q, kv] + + EXPECTED_BLOCK_MASK = create_block_mask(dummy_mask_mod, 2, None, 10, 10, device="cpu") + + # We compatre the str representations, as the BlockMask objects themselves cannot easily be compared + self.assertEqual(causal_mask.to_string(), EXPECTED_BLOCK_MASK.to_string()) + + def test_find_packed_sequence_indices(self): + position_ids = torch.tensor([[0, 1, 2, 3, 0, 1, 0, 1, 2, 3], [0, 1, 2, 3, 4, 5, 0, 1, 2, 3]]) + EXPECTED_SEQUENCE_INDICES = torch.tensor([[0, 0, 0, 0, 1, 1, 2, 2, 2, 2], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1]]) + self.assertTrue((find_packed_sequence_indices(position_ids) == EXPECTED_SEQUENCE_INDICES).all()) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_card.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_card.py new file mode 100644 index 0000000000000000000000000000000000000000..16dec39081caab579b76f7fce1e6716fe9e18a09 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_card.py @@ -0,0 +1,88 @@ +# Copyright 2019 HuggingFace 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. + + +import json +import os +import tempfile +import unittest + +from transformers.modelcard import ModelCard, TrainingSummary + + +class ModelCardTester(unittest.TestCase): + def setUp(self): + self.inputs_dict = { + "model_details": { + "Organization": "testing", + "Model date": "today", + "Model version": "v2.1, Developed by Test Corp in 2019.", + "Architecture": "Convolutional Neural Network.", + }, + "metrics": "BLEU and ROUGE-1", + "evaluation_data": { + "Datasets": {"BLEU": "My-great-dataset-v1", "ROUGE-1": "My-short-dataset-v2.1"}, + "Preprocessing": "See details on https://huggingface.co/papers/1810.03993", + }, + "training_data": { + "Dataset": "English Wikipedia dump dated 2018-12-01", + "Preprocessing": ( + "Using SentencePiece vocabulary of size 52k tokens. See details on" + " https://huggingface.co/papers/1810.03993" + ), + }, + "quantitative_analyses": {"BLEU": 55.1, "ROUGE-1": 76}, + } + + def test_model_card_common_properties(self): + modelcard = ModelCard.from_dict(self.inputs_dict) + self.assertTrue(hasattr(modelcard, "model_details")) + self.assertTrue(hasattr(modelcard, "intended_use")) + self.assertTrue(hasattr(modelcard, "factors")) + self.assertTrue(hasattr(modelcard, "metrics")) + self.assertTrue(hasattr(modelcard, "evaluation_data")) + self.assertTrue(hasattr(modelcard, "training_data")) + self.assertTrue(hasattr(modelcard, "quantitative_analyses")) + self.assertTrue(hasattr(modelcard, "ethical_considerations")) + self.assertTrue(hasattr(modelcard, "caveats_and_recommendations")) + + def test_model_card_to_json_string(self): + modelcard = ModelCard.from_dict(self.inputs_dict) + obj = json.loads(modelcard.to_json_string()) + for key, value in self.inputs_dict.items(): + self.assertEqual(obj[key], value) + + def test_model_card_to_json_file(self): + model_card_first = ModelCard.from_dict(self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + filename = os.path.join(tmpdirname, "modelcard.json") + model_card_first.to_json_file(filename) + model_card_second = ModelCard.from_json_file(filename) + + self.assertEqual(model_card_second.to_dict(), model_card_first.to_dict()) + + def test_model_card_from_and_save_pretrained(self): + model_card_first = ModelCard.from_dict(self.inputs_dict) + + with tempfile.TemporaryDirectory() as tmpdirname: + model_card_first.save_pretrained(tmpdirname) + model_card_second = ModelCard.from_pretrained(tmpdirname) + + self.assertEqual(model_card_second.to_dict(), model_card_first.to_dict()) + + def test_model_summary_modelcard_base_metadata(self): + metadata = TrainingSummary("Model name").create_metadata() + self.assertTrue("library_name" in metadata) + self.assertTrue(metadata["library_name"] == "transformers") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_debugging_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_debugging_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..30419f8b7efa318f44c3d48c13edb221795b5e3a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_debugging_utils.py @@ -0,0 +1,122 @@ +# coding=utf-8 +# Copyright 2025 The HuggingFace Inc. team. +# +# 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. + +import gc +import json +import os +import tempfile +import unittest +from pathlib import Path + +from transformers import is_torch_available +from transformers.model_debugging_utils import model_addition_debugger_context + + +if is_torch_available(): + import torch + from torch import nn + + class ToyModel(nn.Module): + def __init__(self): + super().__init__() + self.embed = nn.Embedding(10, 4) + self.linear_1 = nn.Linear(4, 8) + self.linear_2 = nn.Linear(8, 2) + self.act = nn.ReLU() + + def forward(self, input_ids: str): + hidden_states = self.embed(input_ids).mean(dim=1) + hidden_states = self.act(self.linear_1(hidden_states)) + return self.linear_2(hidden_states) + + class TestModelAdditionDebugger(unittest.TestCase): + def setUp(self): + self.model = ToyModel() + self.inputs = {"input_ids": torch.randint(0, 10, (1, 3))} + + def tearDown(self): + gc.collect() + + def test_debugger_outputs(self): + with tempfile.TemporaryDirectory() as tmpdir: + with model_addition_debugger_context(self.model, debug_path=str(tmpdir)): + _ = self.model.forward(**self.inputs) + + base = f"{self.model.__class__.__name__}_debug_tree" + summary = Path(os.path.join(tmpdir, f"{base}_SUMMARY.json")) + full = Path(os.path.join(tmpdir, f"{base}_FULL_TENSORS.json")) + self.assertTrue(os.path.isfile(summary) and os.path.isfile(full)) + data = json.loads(summary.read_text()) + self.assertTrue({"module_path", "inputs", "children"} <= data.keys()) + self.assertTrue(data["children"]) + + class ToyLayer(nn.Module): + def __init__(self, layer_index): + super().__init__() + self.layer_index = layer_index + self.layer_operation = nn.Linear(4, 4) + + def forward(self, hidden_states): + return self.layer_operation(hidden_states) + + class ToyModelWithLayers(nn.Module): + def __init__(self): + super().__init__() + self.input_proj = nn.Linear(4, 4) + self.layers = nn.ModuleList([ToyLayer(layer_index) for layer_index in range(6)]) + self.output_proj = nn.Linear(4, 2) + + def forward(self, x): + x = self.input_proj(x) + for layer in self.layers: + x = layer(x) + return self.output_proj(x) + + class TestModelWithLayers(unittest.TestCase): + def setUp(self): + self.inputs = {"input_ids": torch.randint(0, 10, (1, 3))} + self.model_with_layers = ToyModelWithLayers() + self.dense_input = {"x": torch.randn(1, 4)} + + def tearDown(self): + gc.collect() + + def test_layer_pruning_behavior(self): + # No pruning: expect all 6 layers + with tempfile.TemporaryDirectory() as tmpdir: + with model_addition_debugger_context(self.model_with_layers, debug_path=tmpdir, do_prune_layers=False): + _ = self.model_with_layers(**self.dense_input) + + summary_path = os.path.join(tmpdir, "ToyModelWithLayers_debug_tree_SUMMARY.json") + with open(summary_path) as f: + data = json.load(f) + self.assertEqual(set(data.keys()), {"module_path", "inputs", "children"}) + for layer_index in range(6): + self.assertEqual( + data["children"][layer_index + 1]["module_path"], + f"ToyModelWithLayers.layers.{int(layer_index)}", + ) + + # Pruning: expect only 2 layers (0 and 5) + with tempfile.TemporaryDirectory() as tmpdir: + with model_addition_debugger_context(self.model_with_layers, debug_path=tmpdir, do_prune_layers=True): + _ = self.model_with_layers(**self.dense_input) + + summary_path = os.path.join(tmpdir, "ToyModelWithLayers_debug_tree_SUMMARY.json") + with open(summary_path) as f: + data = json.load(f) + self.assertEqual(set(data.keys()), {"module_path", "inputs", "children"}) + self.assertEqual(data["children"][1]["module_path"], "ToyModelWithLayers.layers.0") + self.assertEqual(data["children"][2]["module_path"], "ToyModelWithLayers.layers.5") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_output.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_output.py new file mode 100644 index 0000000000000000000000000000000000000000..eef5feb014f51d72f34ec745461b062634ddbcb6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_model_output.py @@ -0,0 +1,204 @@ +# Copyright 2020 The Hugging Face Team. +# +# 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. + +import io +import unittest +from dataclasses import dataclass +from typing import Optional + +import pytest + +from transformers import AlbertForMaskedLM +from transformers.testing_utils import require_torch +from transformers.utils import ModelOutput, is_torch_available + + +if is_torch_available(): + import torch + + from transformers.pytorch_utils import is_torch_greater_or_equal_than_2_2 + + +@dataclass +class ModelOutputTest(ModelOutput): + a: float + b: Optional[float] = None + c: Optional[float] = None + + +class ModelOutputTester(unittest.TestCase): + def test_get_attributes(self): + x = ModelOutputTest(a=30) + self.assertEqual(x.a, 30) + self.assertIsNone(x.b) + self.assertIsNone(x.c) + with self.assertRaises(AttributeError): + _ = x.d + + def test_index_with_ints_and_slices(self): + x = ModelOutputTest(a=30, b=10) + self.assertEqual(x[0], 30) + self.assertEqual(x[1], 10) + self.assertEqual(x[:2], (30, 10)) + self.assertEqual(x[:], (30, 10)) + + x = ModelOutputTest(a=30, c=10) + self.assertEqual(x[0], 30) + self.assertEqual(x[1], 10) + self.assertEqual(x[:2], (30, 10)) + self.assertEqual(x[:], (30, 10)) + + def test_index_with_strings(self): + x = ModelOutputTest(a=30, b=10) + self.assertEqual(x["a"], 30) + self.assertEqual(x["b"], 10) + with self.assertRaises(KeyError): + _ = x["c"] + + x = ModelOutputTest(a=30, c=10) + self.assertEqual(x["a"], 30) + self.assertEqual(x["c"], 10) + with self.assertRaises(KeyError): + _ = x["b"] + + def test_dict_like_properties(self): + x = ModelOutputTest(a=30) + self.assertEqual(list(x.keys()), ["a"]) + self.assertEqual(list(x.values()), [30]) + self.assertEqual(list(x.items()), [("a", 30)]) + self.assertEqual(list(x), ["a"]) + + x = ModelOutputTest(a=30, b=10) + self.assertEqual(list(x.keys()), ["a", "b"]) + self.assertEqual(list(x.values()), [30, 10]) + self.assertEqual(list(x.items()), [("a", 30), ("b", 10)]) + self.assertEqual(list(x), ["a", "b"]) + + x = ModelOutputTest(a=30, c=10) + self.assertEqual(list(x.keys()), ["a", "c"]) + self.assertEqual(list(x.values()), [30, 10]) + self.assertEqual(list(x.items()), [("a", 30), ("c", 10)]) + self.assertEqual(list(x), ["a", "c"]) + + with self.assertRaises(Exception): + x = x.update({"d": 20}) + with self.assertRaises(Exception): + del x["a"] + with self.assertRaises(Exception): + _ = x.pop("a") + with self.assertRaises(Exception): + _ = x.setdefault("d", 32) + + def test_set_attributes(self): + x = ModelOutputTest(a=30) + x.a = 10 + self.assertEqual(x.a, 10) + self.assertEqual(x["a"], 10) + + def test_set_keys(self): + x = ModelOutputTest(a=30) + x["a"] = 10 + self.assertEqual(x.a, 10) + self.assertEqual(x["a"], 10) + + def test_instantiate_from_dict(self): + x = ModelOutputTest({"a": 30, "b": 10}) + self.assertEqual(list(x.keys()), ["a", "b"]) + self.assertEqual(x.a, 30) + self.assertEqual(x.b, 10) + + def test_instantiate_from_iterator(self): + x = ModelOutputTest([("a", 30), ("b", 10)]) + self.assertEqual(list(x.keys()), ["a", "b"]) + self.assertEqual(x.a, 30) + self.assertEqual(x.b, 10) + + with self.assertRaises(ValueError): + _ = ModelOutputTest([("a", 30), (10, 10)]) + + x = ModelOutputTest(a=(30, 30)) + self.assertEqual(list(x.keys()), ["a"]) + self.assertEqual(x.a, (30, 30)) + + @require_torch + def test_torch_pytree(self): + # ensure torch.utils._pytree treats ModelOutput subclasses as nodes (and not leaves) + # this is important for DistributedDataParallel gradient synchronization with static_graph=True + import torch.utils._pytree as pytree + + x = ModelOutput({"a": 1.0, "c": 2.0}) + self.assertFalse(pytree._is_leaf(x)) + + x = ModelOutputTest(a=1.0, c=2.0) + self.assertFalse(pytree._is_leaf(x)) + + expected_flat_outs = [1.0, 2.0] + expected_tree_spec = pytree.TreeSpec(ModelOutputTest, ["a", "c"], [pytree.LeafSpec(), pytree.LeafSpec()]) + + actual_flat_outs, actual_tree_spec = pytree.tree_flatten(x) + self.assertEqual(expected_flat_outs, actual_flat_outs) + self.assertEqual(expected_tree_spec, actual_tree_spec) + + unflattened_x = pytree.tree_unflatten(actual_flat_outs, actual_tree_spec) + self.assertEqual(x, unflattened_x) + + if is_torch_greater_or_equal_than_2_2: + self.assertEqual( + pytree.treespec_dumps(actual_tree_spec), + '[1, {"type": "tests.utils.test_model_output.ModelOutputTest", "context": "[\\"a\\", \\"c\\"]", "children_spec": [{"type": null, "context": null, "children_spec": []}, {"type": null, "context": null, "children_spec": []}]}]', + ) + + # TODO: @ydshieh + @unittest.skip(reason="CPU OOM") + @require_torch + @pytest.mark.torch_export_test + def test_export_serialization(self): + if not is_torch_greater_or_equal_than_2_2: + self.skipTest(reason="Export serialization requires torch >= 2.2.0") + + model_cls = AlbertForMaskedLM + model_config = model_cls.config_class() + model = model_cls(model_config) + + input_dict = {"input_ids": torch.randint(0, 30000, (1, 512), dtype=torch.int64, requires_grad=False)} + + ep = torch.export.export(model, (), input_dict) + + buffer = io.BytesIO() + torch.export.save(ep, buffer) + buffer.seek(0) + loaded_ep = torch.export.load(buffer) + + input_dict = {"input_ids": torch.randint(0, 30000, (1, 512), dtype=torch.int64, requires_grad=False)} + assert torch.allclose(model(**input_dict).logits, loaded_ep(**input_dict).logits) + + +class ModelOutputTestNoDataclass(ModelOutput): + """Invalid test subclass of ModelOutput where @dataclass decorator is not used""" + + a: float + b: Optional[float] = None + c: Optional[float] = None + + +class ModelOutputSubclassTester(unittest.TestCase): + def test_direct_model_output(self): + # Check that direct usage of ModelOutput instantiates without errors + ModelOutput({"a": 1.1}) + + def test_subclass_no_dataclass(self): + # Check that a subclass of ModelOutput without @dataclass is invalid + # A valid subclass is inherently tested other unit tests above. + with self.assertRaises(TypeError): + ModelOutputTestNoDataclass(a=1.1, b=2.2, c=3.3) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_modeling_rope_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_modeling_rope_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..9427b3771b4a2a7e881e819fd6c0216c603435ea --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_modeling_rope_utils.py @@ -0,0 +1,404 @@ +# Copyright 2024 HuggingFace 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. + + +import math +import unittest + +from transformers import LlamaConfig +from transformers.testing_utils import is_torch_available, require_torch, torch_device + + +if is_torch_available(): + import torch + + from transformers import ROPE_INIT_FUNCTIONS + from transformers.modeling_rope_utils import rope_config_validation + + +@require_torch +class RopeTest(unittest.TestCase): + def test_rope_validation(self): + config = LlamaConfig() + all_rope_types = ROPE_INIT_FUNCTIONS.keys() + + # The base config is always valid (default RoPE) + rope_config_validation(config) + + # If we explicitly set the other RoPE types, then validation should fail + for rope_type in all_rope_types: + if rope_type != "default": + config.rope_scaling = {"rope_type": rope_type} + with self.assertRaises(KeyError): + rope_config_validation(config) + + # Parameters are exclusive to their own RoPE type, and should raise an exception if incorrectly passed + valid_param_mapping = { + "factor": ["linear", "dynamic", "yarn", "longrope"], + "attention_factor": ["yarn", "longrope"], + "beta_fast": ["yarn"], + "beta_slow": ["yarn"], + "short_factor": ["longrope"], + "long_factor": ["longrope"], + } + for rope_type in all_rope_types: + if rope_type == "default": + continue # checked above + for param, valid_rope_types in valid_param_mapping.items(): + # Set `param` with a dummy value -- we want to test the dict key + config.rope_scaling = {"rope_type": rope_type, param: True} + if rope_type in valid_rope_types: + continue + else: + with self.assertRaises(KeyError): + rope_config_validation(config) + + # Any other parameters passed to RoPE will raise a warning that a particular key is not used + # But sometimes we can have model-specific RoPE kwargs and bypass warning with `ignore_keys` + model_specific_kwarg = "mrope_sections" # e,g in Qwen2-VL + + for rope_type in all_rope_types: + if rope_type == "default": + config.rope_scaling = {"rope_type": rope_type, model_specific_kwarg: True} + rope_config_validation(config, ignore_keys={model_specific_kwarg}) + with self.assertLogs("transformers.modeling_rope_utils", level="WARNING") as logs: + rope_config_validation(config) + self.assertEqual(len(logs.output), 1) + self.assertIn(model_specific_kwarg, logs.output[0]) + + def test_default_rope_numerically(self): + # Note: some RoPE scaling methods start off by calling the default RoPE frequencies. If this test fails, then + # multiple RoPE strategies will fail. + # fmt: off + EXPECTED_INV_FREQ = torch.tensor( + [ + 1.0000e+00, 8.6596e-01, 7.4989e-01, 6.4938e-01, 5.6234e-01, 4.8697e-01, + 4.2170e-01, 3.6517e-01, 3.1623e-01, 2.7384e-01, 2.3714e-01, 2.0535e-01, + 1.7783e-01, 1.5399e-01, 1.3335e-01, 1.1548e-01, 1.0000e-01, 8.6596e-02, + 7.4989e-02, 6.4938e-02, 5.6234e-02, 4.8697e-02, 4.2170e-02, 3.6517e-02, + 3.1623e-02, 2.7384e-02, 2.3714e-02, 2.0535e-02, 1.7783e-02, 1.5399e-02, + 1.3335e-02, 1.1548e-02, 1.0000e-02, 8.6596e-03, 7.4989e-03, 6.4938e-03, + 5.6234e-03, 4.8697e-03, 4.2170e-03, 3.6517e-03, 3.1623e-03, 2.7384e-03, + 2.3714e-03, 2.0535e-03, 1.7783e-03, 1.5399e-03, 1.3335e-03, 1.1548e-03, + 1.0000e-03, 8.6596e-04, 7.4989e-04, 6.4938e-04, 5.6234e-04, 4.8697e-04, + 4.2170e-04, 3.6517e-04, 3.1623e-04, 2.7384e-04, 2.3714e-04, 2.0535e-04, + 1.7783e-04, 1.5399e-04, 1.3335e-04, 1.1548e-04 + ], device=torch_device + ) + # fmt: on + + # input sanity checks: if these change, the output will also change + config = LlamaConfig() + self.assertEqual(config.rope_scaling, None) + self.assertEqual(config.hidden_size, 4096) + self.assertEqual(config.num_attention_heads, 32) + self.assertEqual(config.rope_theta, 10000.0) + self.assertFalse(hasattr(config, "partial_rotary_factor")) + + rope_fn = ROPE_INIT_FUNCTIONS["default"] + inv_freq, attention_scale = rope_fn(config=config, device=torch_device) + + self.assertEqual(attention_scale, 1.0) # attention scale is always 1 for default RoPE + torch.testing.assert_close(inv_freq, EXPECTED_INV_FREQ) + + def test_linear_rope_numerically(self): + # This is a linear scaling strategy, the **frequencies** are scaled linearly with respect to the default + # frequencies (= the inverse frequencies are scaled **inversely**) + config = LlamaConfig() + default_rope_fn = ROPE_INIT_FUNCTIONS["default"] + default_inv_freq, _ = default_rope_fn(config=config, device=torch_device) + + rope_fn = ROPE_INIT_FUNCTIONS["linear"] + for factor in (2.0, 10.0, 20.0): + config.rope_scaling = {"rope_type": "linear", "factor": factor} + inv_freq, attention_scale = rope_fn(config=config, device=torch_device) + self.assertEqual(attention_scale, 1.0) # attention scale is always 1 for linear RoPE + torch.testing.assert_close(inv_freq, default_inv_freq / factor) + + def test_dynamic_rope_numerically(self): + # fmt: off + EXPECTED_INV_FREQ = torch.tensor( + [ + 1.0000e+00, 8.0931e-01, 6.5498e-01, 5.3008e-01, 4.2900e-01, 3.4720e-01, + 2.8099e-01, 2.2741e-01, 1.8404e-01, 1.4895e-01, 1.2055e-01, 9.7558e-02, + 7.8955e-02, 6.3899e-02, 5.1714e-02, 4.1853e-02, 3.3872e-02, 2.7413e-02, + 2.2185e-02, 1.7955e-02, 1.4531e-02, 1.1760e-02, 9.5176e-03, 7.7027e-03, + 6.2339e-03, 5.0451e-03, 4.0831e-03, 3.3045e-03, 2.6744e-03, 2.1644e-03, + 1.7517e-03, 1.4176e-03, 1.1473e-03, 9.2852e-04, 7.5146e-04, 6.0817e-04, + 4.9220e-04, 3.9834e-04, 3.2238e-04, 2.6091e-04, 2.1115e-04, 1.7089e-04, + 1.3830e-04, 1.1193e-04, 9.0585e-05, 7.3312e-05, 5.9332e-05, 4.8018e-05, + 3.8861e-05, 3.1451e-05, 2.5453e-05, 2.0600e-05, 1.6672e-05, 1.3492e-05, + 1.0920e-05, 8.8374e-06, 7.1522e-06, 5.7883e-06, 4.6845e-06, 3.7912e-06, + 3.0683e-06, 2.4832e-06, 2.0097e-06, 1.6265e-06 + ], device=torch_device + ) + # fmt: on + + # input sanity checks: if these change, the output will also change + config = LlamaConfig() + self.assertEqual(config.rope_scaling, None) + self.assertEqual(config.hidden_size, 4096) + self.assertEqual(config.num_attention_heads, 32) + self.assertEqual(config.rope_theta, 10000.0) + self.assertFalse(hasattr(config, "partial_rotary_factor")) + + rope_fn = ROPE_INIT_FUNCTIONS["default"] + default_inv_freq, _ = rope_fn(config=config, device=torch_device) + + # Check 1: this is a dynamic scaling strategy, it will not scale unless we provide `seq_len` larger than the + # model's original training sequence length + rope_fn = ROPE_INIT_FUNCTIONS["dynamic"] + for factor in (2.0, 10.0, 20.0): + config.rope_scaling = {"rope_type": "dynamic", "factor": factor} + inv_freq, attention_scale = rope_fn(config=config, device=torch_device) + self.assertEqual(attention_scale, 1.0) # attention scale is always 1 for dynamic RoPE + torch.testing.assert_close(inv_freq, default_inv_freq) + + inv_freq, _ = rope_fn(config=config, device=torch_device, seq_len=1) + torch.testing.assert_close(inv_freq, default_inv_freq) + + inv_freq, _ = rope_fn(config=config, device=torch_device, seq_len=torch.tensor(1, dtype=torch.int64)) + torch.testing.assert_close(inv_freq, default_inv_freq) + + # Check 2: if we provide `seq_len` larger than the model's original training sequence length, the frequencies + # will scale up (i.e., the inverse frequencies will scale down). + factor = 10.0 + config.rope_scaling = {"rope_type": "dynamic", "factor": factor} + inv_freq, _ = rope_fn(config=config, device=torch_device, seq_len=16384) + with self.assertRaises(AssertionError): # It is NOT a linear factor + torch.testing.assert_close(inv_freq, default_inv_freq / factor) + torch.testing.assert_close(inv_freq, EXPECTED_INV_FREQ) + + def test_yarn_rope_numerically(self): + # fmt: off + EXPECTED_INV_FREQ = torch.tensor( + [ + 1.0000e+00, 8.6596e-01, 7.4989e-01, 6.4938e-01, 5.6234e-01, 4.8697e-01, + 4.2170e-01, 3.6517e-01, 3.1623e-01, 2.7384e-01, 2.3714e-01, 2.0535e-01, + 1.7783e-01, 1.5399e-01, 1.3335e-01, 1.1548e-01, 1.0000e-01, 8.3479e-02, + 6.9590e-02, 5.7925e-02, 4.8136e-02, 3.9931e-02, 3.3061e-02, 2.7315e-02, + 2.2515e-02, 1.8512e-02, 1.5177e-02, 1.2403e-02, 1.0101e-02, 8.1924e-03, + 6.6143e-03, 5.3120e-03, 4.2400e-03, 3.3599e-03, 2.6396e-03, 2.0520e-03, + 1.5746e-03, 1.1882e-03, 8.7713e-04, 6.2810e-04, 4.3007e-04, 2.7384e-04, + 2.3714e-04, 2.0535e-04, 1.7783e-04, 1.5399e-04, 1.3335e-04, 1.1548e-04, + 1.0000e-04, 8.6596e-05, 7.4989e-05, 6.4938e-05, 5.6234e-05, 4.8697e-05, + 4.2170e-05, 3.6517e-05, 3.1623e-05, 2.7384e-05, 2.3714e-05, 2.0535e-05, + 1.7783e-05, 1.5399e-05, 1.3335e-05, 1.1548e-05 + ], device=torch_device + ) + # fmt: on + + # input sanity checks: if these change, the output will also change + config = LlamaConfig() + self.assertEqual(config.rope_scaling, None) + self.assertEqual(config.hidden_size, 4096) + self.assertEqual(config.num_attention_heads, 32) + self.assertEqual(config.rope_theta, 10000.0) + self.assertFalse(hasattr(config, "partial_rotary_factor")) + + rope_fn = ROPE_INIT_FUNCTIONS["default"] + default_inv_freq, _ = rope_fn(config=config, device=torch_device) + + # Check 1: according to the paper, if `attention_factor` is not specified, then it has a specific default -- + # `0.1 * math.log(factor) + 1.0` + rope_fn = ROPE_INIT_FUNCTIONS["yarn"] + for factor in (2.0, 10.0, 20.0): + config.rope_scaling = {"rope_type": "yarn", "factor": factor} + _, attention_scale = rope_fn(config=config, device=torch_device) + self.assertEqual(attention_scale, 0.1 * math.log(factor) + 1.0) + + config.rope_scaling = {"rope_type": "yarn", "factor": factor, "attention_factor": 0.5} + _, attention_scale = rope_fn(config=config, device=torch_device, seq_len=1) + self.assertEqual(attention_scale, 0.5) + + # Check 2: based on `beta_fast` and `beta_slow`, the frequencies will be scaled between 1 and `factor`. + # Increasing `beta_fast` will make RoPE more interpolative (apply scaling), and the other way around. + # `beta_slow` behaves the opposite way. Remember: `beta_fast` > `beta_slow` + # (note: adds a margin to the test for numerical stability) + factor = 10.0 + margin = 1e-8 + config.rope_scaling = {"rope_type": "yarn", "factor": factor, "beta_fast": 32, "beta_slow": 1} + inv_freq, _ = rope_fn(config=config, device=torch_device) + is_bounded_by_factor = [ + ((default_inv_freq[idx] / factor) - margin) <= yarn_inv_freq_value <= (default_inv_freq[idx] + margin) + for idx, yarn_inv_freq_value in enumerate(inv_freq) + ] + self.assertTrue(all(is_bounded_by_factor)) + + # super high beta_fast = interpolation (i.e. scaling) in all but the first inverse frequency. The last ~20 + # values (empirically checked for `beta_fast` = 1000) should be very small to linear scaling + config.rope_scaling = {"rope_type": "yarn", "factor": factor, "beta_fast": 1000, "beta_slow": 1} + inv_freq, _ = rope_fn(config=config, device=torch_device) + is_interpolating = [ + yarn_inv_freq_value < (default_inv_freq[idx] + margin) for idx, yarn_inv_freq_value in enumerate(inv_freq) + ] + self.assertFalse(is_interpolating[0]) + self.assertTrue(all(is_interpolating[1:])) + torch.testing.assert_close(inv_freq[-20:], default_inv_freq[-20:] / factor) + + # Check 3: numerical snapshot to avoid regressions + config.rope_scaling = {"rope_type": "yarn", "factor": factor, "beta_fast": 32, "beta_slow": 1} + inv_freq, _ = rope_fn(config=config, device=torch_device) + torch.testing.assert_close(inv_freq, EXPECTED_INV_FREQ) + + def test_longrope_rope_numerically(self): + # input sanity checks: if these change, the output will also change + config = LlamaConfig() + self.assertEqual(config.rope_scaling, None) + self.assertEqual(config.hidden_size, 4096) + self.assertEqual(config.num_attention_heads, 32) + self.assertEqual(config.rope_theta, 10000.0) + self.assertFalse(hasattr(config, "partial_rotary_factor")) + + # longrope applies scaling on EACH inv frequency, `short_factor` or `long_factor`, depending on the seq_len + dim = config.hidden_size // config.num_attention_heads + short_factor = [2.0] * (dim // 2) # scaling applied when seq_len <= max_position_embeddings + long_factor = torch.ones(dim // 2).cumsum(0).tolist() # scaling applied when seq_len > max_position_embeddings + + rope_fn = ROPE_INIT_FUNCTIONS["default"] + default_inv_freq, _ = rope_fn(config=config, device=torch_device) + + # Check 1: according to the paper, if `attention_factor` is not specified, then it has a specific default -- + # `math.sqrt(1 + math.log(factor) / math.log(max_position_embeddings))` + rope_fn = ROPE_INIT_FUNCTIONS["longrope"] + max_position_embeddings = config.max_position_embeddings + for factor in (2.0, 10.0, 20.0): + config.rope_scaling = { + "rope_type": "longrope", + "factor": factor, + "short_factor": short_factor, + "long_factor": long_factor, + } + _, attention_scale = rope_fn(config=config, device=torch_device) + self.assertEqual(attention_scale, math.sqrt(1 + math.log(factor) / math.log(max_position_embeddings))) + + config.rope_scaling = { + "rope_type": "longrope", + "factor": factor, + "short_factor": short_factor, + "long_factor": long_factor, + "attention_factor": 0.5, + } + _, attention_scale = rope_fn(config=config, device=torch_device, seq_len=1) + self.assertEqual(attention_scale, 0.5) + + config.rope_scaling = { + "rope_type": "longrope", + "factor": factor, + "short_factor": short_factor, + "long_factor": long_factor, + } + self.assertEqual(config.rope_scaling.get("attention_factor"), None) + # Verify that "TypeError: '<' not supported between instances of 'NoneType' and 'int'" is not raised. + rope_config_validation(config) + + # Check 2: seq_len == 0 -> short factor is applied to the default frequencies + config.rope_scaling = { + "rope_type": "longrope", + "factor": 1.0, + "short_factor": short_factor, + "long_factor": long_factor, + } + inv_freq, _ = rope_fn(config=config, device=torch_device, seq_len=0) + torch.testing.assert_close(inv_freq, default_inv_freq / torch.tensor(short_factor).to(torch_device)) + + # Check 3: seq_len > max_position_embeddings -> long factor is applied to the default frequencies + inv_freq, _ = rope_fn(config=config, device=torch_device, seq_len=config.max_position_embeddings + 1) + torch.testing.assert_close(inv_freq, default_inv_freq / torch.tensor(long_factor).to(torch_device)) + + def test_llama3_rope_numerically(self): + # fmt: off + EXPECTED_INV_FREQ = torch.tensor( + [ + 1.0000e+00, 8.6596e-01, 7.4989e-01, 6.4938e-01, 5.6234e-01, 4.8697e-01, + 4.2170e-01, 3.6517e-01, 3.1623e-01, 2.7384e-01, 2.3714e-01, 2.0535e-01, + 1.7783e-01, 1.5399e-01, 1.3335e-01, 1.1548e-01, 1.0000e-01, 8.6596e-02, + 7.4989e-02, 6.4938e-02, 5.6234e-02, 4.8697e-02, 4.2170e-02, 3.6517e-02, + 3.1623e-02, 2.7384e-02, 2.3714e-02, 2.0535e-02, 1.7783e-02, 1.5399e-02, + 1.3335e-02, 1.0730e-02, 7.7785e-03, 5.6009e-03, 3.9991e-03, 2.8248e-03, + 1.9675e-03, 1.3449e-03, 8.9549e-04, 5.7363e-04, 3.4539e-04, 2.7384e-04, + 2.3714e-04, 2.0535e-04, 1.7783e-04, 1.5399e-04, 1.3335e-04, 1.1548e-04, + 1.0000e-04, 8.6596e-05, 7.4989e-05, 6.4938e-05, 5.6234e-05, 4.8697e-05, + 4.2170e-05, 3.6517e-05, 3.1623e-05, 2.7384e-05, 2.3714e-05, 2.0535e-05, + 1.7783e-05, 1.5399e-05, 1.3335e-05, 1.1548e-05 + ], device=torch_device + ) + # fmt: on + + # input sanity checks: if these change, the output will also change + config = LlamaConfig() + self.assertEqual(config.rope_scaling, None) + self.assertEqual(config.hidden_size, 4096) + self.assertEqual(config.num_attention_heads, 32) + self.assertEqual(config.rope_theta, 10000.0) + self.assertFalse(hasattr(config, "partial_rotary_factor")) + + rope_fn = ROPE_INIT_FUNCTIONS["default"] + default_inv_freq, _ = rope_fn(config=config, device=torch_device) + + # Check 1: `attention_factor` is always 1 + rope_fn = ROPE_INIT_FUNCTIONS["llama3"] + for factor in (2.0, 10.0, 20.0): + config.rope_scaling = { + "rope_type": "llama3", + "factor": factor, + "original_max_position_embeddings": 2048, + "low_freq_factor": 1, + "high_freq_factor": 4, + } + _, attention_scale = rope_fn(config=config, device=torch_device) + self.assertEqual(attention_scale, 1.0) + + # Check 2: based on `low_freq_factor` and `high_freq_factor`, the frequencies will be scaled between 1 and + # `factor` (similar to yarn). Low frequencies get scaled by `factor`, high frequencies see no change, medium + # frequencies are scaled by a value in between. Changing `low_freq_factor` and `high_freq_factor` changes what + # is considered low, medium, and high frequencies. + factor = 10.0 + config.rope_scaling = { + "rope_type": "llama3", + "factor": factor, + "original_max_position_embeddings": 2048, + "low_freq_factor": 1, + "high_freq_factor": 4, + } + inv_freq, _ = rope_fn(config=config, device=torch_device) + is_bounded_by_factor = [ + (default_inv_freq[idx] / factor) <= llama3_inv_freq_value <= default_inv_freq[idx] + for idx, llama3_inv_freq_value in enumerate(inv_freq) + ] + self.assertTrue(all(is_bounded_by_factor)) + + # if we change `high_freq_factor` to a very high value, none is considered high-frequency -> ALL values will be + # scaled + config.rope_scaling = config.rope_scaling = { + "rope_type": "llama3", + "factor": factor, + "original_max_position_embeddings": 2048, + "low_freq_factor": 1, + "high_freq_factor": 1000, + } + inv_freq, _ = rope_fn(config=config, device=torch_device) + is_scaled = [yarn_inv_freq_value < default_inv_freq[idx] for idx, yarn_inv_freq_value in enumerate(inv_freq)] + self.assertTrue(all(is_scaled)) + + # Check 3: numerical snapshot to avoid regressions + config.rope_scaling = { + "rope_type": "llama3", + "factor": factor, + "original_max_position_embeddings": 2048, + "low_freq_factor": 1, + "high_freq_factor": 4, + } + inv_freq, _ = rope_fn(config=config, device=torch_device) + torch.testing.assert_close(inv_freq, EXPECTED_INV_FREQ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_modeling_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_modeling_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..a7837d5d2336d3a750444e4c3e835c5084c215c3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_modeling_utils.py @@ -0,0 +1,2889 @@ +# Copyright 2019 HuggingFace 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. +import copy +import glob +import json +import os +import os.path +import subprocess +import sys +import tempfile +import textwrap +import threading +import unittest +import unittest.mock as mock +import uuid +import warnings +from pathlib import Path + +import pytest +import requests +from huggingface_hub import HfApi, HfFolder +from parameterized import parameterized +from pytest import mark +from requests.exceptions import HTTPError + +from transformers import ( + AutoConfig, + AutoModel, + AutoModelForImageClassification, + AutoModelForSequenceClassification, + CLIPTextModelWithProjection, + DynamicCache, + LlavaForConditionalGeneration, + MistralForCausalLM, + OwlViTForObjectDetection, + PretrainedConfig, + is_torch_available, + logging, +) +from transformers.modeling_flash_attention_utils import is_flash_attn_available +from transformers.testing_utils import ( + TOKEN, + CaptureLogger, + LoggingLevel, + TemporaryHubRepo, + TestCasePlus, + hub_retry, + is_staging_test, + require_accelerate, + require_non_hpu, + require_read_token, + require_safetensors, + require_torch, + require_torch_accelerator, + require_torch_multi_accelerator, + slow, + torch_device, +) +from transformers.utils import ( + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + check_torch_load_is_safe, +) +from transformers.utils.import_utils import ( + is_flash_attn_2_available, + is_flash_attn_3_available, + is_torch_npu_available, + is_torch_sdpa_available, +) + + +sys.path.append(str(Path(__file__).parent.parent.parent / "utils")) + +from test_module.custom_configuration import CustomConfig + + +if is_torch_available(): + import torch + from safetensors.torch import save_file as safe_save_file + from test_module.custom_modeling import CustomModel + from torch import nn + + from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + BertConfig, + BertModel, + CLIPTextModel, + GenerationMixin, + PreTrainedModel, + T5Config, + T5ForConditionalGeneration, + ) + from transformers.modeling_attn_mask_utils import ( + AttentionMaskConverter, + _create_4d_causal_attention_mask, + _prepare_4d_attention_mask, + _prepare_4d_causal_attention_mask, + ) + from transformers.modeling_utils import ( + _find_disjoint, + _find_identical, + ) + from transformers.pytorch_utils import isin_mps_friendly + + # Fake pretrained models for tests + class BaseModel(PreTrainedModel): + base_model_prefix = "base" + config_class = PretrainedConfig + + def __init__(self, config): + super().__init__(config) + self.linear = nn.Linear(5, 5) + self.linear_2 = nn.Linear(5, 5) + + def forward(self, x): + return self.linear_2(self.linear(x)) + + class BaseModelWithTiedWeights(PreTrainedModel): + config_class = PretrainedConfig + + def __init__(self, config): + super().__init__(config) + self.linear = nn.Linear(5, 5) + self.linear_2 = nn.Linear(5, 5) + + def forward(self, x): + return self.linear_2(self.linear(x)) + + def tie_weights(self): + self.linear_2.weight = self.linear.weight + + class ModelWithHead(PreTrainedModel): + base_model_prefix = "base" + config_class = PretrainedConfig + + def _init_weights(self, module): + pass + + def __init__(self, config): + super().__init__(config) + self.base = BaseModel(config) + # linear is a common name between Base and Head on purpose. + self.linear = nn.Linear(5, 5) + self.linear2 = nn.Linear(5, 5) + + def forward(self, x): + return self.linear2(self.linear(self.base(x))) + + class ModelWithDirectParam(PreTrainedModel): + base_model_prefix = "base" + config_class = PretrainedConfig + + def _init_weights(self, module): + pass + + def __init__(self, config): + super().__init__(config) + # direct params and submodules is helpful for testing offloading logic + self.weight = nn.Parameter(torch.rand((5, 5))) + self.base = BaseModel(config) + + def forward(self, x): + return self.base(x @ self.weight.T) + + class ModelWithDirectParamSubmodule(PreTrainedModel): + base_model_prefix = "base" + config_class = PretrainedConfig + + def _init_weights(self, module): + pass + + def __init__(self, config): + super().__init__(config) + self.submodule = ModelWithDirectParam(config) + # needed so model can have at least one module on accelerator + self.linear = nn.Linear(5, 5) + + def forward(self, x): + return self.linear(self.submodule(x)) + + class ModelWithHeadAndTiedWeights(PreTrainedModel): + base_model_prefix = "base" + config_class = PretrainedConfig + + def _init_weights(self, module): + pass + + def __init__(self, config): + super().__init__(config) + self.base = BaseModel(config) + self.decoder = nn.Linear(5, 5) + + def forward(self, x): + return self.decoder(self.base(x)) + + def tie_weights(self): + self.decoder.weight = self.base.linear.weight + + class Prepare4dCausalAttentionMaskModel(nn.Module): + def forward(self, inputs_embeds): + batch_size, seq_length, _ = inputs_embeds.shape + past_key_values_length = 4 + attention_mask = _prepare_4d_causal_attention_mask( + None, (batch_size, seq_length), inputs_embeds, past_key_values_length + ) + return attention_mask + + class Create4dCausalAttentionMaskModel(nn.Module): + def forward(self, inputs_embeds): + batch_size, seq_length, _ = inputs_embeds.shape + past_key_values_length = 4 + attention_mask = _create_4d_causal_attention_mask( + (batch_size, seq_length), + dtype=inputs_embeds.dtype, + device=inputs_embeds.device, + past_key_values_length=past_key_values_length, + ) + return attention_mask + + class Prepare4dAttentionMaskModel(nn.Module): + def forward(self, mask, inputs_embeds): + attention_mask = _prepare_4d_attention_mask(mask, dtype=inputs_embeds.dtype) + return attention_mask + + class TestOffline(unittest.TestCase): + def test_offline(self): + # Ugly setup with monkeypatches, amending env vars here is too late as libs have already been imported + from huggingface_hub import constants + + from transformers.utils import hub + + offlfine_env = hub._is_offline_mode + hub_cache_env = constants.HF_HUB_CACHE + hub_cache_env1 = constants.HUGGINGFACE_HUB_CACHE + default_cache = constants.default_cache_path + transformers_cache = hub.TRANSFORMERS_CACHE + + try: + hub._is_offline_mode = True + with tempfile.TemporaryDirectory() as tmpdir: + LOG.info("Temporary cache dir %s", tmpdir) + constants.HF_HUB_CACHE = tmpdir + constants.HUGGINGFACE_HUB_CACHE = tmpdir + constants.default_cache_path = tmpdir + hub.TRANSFORMERS_CACHE = tmpdir + # First offline load should fail + try: + AutoModelForImageClassification.from_pretrained( + TINY_IMAGE_CLASSIF, revision="main", use_auth_token=None + ) + except OSError: + LOG.info("Loading model %s in offline mode failed as expected", TINY_IMAGE_CLASSIF) + else: + self.fail(f"Loading model {TINY_IMAGE_CLASSIF} in offline mode should fail") + + # Download model -> Huggingface Hub not concerned by our offline mode + LOG.info("Downloading %s for offline tests", TINY_IMAGE_CLASSIF) + hub_api = HfApi() + local_dir = hub_api.snapshot_download(TINY_IMAGE_CLASSIF, cache_dir=tmpdir) + + LOG.info("Model %s downloaded in %s", TINY_IMAGE_CLASSIF, local_dir) + + AutoModelForImageClassification.from_pretrained( + TINY_IMAGE_CLASSIF, revision="main", use_auth_token=None + ) + finally: + # Tear down: reset env as it was before calling this test + hub._is_offline_mode = offlfine_env + constants.HF_HUB_CACHE = hub_cache_env + constants.HUGGINGFACE_HUB_CACHE = hub_cache_env1 + constants.default_cache_path = default_cache + hub.TRANSFORMERS_CACHE = transformers_cache + + def test_local_files_only(self): + # Ugly setup with monkeypatches, amending env vars here is too late as libs have already been imported + from huggingface_hub import constants + + from transformers.utils import hub + + hub_cache_env = constants.HF_HUB_CACHE + hub_cache_env1 = constants.HUGGINGFACE_HUB_CACHE + default_cache = constants.default_cache_path + transformers_cache = hub.TRANSFORMERS_CACHE + try: + with tempfile.TemporaryDirectory() as tmpdir: + LOG.info("Temporary cache dir %s", tmpdir) + constants.HF_HUB_CACHE = tmpdir + constants.HUGGINGFACE_HUB_CACHE = tmpdir + constants.default_cache_path = tmpdir + hub.TRANSFORMERS_CACHE = tmpdir + try: + AutoModelForImageClassification.from_pretrained( + TINY_IMAGE_CLASSIF, revision="main", use_auth_token=None, local_files_only=True + ) + except OSError: + LOG.info("Loading model %s in offline mode failed as expected", TINY_IMAGE_CLASSIF) + else: + self.fail(f"Loading model {TINY_IMAGE_CLASSIF} in offline mode should fail") + + LOG.info("Downloading %s for offline tests", TINY_IMAGE_CLASSIF) + hub_api = HfApi() + local_dir = hub_api.snapshot_download(TINY_IMAGE_CLASSIF, cache_dir=tmpdir) + + LOG.info("Model %s downloaded in %s", TINY_IMAGE_CLASSIF, local_dir) + + AutoModelForImageClassification.from_pretrained( + TINY_IMAGE_CLASSIF, revision="main", use_auth_token=None, local_files_only=True + ) + finally: + # Tear down: reset env as it was before calling this test + constants.HF_HUB_CACHE = hub_cache_env + constants.HUGGINGFACE_HUB_CACHE = hub_cache_env1 + constants.default_cache_path = default_cache + hub.TRANSFORMERS_CACHE = transformers_cache + + +# Need to be serializable, which means they cannot be in a test class method +class TestGammaBetaNorm(torch.nn.Module): + def __init__(self): + super().__init__() + self.gamma = torch.nn.Parameter(torch.ones(1)) + self.beta = torch.nn.Parameter(torch.zeros(1)) + + def forward(self): + return self.gamma.sum() + self.beta.sum() + + +class TestModelGammaBeta(PreTrainedModel): + def __init__(self, config): + super().__init__(config) + self.LayerNorm = TestGammaBetaNorm() + self.post_init() + + def forward(self): + return self.LayerNorm() + + +TINY_T5 = "patrickvonplaten/t5-tiny-random" +TINY_BERT_FOR_TOKEN_CLASSIFICATION = "hf-internal-testing/tiny-bert-for-token-classification" +TINY_MISTRAL = "hf-internal-testing/tiny-random-MistralForCausalLM" +TINY_IMAGE_CLASSIF = "hf-internal-testing/tiny-random-SiglipForImageClassification" +TINY_LLAVA = "hf-internal-testing/tiny-random-LlavaForConditionalGeneration" + +LOG = logging.get_logger(__name__) + + +def check_models_equal(model1, model2): + models_are_equal = True + for model1_p, model2_p in zip(model1.parameters(), model2.parameters()): + if model1_p.data.ne(model2_p.data).sum() > 0: + models_are_equal = False + + return models_are_equal + + +@require_torch +class ModelUtilsTest(TestCasePlus): + def setUp(self): + self.old_dtype = torch.get_default_dtype() + super().setUp() + + def tearDown(self): + torch.set_default_dtype(self.old_dtype) + super().tearDown() + + def test_hub_retry(self): + @hub_retry(max_attempts=2) + def test_func(): + # First attempt will fail with a connection error + if not hasattr(test_func, "attempt"): + test_func.attempt = 1 + raise requests.exceptions.ConnectionError("Connection failed") + # Second attempt will succeed + return True + + self.assertTrue(test_func()) + + @slow + def test_model_from_pretrained(self): + model_name = "google-bert/bert-base-uncased" + config = BertConfig.from_pretrained(model_name) + self.assertIsNotNone(config) + self.assertIsInstance(config, PretrainedConfig) + + model = BertModel.from_pretrained(model_name) + model, loading_info = BertModel.from_pretrained(model_name, output_loading_info=True) + self.assertIsNotNone(model) + self.assertIsInstance(model, PreTrainedModel) + + self.assertEqual(len(loading_info["missing_keys"]), 0) + self.assertEqual(len(loading_info["unexpected_keys"]), 8) + self.assertEqual(len(loading_info["mismatched_keys"]), 0) + self.assertEqual(len(loading_info["error_msgs"]), 0) + + config = BertConfig.from_pretrained(model_name, output_attentions=True, output_hidden_states=True) + + # Not sure this is the intended behavior. TODO fix Lysandre & Thom + config.name_or_path = model_name + + model = BertModel.from_pretrained(model_name, output_attentions=True, output_hidden_states=True) + self.assertEqual(model.config.output_hidden_states, True) + self.assertEqual(model.config, config) + + def test_model_from_pretrained_subfolder(self): + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + model = BertModel(config) + + subfolder = "bert" + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(os.path.join(tmp_dir, subfolder)) + + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(tmp_dir) + + model_loaded = BertModel.from_pretrained(tmp_dir, subfolder=subfolder) + + self.assertTrue(check_models_equal(model, model_loaded)) + + def test_model_manually_shared_disjointed_tensors_optimum(self): + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + model = BertModel(config) + + # Let's fuse qkv + attn = model.encoder.layer[0].attention.self + q = attn.query.weight + k = attn.key.weight + v = attn.value.weight + # Force some shared storage + qkv = torch.stack([q, k, v], dim=0) + attn.query.weight = torch.nn.Parameter(qkv[0]) + attn.key.weight = torch.nn.Parameter(qkv[1]) + attn.value.weight = torch.nn.Parameter(qkv[2]) + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + model_loaded = BertModel.from_pretrained(tmp_dir) + + self.assertTrue(check_models_equal(model, model_loaded)) + + def test_model_from_pretrained_subfolder_sharded(self): + config = BertConfig.from_pretrained("hf-internal-testing/tiny-random-bert") + model = BertModel(config) + + subfolder = "bert" + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(os.path.join(tmp_dir, subfolder), max_shard_size="10KB") + + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(tmp_dir) + + model_loaded = BertModel.from_pretrained(tmp_dir, subfolder=subfolder) + + self.assertTrue(check_models_equal(model, model_loaded)) + + def test_model_from_pretrained_hub_subfolder(self): + subfolder = "bert" + model_id = "hf-internal-testing/tiny-random-bert-subfolder" + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(model_id) + + model = BertModel.from_pretrained(model_id, subfolder=subfolder) + + self.assertIsNotNone(model) + + def test_model_from_pretrained_hub_subfolder_sharded(self): + subfolder = "bert" + model_id = "hf-internal-testing/tiny-random-bert-sharded-subfolder" + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(model_id) + + model = BertModel.from_pretrained(model_id, subfolder=subfolder) + + self.assertIsNotNone(model) + + def test_model_from_pretrained_with_different_pretrained_model_name(self): + model = T5ForConditionalGeneration.from_pretrained(TINY_T5) + self.assertIsNotNone(model) + + logger = logging.get_logger("transformers.configuration_utils") + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + BertModel.from_pretrained(TINY_T5) + self.assertTrue("You are using a model of type t5 to instantiate a model of type bert" in cl.out) + + @require_accelerate + def test_model_from_pretrained_with_none_quantization_config(self): + # Needs a device_map for to enter the low_cpu_mem branch. We also load AutoModelForSequenceClassification + # deliberately to enter the missing keys branch. + model = AutoModelForSequenceClassification.from_pretrained( + TINY_MISTRAL, device_map="auto", quantization_config=None + ) + self.assertIsNotNone(model) + + def test_model_from_config_torch_dtype(self): + # test that the model can be instantiated with dtype of user's choice - as long as it's a + # float dtype. To make it happen config.torch_dtype needs to be set before instantiating the + # model from the config object. + + config = T5Config.from_pretrained(TINY_T5) + model = AutoModel.from_config(config) + # XXX: isn't supported + # model = T5ForConditionalGeneration.from_config(config) + self.assertEqual(model.dtype, torch.float32) + + model = AutoModel.from_config(config, torch_dtype=torch.float16) + self.assertEqual(model.dtype, torch.float16) + + # torch.set_default_dtype() supports only float dtypes, so will fail with non-float type + with self.assertRaises(ValueError): + model = AutoModel.from_config(config, torch_dtype=torch.int64) + + def test_model_from_config_torch_dtype_str(self): + # test that from_pretrained works with torch_dtype being strings like "float32" for PyTorch backend + model = AutoModel.from_pretrained(TINY_T5, torch_dtype="float32") + self.assertEqual(model.dtype, torch.float32) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + model = AutoModel.from_pretrained(TINY_T5, torch_dtype="float16") + self.assertEqual(model.dtype, torch.float16) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + # torch.set_default_dtype() supports only float dtypes, so will fail with non-float type + with self.assertRaises(ValueError): + model = AutoModel.from_pretrained(TINY_T5, torch_dtype="int64") + + def test_model_from_config_torch_dtype_composite(self): + """ + Test that from_pretrained works with torch_dtype being as a dict per each sub-config in composite config + Tiny-Llava has saved auto dtype as `torch.float32` for all modules. + """ + # Load without dtype specified + model = LlavaForConditionalGeneration.from_pretrained(TINY_LLAVA) + self.assertEqual(model.language_model.dtype, torch.float32) + self.assertEqual(model.vision_tower.dtype, torch.float32) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + # should be able to set torch_dtype as a simple string and the model loads it correctly + model = LlavaForConditionalGeneration.from_pretrained(TINY_LLAVA, torch_dtype="float32") + self.assertEqual(model.language_model.dtype, torch.float32) + self.assertEqual(model.vision_tower.dtype, torch.float32) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + model = LlavaForConditionalGeneration.from_pretrained(TINY_LLAVA, torch_dtype=torch.float16) + self.assertEqual(model.language_model.dtype, torch.float16) + self.assertEqual(model.vision_tower.dtype, torch.float16) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + # should be able to set torch_dtype as a dict for each sub-config + model = LlavaForConditionalGeneration.from_pretrained( + TINY_LLAVA, torch_dtype={"text_config": "float32", "vision_config": "float16", "": "bfloat16"} + ) + self.assertEqual(model.language_model.dtype, torch.float32) + self.assertEqual(model.vision_tower.dtype, torch.float16) + self.assertEqual(model.multi_modal_projector.linear_1.weight.dtype, torch.bfloat16) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + # should be able to set the values as torch.dtype (not str) + model = LlavaForConditionalGeneration.from_pretrained( + TINY_LLAVA, torch_dtype={"text_config": torch.float32, "vision_config": torch.float16, "": torch.bfloat16} + ) + self.assertEqual(model.language_model.dtype, torch.float32) + self.assertEqual(model.vision_tower.dtype, torch.float16) + self.assertEqual(model.multi_modal_projector.linear_1.weight.dtype, torch.bfloat16) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + # should be able to set the values in configs directly and pass it to `from_pretrained` + config = copy.deepcopy(model.config) + config.text_config.torch_dtype = torch.float32 + config.vision_config.torch_dtype = torch.bfloat16 + config.torch_dtype = torch.float16 + model = LlavaForConditionalGeneration.from_pretrained(TINY_LLAVA, config=config, torch_dtype="auto") + self.assertEqual(model.language_model.dtype, torch.float32) + self.assertEqual(model.vision_tower.dtype, torch.bfloat16) + self.assertEqual(model.multi_modal_projector.linear_1.weight.dtype, torch.float16) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + # but if the model has `_keep_in_fp32_modules` then those modules should be in fp32 no matter what + LlavaForConditionalGeneration._keep_in_fp32_modules = ["multi_modal_projector"] + model = LlavaForConditionalGeneration.from_pretrained(TINY_LLAVA, config=config, torch_dtype="auto") + self.assertEqual(model.language_model.dtype, torch.float32) + self.assertEqual(model.vision_tower.dtype, torch.bfloat16) + self.assertEqual(model.multi_modal_projector.linear_1.weight.dtype, torch.float32) + self.assertIsInstance(model.config.torch_dtype, torch.dtype) + + # torch.set_default_dtype() supports only float dtypes, so will fail with non-float type + with self.assertRaises(ValueError): + model = LlavaForConditionalGeneration.from_pretrained(TINY_LLAVA, torch_dtype="int64") + model = LlavaForConditionalGeneration.from_pretrained( + TINY_LLAVA, torch_dtype={"text_config": "float32", "vision_config": "int64", "": "float16"} + ) + + def test_model_from_pretrained_torch_dtype(self): + # test that the model can be instantiated with dtype of either + # 1. explicit from_pretrained's torch_dtype argument + # 2. via autodiscovery by looking at model weights (torch_dtype="auto") + # so if a model.half() was saved, we want it to be instantiated as such. + # + # test an explicit model class, but also AutoModel separately as the latter goes through a different code path + model_path = self.get_auto_remove_tmp_dir() + + # baseline - we know TINY_T5 is fp32 model + model = T5ForConditionalGeneration.from_pretrained(TINY_T5) + self.assertEqual(model.dtype, torch.float32) + + def remove_torch_dtype(model_path): + file = f"{model_path}/config.json" + with open(file, encoding="utf-8") as f: + s = json.load(f) + s.pop("torch_dtype") + with open(file, "w", encoding="utf-8") as f: + json.dump(s, f) + + # test the default fp32 save_pretrained => from_pretrained cycle + model.save_pretrained(model_path) + model = T5ForConditionalGeneration.from_pretrained(model_path) + self.assertEqual(model.dtype, torch.float32) + # 1. test torch_dtype="auto" via `config.torch_dtype` + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float32) + # 2. test torch_dtype="auto" via auto-derivation + # now remove the torch_dtype entry from config.json and try "auto" again which should + # perform auto-derivation from weights + remove_torch_dtype(model_path) + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float32) + + # test forced loading in fp16 (even though the weights are in fp32) + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype=torch.float16) + self.assertEqual(model.dtype, torch.float16) + + # test fp16 save_pretrained, loaded with auto-detection + model = model.half() + model.save_pretrained(model_path) + # 1. test torch_dtype="auto" via `config.torch_dtype` + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.config.torch_dtype, torch.float16) + self.assertEqual(model.dtype, torch.float16) + # tests `config.torch_dtype` saving + with open(f"{model_path}/config.json") as f: + config_dict = json.load(f) + self.assertEqual(config_dict["torch_dtype"], "float16") + # 2. test torch_dtype="auto" via auto-derivation + # now same with using config info + remove_torch_dtype(model_path) + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float16) + + # 3. now retest that AutoModel behaves the same wrt torch_dtype="auto" as T5ForConditionalGeneration + model = AutoModel.from_pretrained(model_path, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float16) + + # test fp16 save_pretrained, loaded with the explicit fp16 + model = T5ForConditionalGeneration.from_pretrained(model_path, torch_dtype=torch.float16) + self.assertEqual(model.dtype, torch.float16) + + # test AutoModel separately as it goes through a different path + # test auto-detection - as currently TINY_T5 doesn't have torch_dtype entry + model = AutoModel.from_pretrained(TINY_T5, torch_dtype="auto") + # test that the config object didn't get polluted with torch_dtype="auto" + # there was a bug that after this call we ended up with config.torch_dtype=="auto" + self.assertNotEqual(model.config.torch_dtype, "auto") + # now test the outcome + self.assertEqual(model.dtype, torch.float32) + model = AutoModel.from_pretrained(TINY_T5, torch_dtype=torch.float16) + self.assertEqual(model.dtype, torch.float16) + + # test model whose first param is not of a floating type, but int + model = AutoModel.from_pretrained(TINY_BERT_FOR_TOKEN_CLASSIFICATION, torch_dtype="auto") + self.assertEqual(model.dtype, torch.float32) + + # test model that init the model with _from_config + model = CLIPTextModelWithProjection.from_pretrained( + "hf-internal-testing/diffusers-stable-diffusion-tiny-all", + subfolder="text_encoder", + torch_dtype=torch.bfloat16, + ) + self.assertEqual(model.dtype, torch.bfloat16) + + def test_model_from_pretrained_attn_implementation(self): + # test that the model can be instantiated with attn_implementation of either + # 1. explicit from_pretrained's attn_implementation argument + # 2. explicit from_pretrained's attn_implementation argument with a config argument + attn_implementation_available = ["eager"] + if is_torch_sdpa_available(): + attn_implementation_available.append("sdpa") + + if is_flash_attn_available(): + attn_implementation_available.append("flash_attention_2") + + if is_flash_attn_3_available(): + attn_implementation_available.append("flash_attention_3") + + for requested_attn_implementation in attn_implementation_available: + model = AutoModelForCausalLM.from_pretrained( + TINY_MISTRAL, attn_implementation=requested_attn_implementation + ) + self.assertEqual(model.config._attn_implementation, requested_attn_implementation) + + config = AutoConfig.from_pretrained(TINY_MISTRAL) + model = AutoModelForCausalLM.from_pretrained( + TINY_MISTRAL, config=config, attn_implementation=requested_attn_implementation + ) + self.assertEqual(model.config._attn_implementation, requested_attn_implementation) + + def test_model_from_config_attn_implementation(self): + # test that the model can be instantiated with attn_implementation of either + # 1. config created with explicit attn_implementatation and from_config + # 2. explicit from_config's attn_implementation argument with a config argument + # 3. config created with explicit attn_implementatation and from_config overriding with explicit attn_implementation argument + attn_implementation_available = ["eager"] + if is_torch_sdpa_available(): + attn_implementation_available.append("sdpa") + + if is_flash_attn_available(): + attn_implementation_available.append("flash_attention_2") + + if is_flash_attn_3_available(): + attn_implementation_available.append("flash_attention_3") + + for requested_attn_implementation in attn_implementation_available: + config = AutoConfig.from_pretrained(TINY_MISTRAL, attn_implementation=requested_attn_implementation) + # Ensure the config was set correctly + self.assertEqual(config._attn_implementation, requested_attn_implementation) + model = AutoModelForCausalLM.from_config(config) + self.assertEqual(model.config._attn_implementation, requested_attn_implementation) + + config = AutoConfig.from_pretrained(TINY_MISTRAL) + # When the config is not set, the default is "eager" + self.assertEqual(config._attn_implementation, None) + model = AutoModelForCausalLM.from_config(config=config, attn_implementation=requested_attn_implementation) + self.assertEqual(model.config._attn_implementation, requested_attn_implementation) + + # Set a nonsense attn_implementation in the config, which should be overridden by the explicit argument + config = AutoConfig.from_pretrained(TINY_MISTRAL, attn_implementation="foo-bar-baz") + self.assertEqual(config._attn_implementation, "foo-bar-baz") + model = AutoModelForCausalLM.from_config(config=config, attn_implementation=requested_attn_implementation) + self.assertEqual(model.config._attn_implementation, requested_attn_implementation) + + def test_checkpoint_sharding_local_bin(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + # We use the same folder for various sizes to make sure a new save erases the old checkpoint. + for max_size in ["50kB", "100kB", "200kB"]: + model.save_pretrained(tmp_dir, max_shard_size=max_size, safe_serialization=False) + + # Get each shard file and its size + shard_to_size = {} + for shard in os.listdir(tmp_dir): + if shard.endswith(".bin"): + shard_file = os.path.join(tmp_dir, shard) + shard_to_size[shard_file] = os.path.getsize(shard_file) + + index_file = os.path.join(tmp_dir, WEIGHTS_INDEX_NAME) + # Check there is an index but no regular weight file + self.assertTrue(os.path.isfile(index_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + + # Check a file is bigger than max_size only when it has a single weight + for shard_file, size in shard_to_size.items(): + max_size_int = int(max_size[:-2]) * 10**3 + # Note: pickle adds some junk so the weight of the file can end up being slightly bigger than + # the size asked for (since we count parameters) + if size >= max_size_int + 50000: + check_torch_load_is_safe() + state_dict = torch.load(shard_file, weights_only=True) + self.assertEqual(len(state_dict), 1) + + # Check the index and the shard files found match + with open(index_file, encoding="utf-8") as f: + index = json.loads(f.read()) + + all_shards = set(index["weight_map"].values()) + shards_found = {f for f in os.listdir(tmp_dir) if f.endswith(".bin")} + self.assertSetEqual(all_shards, shards_found) + + # Finally, check the model can be reloaded + new_model = BertModel.from_pretrained(tmp_dir) + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + def test_checkpoint_sharding_from_hub(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded") + # the model above is the same as the model below, just a sharded version. + ref_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + for p1, p2 in zip(model.parameters(), ref_model.parameters()): + torch.testing.assert_close(p1, p2) + + def test_checkpoint_variant_local_bin(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, variant="v2", safe_serialization=False) + + weights_name = ".".join(WEIGHTS_NAME.split(".")[:-1] + ["v2"] + ["bin"]) + + weights_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained(tmp_dir) + + new_model = BertModel.from_pretrained(tmp_dir, variant="v2") + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + def test_checkpoint_variant_local_sharded_bin(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, variant="v2", max_shard_size="50kB", safe_serialization=False) + + weights_index_name = ".".join(WEIGHTS_INDEX_NAME.split(".")[:-1] + ["v2"] + ["json"]) + weights_index_file = os.path.join(tmp_dir, weights_index_name) + self.assertTrue(os.path.isfile(weights_index_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_INDEX_NAME))) + + for i in range(1, 5): + weights_name = ".".join(WEIGHTS_NAME.split(".")[:-1] + [f"v2-0000{i}-of-00005"] + ["bin"]) + weights_name_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_name_file)) + + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained(tmp_dir) + + new_model = BertModel.from_pretrained(tmp_dir, variant="v2") + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + @require_safetensors + def test_checkpoint_variant_local_safe(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, variant="v2", safe_serialization=True) + + weights_name = ".".join(SAFE_WEIGHTS_NAME.split(".")[:-1] + ["v2"] + ["safetensors"]) + + weights_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained(tmp_dir) + + new_model = BertModel.from_pretrained(tmp_dir, variant="v2") + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + @require_safetensors + def test_checkpoint_variant_local_sharded_safe(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, variant="v2", max_shard_size="50kB", safe_serialization=True) + + weights_index_name = ".".join(SAFE_WEIGHTS_INDEX_NAME.split(".")[:-1] + ["v2"] + ["json"]) + weights_index_file = os.path.join(tmp_dir, weights_index_name) + self.assertTrue(os.path.isfile(weights_index_file)) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_INDEX_NAME))) + + for i in range(1, 5): + weights_name = ".".join(SAFE_WEIGHTS_NAME.split(".")[:-1] + [f"v2-0000{i}-of-00005"] + ["safetensors"]) + weights_name_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_name_file)) + + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained(tmp_dir) + + new_model = BertModel.from_pretrained(tmp_dir, variant="v2") + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + def test_checkpoint_loading_only_safetensors_available(self): + # Test that the loading behaviour is as expected when only safetensor checkpoints are available + # - We can load the model with use_safetensors=True + # - We can load the model without specifying use_safetensors i.e. we search for the available checkpoint, + # preferring safetensors + # - We cannot load the model with use_safetensors=False + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, max_shard_size="50kB", safe_serialization=True) + + weights_index_name = ".".join(SAFE_WEIGHTS_INDEX_NAME.split(".")[:-1] + ["json"]) + weights_index_file = os.path.join(tmp_dir, weights_index_name) + self.assertTrue(os.path.isfile(weights_index_file)) + + for i in range(1, 5): + weights_name = f"model-0000{i}-of-00005" + ".safetensors" + weights_name_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_name_file)) + + # Setting use_safetensors=False should raise an error as the checkpoint was saved with safetensors=True + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(tmp_dir, use_safetensors=False) + + # We can load the model with use_safetensors=True + new_model = BertModel.from_pretrained(tmp_dir, use_safetensors=True) + + # We can load the model without specifying use_safetensors + new_model = BertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + def test_checkpoint_loading_only_pytorch_bin_available(self): + # Test that the loading behaviour is as expected when only pytorch checkpoints are available + # - We can load the model with use_safetensors=False + # - We can load the model without specifying use_safetensors i.e. we search for the available checkpoint, + # preferring safetensors but falling back to pytorch + # - We cannot load the model with use_safetensors=True + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, max_shard_size="50kB", safe_serialization=False) + + weights_index_name = ".".join(WEIGHTS_INDEX_NAME.split(".")[:-1] + ["json"]) + weights_index_file = os.path.join(tmp_dir, weights_index_name) + self.assertTrue(os.path.isfile(weights_index_file)) + + for i in range(1, 5): + weights_name = WEIGHTS_NAME.split(".")[0].split("_")[0] + f"_model-0000{i}-of-00005" + ".bin" + weights_name_file = os.path.join(tmp_dir, weights_name) + self.assertTrue(os.path.isfile(weights_name_file)) + + # Setting use_safetensors=True should raise an error as the checkpoint was saved with safetensors=False + with self.assertRaises(OSError): + _ = BertModel.from_pretrained(tmp_dir, use_safetensors=True) + + # We can load the model with use_safetensors=False + new_model = BertModel.from_pretrained(tmp_dir, use_safetensors=False) + + # We can load the model without specifying use_safetensors + new_model = BertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + def test_checkpoint_variant_hub(self): + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-variant", cache_dir=tmp_dir) + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant", cache_dir=tmp_dir, variant="v2" + ) + self.assertIsNotNone(model) + + def test_checkpoint_variant_hub_sharded(self): + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-sharded", cache_dir=tmp_dir + ) + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-sharded", cache_dir=tmp_dir, variant="v2" + ) + self.assertIsNotNone(model) + + @require_safetensors + def test_checkpoint_variant_hub_safe(self): + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-variant-safe", cache_dir=tmp_dir) + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-safe", cache_dir=tmp_dir, variant="v2" + ) + self.assertIsNotNone(model) + + @require_safetensors + def test_checkpoint_variant_hub_sharded_safe(self): + with tempfile.TemporaryDirectory() as tmp_dir: + with self.assertRaises(EnvironmentError): + _ = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-sharded-safe", cache_dir=tmp_dir + ) + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant-sharded-safe", cache_dir=tmp_dir, variant="v2" + ) + self.assertIsNotNone(model) + + def test_checkpoint_variant_save_load_bin(self): + with tempfile.TemporaryDirectory() as tmp_dir: + model = BertModel.from_pretrained( + "hf-internal-testing/tiny-random-bert-variant", cache_dir=tmp_dir, variant="v2" + ) + weights_name = ".".join(WEIGHTS_NAME.split(".")[:-1] + ["v2"] + ["bin"]) + + model.save_pretrained(tmp_dir, variant="v2", safe_serialization=False) + # saving will create a variant checkpoint + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, weights_name))) + + model.save_pretrained(tmp_dir, safe_serialization=False) + # saving shouldn't delete variant checkpoints + weights_name = ".".join(WEIGHTS_NAME.split(".")[:-1] + ["v2"] + ["bin"]) + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, weights_name))) + + # there should be a normal checkpoint + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + + self.assertIsNotNone(model) + + @require_non_hpu + @require_accelerate + @mark.accelerate_tests + @require_torch_multi_accelerator + @slow + def test_model_parallelism_gpt2(self): + device_map = {"transformer.wte": 0, "transformer.wpe": 0, "lm_head": 0, "transformer.ln_f": 1} + for i in range(12): + device_map[f"transformer.h.{i}"] = 0 if i <= 5 else 1 + + model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2", device_map=device_map) + + tokenizer = AutoTokenizer.from_pretrained("openai-community/gpt2") + inputs = tokenizer("Hello, my name is", return_tensors="pt") + output = model.generate(inputs["input_ids"].to(f"{torch_device}:0")) + + text_output = tokenizer.decode(output[0].tolist()) + self.assertEqual(text_output, "Hello, my name is John. I'm a writer, and I'm a writer. I'm") + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_from_pretrained_disk_offload_task_model(self): + model = AutoModel.from_pretrained("hf-internal-testing/tiny-random-gpt2") + device_map = { + "transformer.wte": f"{torch_device}:0", + "transformer.wpe": f"{torch_device}:0", + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": "cpu", + "transformer.h.3": "disk", + "transformer.h.4": "disk", + "transformer.ln_f": f"{torch_device}:0", + "lm_head": f"{torch_device}:0", + } + with tempfile.TemporaryDirectory() as tmp_dir: + inputs = torch.tensor([[1, 2, 3]]).to(f"{torch_device}:0") + + model.save_pretrained(tmp_dir) + new_model = AutoModelForCausalLM.from_pretrained(tmp_dir).to(f"{torch_device}:0") + outputs1 = new_model.to(f"{torch_device}:0")(inputs) + + offload_folder = os.path.join(tmp_dir, "offload") + new_model_with_offload = AutoModelForCausalLM.from_pretrained( + tmp_dir, device_map=device_map, offload_folder=offload_folder + ) + outputs2 = new_model_with_offload(inputs) + + torch.testing.assert_close(outputs1.logits.cpu(), outputs2.logits.cpu()) + + # With state dict temp offload + new_model_with_offload = AutoModelForCausalLM.from_pretrained( + tmp_dir, + device_map=device_map, + offload_folder=offload_folder, + offload_state_dict=True, + ) + outputs2 = new_model_with_offload(inputs) + torch.testing.assert_close(outputs1.logits.cpu(), outputs2.logits.cpu()) + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_from_pretrained_disk_offload_derived_to_base_model(self): + derived_model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-gpt2") + + device_map = { + "wte": f"{torch_device}:0", + "wpe": f"{torch_device}:0", + "h.0": "cpu", + "h.1": "cpu", + "h.2": "cpu", + "h.3": "disk", + "h.4": "disk", + "ln_f": f"{torch_device}:0", + } + with tempfile.TemporaryDirectory() as tmp_dir: + inputs = torch.tensor([[1, 2, 3]]).to(f"{torch_device}:0") + derived_model.save_pretrained(tmp_dir, use_safetensors=True) + base_model = AutoModel.from_pretrained(tmp_dir) + outputs1 = base_model.to(f"{torch_device}:0")(inputs) + + # with disk offload + offload_folder = os.path.join(tmp_dir, "offload") + base_model_with_offload = AutoModel.from_pretrained( + tmp_dir, device_map=device_map, offload_folder=offload_folder + ) + outputs2 = base_model_with_offload(inputs) + torch.testing.assert_close(outputs1[0].cpu(), outputs2[0].cpu()) + + # With state dict temp offload + new_model_with_offload = AutoModel.from_pretrained( + tmp_dir, + device_map=device_map, + offload_folder=offload_folder, + offload_state_dict=True, + ) + outputs2 = new_model_with_offload(inputs) + torch.testing.assert_close(outputs1[0].cpu(), outputs2[0].cpu()) + + @slow + @require_torch + def test_from_pretrained_non_contiguous_checkpoint(self): + # See: https://github.com/huggingface/transformers/pull/28414 + # Tiny models on the Hub have contiguous weights, contrarily to google/owlvit + model = OwlViTForObjectDetection.from_pretrained("fxmarty/owlvit-tiny-non-contiguous-weight") + self.assertTrue(model.owlvit.visual_projection.weight.is_contiguous()) + + model = OwlViTForObjectDetection.from_pretrained( + "fxmarty/owlvit-tiny-non-contiguous-weight", device_map="auto" + ) + self.assertTrue(model.owlvit.visual_projection.weight.is_contiguous()) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=False) + model.save_pretrained(tmp_dir, safe_serialization=True) + + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Under the mock environment we get a 500 error when trying to reach the model. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + # This check we did call the fake head request + mock_head.assert_called() + + @require_accelerate + @mark.accelerate_tests + def test_save_model_with_device_map_cpu(self): + model_id = "hf-internal-testing/tiny-random-gpt2" + inputs = torch.tensor([[1, 2, 3]]) + + with tempfile.TemporaryDirectory() as tmp_dir: + model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cpu") + output = model(inputs)[0] + model.save_pretrained( + tmp_dir, max_shard_size="200KB" + ) # model is 1.6MB, max shard size is allocated to cpu by default + saved_model = AutoModelForCausalLM.from_pretrained(tmp_dir, device_map="cpu") + saved_model_output = saved_model(inputs)[0] + + torch.testing.assert_close(output, saved_model_output) + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_save_offloaded_model(self): + device_map = { + "transformer.wte": f"{torch_device}:0", + "transformer.wpe": f"{torch_device}:0", + "transformer.h.0": "cpu", + "transformer.h.1": "cpu", + "transformer.h.2": "cpu", + "transformer.h.3": "disk", + "transformer.h.4": "disk", + "transformer.ln_f": f"{torch_device}:0", + "lm_head": f"{torch_device}:0", + } + + # check_models_equal requires onloaded tensors + model_id = "hf-internal-testing/tiny-random-gpt2" + onloaded_model = AutoModelForCausalLM.from_pretrained(model_id, device_map="cpu").to(f"{torch_device}:0") + inputs = torch.tensor([[1, 2, 3]]).to(f"{torch_device}:0") + output = onloaded_model(inputs)[0] + + with tempfile.TemporaryDirectory() as tmp_dir: + offload_folder = os.path.join(tmp_dir, "offload") + offloaded_model = AutoModelForCausalLM.from_pretrained( + model_id, device_map=device_map, offload_folder=offload_folder + ) + presaved_output = offloaded_model(inputs)[0] + offloaded_model.save_pretrained( + tmp_dir, max_shard_size="200KB" + ) # model is 1.6MB, max shard size is allocated to cpu by default + saved_model = AutoModelForCausalLM.from_pretrained(tmp_dir, device_map=device_map) + postsaved_output = saved_model(inputs)[0] + + torch.testing.assert_close(output, presaved_output, rtol=1e-4, atol=1e-4) + torch.testing.assert_close(presaved_output, postsaved_output) + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_save_offloaded_model_with_direct_params(self): + from accelerate import dispatch_model + + device_map = {"submodule": "cpu", "linear": f"{torch_device}:0"} + model = ModelWithDirectParamSubmodule(PretrainedConfig()) + dispatch_model(model, device_map) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + @require_accelerate + @mark.accelerate_tests + @require_torch_accelerator + def test_save_offloaded_model_dynamic_tied_weights_keys(self): + from accelerate import dispatch_model + + device_map = {"base": f"{torch_device}:0", "linear": "cpu", "linear2": "cpu"} + model = ModelWithHead(PretrainedConfig()) + dispatch_model(model, device_map) + + transform_a = torch.nn.Linear(1, 1, bias=False) + transform_a._dynamic_tied_weights_keys = ["weight"] + transform_b = torch.nn.Linear(1, 1, bias=False) + transform_b._dynamic_tied_weights_keys = ["weight"] + + model.linear.register_module("transform_a", transform_a) + model.linear.register_module("transform_b", transform_b) + model.linear2.register_module("transform_a", transform_a) + model.linear2.register_module("transform_b", transform_b) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + @require_safetensors + def test_use_safetensors(self): + # Should not raise anymore + AutoModel.from_pretrained("hf-internal-testing/tiny-random-RobertaModel", use_safetensors=True) + + # test that error if only safetensors is available + with self.assertRaises(OSError) as env_error: + BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-safetensors", use_safetensors=False) + + self.assertTrue("does not appear to have a file named pytorch_model.bin" in str(env_error.exception)) + + # test that only safetensors if both available and use_safetensors=False + with tempfile.TemporaryDirectory() as tmp_dir: + CLIPTextModel.from_pretrained( + "hf-internal-testing/diffusers-stable-diffusion-tiny-all", + subfolder="text_encoder", + use_safetensors=False, + cache_dir=tmp_dir, + ) + + all_downloaded_files = glob.glob(os.path.join(tmp_dir, "*", "snapshots", "*", "*", "*")) + self.assertTrue(any(f.endswith("bin") for f in all_downloaded_files)) + self.assertFalse(any(f.endswith("safetensors") for f in all_downloaded_files)) + + # test that no safetensors if both available and use_safetensors=True + with tempfile.TemporaryDirectory() as tmp_dir: + CLIPTextModel.from_pretrained( + "hf-internal-testing/diffusers-stable-diffusion-tiny-all", + subfolder="text_encoder", + use_safetensors=True, + cache_dir=tmp_dir, + ) + + all_downloaded_files = glob.glob(os.path.join(tmp_dir, "*", "snapshots", "*", "*", "*")) + self.assertTrue(any(f.endswith("safetensors") for f in all_downloaded_files)) + self.assertFalse(any(f.endswith("bin") for f in all_downloaded_files)) + + # test no model file found when use_safetensors=None (default when safetensors package available) + with self.assertRaises(OSError) as missing_model_file_error: + BertModel.from_pretrained("hf-internal-testing/config-no-model") + + self.assertTrue( + "does not appear to have a file named pytorch_model.bin, model.safetensors," + in str(missing_model_file_error.exception) + ) + + with self.assertRaises(OSError) as missing_model_file_error: + with tempfile.TemporaryDirectory() as tmp_dir: + with open(os.path.join(tmp_dir, "config.json"), "w") as f: + f.write("{}") + f.close() + BertModel.from_pretrained(tmp_dir) + + self.assertTrue( + "Error no file named pytorch_model.bin, model.safetensors" in str(missing_model_file_error.exception) + ) + + @require_safetensors + def test_safetensors_save_and_load(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + # No pytorch_model.bin file, only a model.safetensors + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + + new_model = BertModel.from_pretrained(tmp_dir) + + # Check models are equal + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + @require_safetensors + def test_safetensors_load_from_hub(self): + safetensors_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-safetensors") + pytorch_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Check models are equal + for p1, p2 in zip(safetensors_model.parameters(), pytorch_model.parameters()): + torch.testing.assert_close(p1, p2) + + @require_safetensors + def test_safetensors_save_and_load_sharded(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True, max_shard_size="100kB") + # No pytorch_model.bin index file, only a model.safetensors index + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_INDEX_NAME))) + self.assertTrue(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_INDEX_NAME))) + # No regular weights file + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, WEIGHTS_NAME))) + self.assertFalse(os.path.isfile(os.path.join(tmp_dir, SAFE_WEIGHTS_NAME))) + + new_model = BertModel.from_pretrained(tmp_dir) + + # Check models are equal + for p1, p2 in zip(model.parameters(), new_model.parameters()): + torch.testing.assert_close(p1, p2) + + @require_safetensors + def test_safetensors_load_from_hub_sharded(self): + safetensors_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded-safetensors") + pytorch_model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert-sharded") + + # Check models are equal + for p1, p2 in zip(safetensors_model.parameters(), pytorch_model.parameters()): + torch.testing.assert_close(p1, p2) + + def test_base_model_to_head_model_load(self): + base_model = BaseModel(PretrainedConfig()) + with tempfile.TemporaryDirectory() as tmp_dir: + base_model.save_pretrained(tmp_dir, safe_serialization=False) + + # Can load a base model in a model with head + model = ModelWithHead.from_pretrained(tmp_dir) + for p1, p2 in zip(model.base.parameters(), base_model.parameters()): + torch.testing.assert_close(p1, p2) + + # It doesn't work if the state dict has a mix of keys of the head and base without prefix though. + base_state_dict = base_model.state_dict() + head_state_dict = model.state_dict() + base_state_dict["linear2.weight"] = head_state_dict["linear2.weight"] + base_state_dict["linear2.bias"] = head_state_dict["linear2.bias"] + safe_save_file(base_state_dict, os.path.join(tmp_dir, SAFE_WEIGHTS_NAME), metadata={"format": "pt"}) + + with self.assertRaisesRegex( + ValueError, "The state dictionary of the model you are trying to load is corrupted." + ): + _ = ModelWithHead.from_pretrained(tmp_dir) + + def test_tied_weights_reload(self): + # Base + model = BaseModelWithTiedWeights(PretrainedConfig()) + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + new_model = BaseModelWithTiedWeights.from_pretrained(tmp_dir) + self.assertIs(new_model.linear.weight, new_model.linear_2.weight) + + state_dict = model.state_dict() + # Remove tied weight from state_dict -> model should load with no complain of missing keys + del state_dict["linear_2.weight"] + torch.save(state_dict, os.path.join(tmp_dir, WEIGHTS_NAME)) + new_model, load_info = BaseModelWithTiedWeights.from_pretrained(tmp_dir, output_loading_info=True) + self.assertListEqual(load_info["missing_keys"], []) + self.assertIs(new_model.linear.weight, new_model.linear_2.weight) + + # With head + model.save_pretrained(tmp_dir) + new_model, load_info = ModelWithHeadAndTiedWeights.from_pretrained(tmp_dir, output_loading_info=True) + self.assertIs(new_model.base.linear.weight, new_model.decoder.weight) + # Should only complain about the missing bias + self.assertListEqual(load_info["missing_keys"], ["decoder.bias"]) + + def test_unexpected_keys_warnings(self): + model = ModelWithHead(PretrainedConfig()) + logger = logging.get_logger("transformers.modeling_utils") + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + + # Loading the model with a new class, we don't get a warning for unexpected weights, just an info + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + _, loading_info = BaseModel.from_pretrained(tmp_dir, output_loading_info=True) + self.assertNotIn("were not used when initializing ModelWithHead", cl.out) + self.assertEqual( + set(loading_info["unexpected_keys"]), + {"linear.weight", "linear.bias", "linear2.weight", "linear2.bias"}, + ) + + # Loading the model with the same class, we do get a warning for unexpected weights + state_dict = model.state_dict() + state_dict["added_key"] = copy.deepcopy(state_dict["linear.weight"]) + safe_save_file(state_dict, os.path.join(tmp_dir, SAFE_WEIGHTS_NAME), metadata={"format": "pt"}) + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + _, loading_info = ModelWithHead.from_pretrained(tmp_dir, output_loading_info=True) + self.assertIn("were not used when initializing ModelWithHead: ['added_key']", cl.out) + self.assertEqual(loading_info["unexpected_keys"], ["added_key"]) + + def test_warn_if_padding_and_no_attention_mask(self): + logger = logging.get_logger("transformers.modeling_utils") + + with self.subTest("Ensure no warnings when pad_token_id is None."): + logger.warning_once.cache_clear() + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + config_no_pad_token = PretrainedConfig() + config_no_pad_token.pad_token_id = None + model = ModelWithHead(config_no_pad_token) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertNotIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure no warnings when there is an attention_mask."): + logger.warning_once.cache_clear() + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + attention_mask = torch.tensor([[1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask) + self.assertNotIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure no warnings when there are no pad_token_ids in the input_ids."): + logger.warning_once.cache_clear() + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[1, 345, 232, 328, 740, 140, 1695, 69, 6078, 2341, 25]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertNotIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure a warning is shown when the input_ids start with a pad_token_id."): + logger.warning_once.cache_clear() + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 432, 5232]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure a warning is shown when the input_ids end with a pad_token_id."): + logger.warning_once.cache_clear() + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[432, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertIn("We strongly recommend passing in an `attention_mask`", cl.out) + + with self.subTest("Ensure that the warning is shown at most once."): + logger.warning_once.cache_clear() + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertEqual(cl.out.count("We strongly recommend passing in an `attention_mask`"), 1) + + with self.subTest("Ensure a different warning is shown when the pad_token_id is equal to the bos_token_id."): + logger.warning_once.cache_clear() + with LoggingLevel(logging.WARNING): + with CaptureLogger(logger) as cl: + config = PretrainedConfig() + config.pad_token_id = 0 + config.bos_token_id = config.pad_token_id + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 0, 0]]) + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + self.assertIn("You may ignore this warning if your `pad_token_id`", cl.out) + + with self.subTest("Ensure that the warning code is skipped when compiling with torchdynamo."): + logger.warning_once.cache_clear() + from torch._dynamo import config, testing + + config = PretrainedConfig() + config.pad_token_id = 0 + model = ModelWithHead(config) + input_ids = torch.tensor([[0, 345, 232, 328, 740, 140, 1695, 69, 6078, 432, 5232]]) + + def f(input_ids): + model.warn_if_padding_and_no_attention_mask(input_ids, attention_mask=None) + + compile_counter = testing.CompileCounter() + opt_fn = torch.compile(f, dynamic=True, backend=compile_counter) + opt_fn(input_ids) + self.assertEqual(compile_counter.frame_count, 0) + + @require_torch_accelerator + @slow + def test_pretrained_low_mem_new_config(self): + # Checking for 1 model(the same one which was described in the issue) . + model_ids = ["openai-community/gpt2"] + + for model_id in model_ids: + model_config = AutoConfig.from_pretrained(pretrained_model_name_or_path=model_id) + model_config.n_layer = 48 + model_config.n_head = 25 + model_config.n_embd = 1600 + model = AutoModelForCausalLM.from_pretrained( + pretrained_model_name_or_path=model_id, + config=model_config, + ignore_mismatched_sizes=True, + torch_dtype=torch.float16, + ) + model_ref = AutoModelForCausalLM.from_pretrained(pretrained_model_name_or_path=model_id) + + self.assertEqual(model.__class__.__name__, model_ref.__class__.__name__) + + def test_generation_config_is_loaded_with_model(self): + # Note: `hf-internal-testing/tiny-random-MistralForCausalLM` has a `generation_config.json` + # containing `bos_token_id: 1` + + # 1. Load without further parameters + model = AutoModelForCausalLM.from_pretrained(TINY_MISTRAL) + self.assertEqual(model.generation_config.bos_token_id, 1) + + # 2. Load with `device_map` + model = AutoModelForCausalLM.from_pretrained(TINY_MISTRAL, device_map="auto") + self.assertEqual(model.generation_config.bos_token_id, 1) + + @require_safetensors + def test_safetensors_torch_from_torch(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + new_model = BertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + @require_safetensors + def test_safetensors_torch_from_torch_sharded(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-only") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True, max_shard_size="100kB") + new_model = BertModel.from_pretrained(tmp_dir) + + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + def test_modifying_model_config_gets_moved_to_generation_config(self): + """ + Calling `model.save_pretrained` should move the changes made to `generate` parameterization in the model config + to the generation config. + """ + model = AutoModelForCausalLM.from_pretrained("openai-community/gpt2") + # Initially, the repetition penalty has its default value in `model.config`. The `model.generation_config` will + # have the exact same default + self.assertTrue(model.config.repetition_penalty == 1.0) + self.assertTrue(model.generation_config.repetition_penalty == 1.0) + # If the user attempts to save a custom generation parameter: + model.config.repetition_penalty = 3.0 + with warnings.catch_warnings(record=True) as warning_list: + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + # 1 - That parameter will be removed from `model.config`. We don't want to use `model.config` to store + # generative parameters, and the old default (1.0) would no longer relect the user's wishes. + self.assertTrue(model.config.repetition_penalty is None) + # 2 - That parameter will be set in `model.generation_config` instead. + self.assertTrue(model.generation_config.repetition_penalty == 3.0) + # 3 - The user will see a warning regarding the custom parameter that has been moved. + self.assertTrue(len(warning_list) == 1) + self.assertTrue("Moving the following attributes" in str(warning_list[0].message)) + self.assertTrue("repetition_penalty" in str(warning_list[0].message)) + + @require_safetensors + def test_model_from_pretrained_from_mlx(self): + from safetensors import safe_open + + model = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-mistral-mlx") + self.assertIsNotNone(model) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, safe_serialization=True) + with safe_open(os.path.join(tmp_dir, "model.safetensors"), framework="pt") as f: + metadata = f.metadata() + self.assertEqual(metadata.get("format"), "pt") + new_model = AutoModelForCausalLM.from_pretrained(tmp_dir) + + input_ids = torch.randint(100, 1000, (1, 10)) + with torch.no_grad(): + outputs = model(input_ids) + outputs_from_saved = new_model(input_ids) + torch.testing.assert_close(outputs_from_saved["logits"], outputs["logits"]) + + def test_warning_for_beta_gamma_parameters(self): + logger = logging.get_logger("transformers.modeling_utils") + config = PretrainedConfig() + warning_msg_gamma = "`LayerNorm.gamma` -> `LayerNorm.weight`" + warning_msg_beta = "`LayerNorm.beta` -> `LayerNorm.bias`" + model = TestModelGammaBeta(config) + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + with LoggingLevel(logging.INFO): + with CaptureLogger(logger) as cl1: + _, loading_info = TestModelGammaBeta.from_pretrained( + tmp_dir, config=config, output_loading_info=True + ) + + missing_keys = loading_info["missing_keys"] + unexpected_keys = loading_info["unexpected_keys"] + self.assertIn("`TestModelGammaBeta`", cl1.out) + self.assertIn(warning_msg_gamma, cl1.out) + self.assertIn(warning_msg_beta, cl1.out) + self.assertIn("LayerNorm.gamma", missing_keys) + self.assertIn("LayerNorm.weight", unexpected_keys) + self.assertIn("LayerNorm.beta", missing_keys) + self.assertIn("LayerNorm.bias", unexpected_keys) + + def test_isin_mps_friendly(self): + """tests that our custom `isin_mps_friendly` matches `torch.isin`""" + random_ids = torch.randint(0, 100, (100,)) + # We can match against an integer + random_test_integer = torch.randint(0, 100, (1,)).item() + self.assertTrue( + torch.equal( + torch.isin(random_ids, random_test_integer), isin_mps_friendly(random_ids, random_test_integer) + ) + ) + # We can match against an 0D tensor + random_test_tensor = torch.randint(0, 100, (1,)).squeeze() + self.assertTrue( + torch.equal(torch.isin(random_ids, random_test_tensor), isin_mps_friendly(random_ids, random_test_tensor)) + ) + # We can match against an 1D tensor (with many items) + random_test_tensor = torch.randint(0, 100, (10,)) + self.assertTrue( + torch.equal(torch.isin(random_ids, random_test_tensor), isin_mps_friendly(random_ids, random_test_tensor)) + ) + + def test_can_generate(self): + """Tests the behavior of `PreTrainedModel.can_generate` method.""" + logger = logging.get_logger("transformers.modeling_utils") + logger.warning_once.cache_clear() + + # 1 - By default, a model CAN'T generate + can_generate = BertModel.can_generate() + self.assertFalse(can_generate) + + # 2 - The most common case for a model to be able to generate is to inherit from `GenerationMixin` directly + class DummyBertWithMixin(BertModel, GenerationMixin): + pass + + with CaptureLogger(logger) as cl: + can_generate = DummyBertWithMixin.can_generate() + self.assertTrue("" == cl.out) + self.assertTrue(can_generate) + + # 3 - Finally, it can inherit from a model that can generate + class DummyBertWithParent(DummyBertWithMixin): + pass + + with CaptureLogger(logger) as cl: + can_generate = DummyBertWithParent.can_generate() + self.assertTrue("" == cl.out) + self.assertTrue(can_generate) + + # 4 - Legacy: models with a custom `prepare_inputs_for_generation` can generate (it was assumed + # they inherited `GenerationMixin`). Deprecated in v4.45 and removed in v4.51. + class DummyBertWithPrepareInputs(BertModel): + def prepare_inputs_for_generation(self): + pass + + with CaptureLogger(logger) as cl: + can_generate = DummyBertWithPrepareInputs.can_generate() + self.assertTrue("it doesn't directly inherit from `GenerationMixin`" in cl.out) + self.assertFalse(can_generate) + + def test_save_and_load_config_with_custom_generation(self): + """ + Regression test for the ability to save and load a config with a custom generation kwarg (i.e. a parameter + that gets moved to the generation config and reset on the model config) + """ + model = T5ForConditionalGeneration.from_pretrained(TINY_T5) + + # The default for `num_beams` is 1 and `early_stopping` is False + self.assertTrue(model.config.num_beams == 1) + self.assertTrue(model.config.early_stopping is False) + + # When we save the model, this custom parameter should be moved to the generation config AND the model + # config should contain `None` + model.config.num_beams = 2 + model.config.early_stopping = True + self.assertTrue(model.generation_config.num_beams == 1) # unmodified generation config + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + new_model = T5ForConditionalGeneration.from_pretrained(tmp_dir) + # moved to generation config + self.assertTrue(new_model.generation_config.num_beams == 2) + self.assertTrue(new_model.generation_config.early_stopping is True) + # reset in the model config + self.assertTrue(new_model.config.num_beams is None) + self.assertTrue(new_model.config.early_stopping is None) + + # Sanity check: We can run `generate` with the new model without any warnings + random_ids = torch.randint(0, 100, (1, 5)) + with warnings.catch_warnings(record=True) as w: + new_model.generate(random_ids, max_new_tokens=3) + self.assertTrue(len(w) == 0) + + def test_load_model_with_state_dict_only(self): + model = BertModel.from_pretrained("hf-internal-testing/tiny-random-bert") + state_dict = model.state_dict() + config = model.config + + model_loaded = BertModel.from_pretrained( + pretrained_model_name_or_path=None, config=config, state_dict=state_dict + ) + self.assertTrue(check_models_equal(model, model_loaded)) + + def test_cache_when_needed_at_train_time(self): + """ + Some fine-tuning methods require the use of cache, like prefix tuning in PEFT. This test checks that a cache + is at train time used if we request it. Related issue: #35648 + """ + model = AutoModelForCausalLM.from_pretrained(TINY_MISTRAL) + tokenizer = AutoTokenizer.from_pretrained(TINY_MISTRAL) + model_inputs = tokenizer("Hello, my dog is cute", return_tensors="pt") + + # By default it is not training, we have to set it + self.assertFalse(model.training) + model.train() + + # If we set `use_cache=True` while training, then a cache is returned + model_outputs = model(**model_inputs, use_cache=True) + self.assertIsInstance(model_outputs.past_key_values, DynamicCache) + self.assertTrue(model.training) + + # simulate injecting virtual tokens like in prefix tuning + num_virtual_tokens = 3 + past_key_values = [torch.randn(2, 1, 2, num_virtual_tokens, 8)] * 2 + past_key_values = DynamicCache.from_legacy_cache(past_key_values) + model_inputs["attention_mask"] = torch.cat( + ( + model_inputs["attention_mask"], + torch.ones(1, num_virtual_tokens).to(model_inputs["attention_mask"].device), + ), + dim=1, + ) + model_outputs = model(**model_inputs, past_key_values=past_key_values, use_cache=True) + self.assertTrue(model.training) + + # We can also disable the cache to skip a few operations, if the training loop doesn't need cache + model_outputs = model(**model_inputs, use_cache=False) + self.assertIsNone(model_outputs.past_key_values) + self.assertTrue(model.training) + + def test_restore_default_torch_dtype_from_pretrained(self): + """ + Tests that the default torch dtype is restored + when an error happens during the loading of a model. + """ + old_dtype = torch.get_default_dtype() + # set default type to float32 + torch.set_default_dtype(torch.float32) + + # Mock injection point which is right after the call to `_set_default_torch_dtype` + original_set_default_torch_dtype = MistralForCausalLM._set_default_torch_dtype + + def debug(*args, **kwargs): + # call the method as usual, than raise a RuntimeError + original_set_default_torch_dtype(*args, **kwargs) + raise RuntimeError + + with mock.patch( + "transformers.models.mistral.modeling_mistral.MistralForCausalLM._set_default_torch_dtype", + side_effect=debug, + ): + with self.assertRaises(RuntimeError): + _ = AutoModelForCausalLM.from_pretrained(TINY_MISTRAL, device_map="auto", torch_dtype=torch.float16) + # default should still be float32 + assert torch.get_default_dtype() == torch.float32 + torch.set_default_dtype(old_dtype) + + def test_restore_default_torch_dtype_from_config(self): + """ + Tests that the default torch dtype is restored + when an error happens during the loading of a model. + """ + old_dtype = torch.get_default_dtype() + # set default type to float32 + torch.set_default_dtype(torch.float32) + + config = AutoConfig.from_pretrained( + TINY_MISTRAL, + ) + + # Mock injection point which is right after the call to `_set_default_torch_dtype` + original_set_default_torch_dtype = MistralForCausalLM._set_default_torch_dtype + + def debug(*args, **kwargs): + # call the method as usual, than raise a RuntimeError + original_set_default_torch_dtype(*args, **kwargs) + raise RuntimeError + + with mock.patch( + "transformers.models.mistral.modeling_mistral.MistralForCausalLM._set_default_torch_dtype", + side_effect=debug, + ): + with self.assertRaises(RuntimeError): + config.torch_dtype = torch.float16 + _ = AutoModelForCausalLM.from_config( + config, + ) + # default should still be float32 + assert torch.get_default_dtype() == torch.float32 + torch.set_default_dtype(old_dtype) + + def test_unknown_quantization_config(self): + with tempfile.TemporaryDirectory() as tmpdir: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + config.quantization_config = {"quant_method": "unknown"} + model.save_pretrained(tmpdir) + with self.assertLogs("transformers", level="WARNING") as cm: + BertModel.from_pretrained(tmpdir) + self.assertEqual(len(cm.records), 1) + self.assertTrue(cm.records[0].message.startswith("Unknown quantization type, got")) + + @parameterized.expand([("Qwen/Qwen2.5-3B-Instruct", 10), ("meta-llama/Llama-2-7b-chat-hf", 10)]) + @slow + @require_read_token + @require_torch_accelerator + def test_loading_is_fast_on_gpu(self, model_id: str, max_loading_time: float): + """ + This test is used to avoid regression on https://github.com/huggingface/transformers/pull/36380. + 10s should be more than enough for both models, and allows for some margin as loading time are quite + unstable. Before #36380, it used to take more than 40s, so 10s is still reasonable. + Note that we run this test in a subprocess, to ensure that cuda is not already initialized/warmed-up. + """ + # First download the weights if not already on disk + _ = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.float16) + + script_to_run = textwrap.dedent( + """ + import torch + import time + import argparse + from transformers import AutoModelForCausalLM + from transformers.utils import is_torch_accelerator_available + + parser = argparse.ArgumentParser() + parser.add_argument("model_id", type=str) + parser.add_argument("max_loading_time", type=float) + args = parser.parse_args() + + device_type = torch.accelerator.current_accelerator().type if is_torch_accelerator_available() else "cuda" + device = torch.device(f"{device_type}:0") + + torch_accelerator_module = getattr(torch, device_type, torch.cuda) + torch_accelerator_module.synchronize(device) + t0 = time.time() + model = AutoModelForCausalLM.from_pretrained(args.model_id, torch_dtype=torch.float16, device_map=device) + torch_accelerator_module.synchronize(device) + dt = time.time() - t0 + + # Assert loading is faster (it should be more than enough in both cases) + if dt > args.max_loading_time: + raise ValueError(f"Loading took {dt:.2f}s! It should not take more than {args.max_loading_time}s") + # Ensure everything is correctly loaded on accelerator + bad_device_params = {k for k, v in model.named_parameters() if v.device != device} + if len(bad_device_params) > 0: + raise ValueError(f"The following parameters are not on accelerator: {bad_device_params}") + """ + ) + + with tempfile.NamedTemporaryFile(mode="w+", suffix=".py") as tmp: + tmp.write(script_to_run) + tmp.flush() + tmp.seek(0) + cmd = f"python {tmp.name} {model_id} {max_loading_time}".split() + try: + # We cannot use a timeout of `max_loading_time` as cuda initialization can take up to 15-20s + _ = subprocess.run(cmd, capture_output=True, env=self.get_env(), text=True, check=True, timeout=60) + except subprocess.CalledProcessError as e: + raise Exception(f"The following error was captured: {e.stderr}") + + def test_explicit_transformers_weights(self): + """ + Transformers supports loading from repos where the weights file is explicitly set in the config. + When loading a config file, transformers will see whether `transformers_weights` is defined in the config. + If so, it will load from that file. + + Here, we ensure that the correct file is loaded. + """ + model = BertModel.from_pretrained("hf-internal-testing/explicit_transformers_weight_in_config") + self.assertEqual(model.num_parameters(), 87929) + + def test_explicit_transformers_weights_index(self): + """ + Transformers supports loading from repos where the weights file is explicitly set in the config. + When loading a config file, transformers will see whether `transformers_weights` is defined in the config. + If so, it will load from that file. + + Here, we ensure that the correct file is loaded, given the file is an index of multiple weights. + """ + model = BertModel.from_pretrained("hf-internal-testing/explicit_transformers_weight_in_config_sharded") + self.assertEqual(model.num_parameters(), 87929) + + def test_explicit_transformers_weights_save_and_reload(self): + """ + Transformers supports loading from repos where the weights file is explicitly set in the config. + When loading a config file, transformers will see whether `transformers_weights` is defined in the config. + If so, it will load from that file. + + When saving the model, we should be careful not to safe the `transformers_weights` attribute in the config; + otherwise, transformers will try to load from that file whereas it should simply load from the default file. + + We test that for a non-sharded repo. + """ + model = BertModel.from_pretrained("hf-internal-testing/explicit_transformers_weight_in_config") + explicit_transformers_weights = model.config.transformers_weights + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + + # The config should not have a mention of transformers_weights + with open(os.path.join(tmpdirname, "config.json")) as f: + config = json.loads(f.read()) + self.assertFalse("transformers_weights" in config) + + # The serialized weights should be in model.safetensors and not the transformers_weights + self.assertTrue(explicit_transformers_weights not in os.listdir(tmpdirname)) + self.assertTrue("model.safetensors" in os.listdir(tmpdirname)) + + def test_explicit_transformers_weights_index_save_and_reload(self): + """ + Transformers supports loading from repos where the weights file is explicitly set in the config. + When loading a config file, transformers will see whether `transformers_weights` is defined in the config. + If so, it will load from that file. + + When saving the model, we should be careful not to safe the `transformers_weights` attribute in the config; + otherwise, transformers will try to load from that file whereas it should simply load from the default file. + + We test that for a sharded repo. + """ + model = BertModel.from_pretrained("hf-internal-testing/explicit_transformers_weight_in_config_sharded") + explicit_transformers_weights = model.config.transformers_weights + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname, max_shard_size="100kb") + + # The config should not have a mention of transformers_weights + with open(os.path.join(tmpdirname, "config.json")) as f: + config = json.loads(f.read()) + self.assertFalse("transformers_weights" in config) + + # The serialized weights should be in model.safetensors and not the transformers_weights + self.assertTrue(explicit_transformers_weights not in os.listdir(tmpdirname)) + self.assertTrue("model.safetensors.index.json" in os.listdir(tmpdirname)) + + def test_config_class_attribute(self): + # custom configs + class MyConfigA(PretrainedConfig): + pass + + class MyConfigB(PretrainedConfig): + pass + + class MyConfigC(PretrainedConfig): + pass + + # custom models + class MyModelA(PreTrainedModel): + config: dict + config_class = MyConfigA + + class MyModelB(MyModelA): + config: MyConfigB + + class MyModelC(MyModelA): + config_class = MyConfigC + + class MyModelD(MyModelA): + pass + + # child config_class > child 'config:' > parent config_class > parent 'config:' + self.assertIs(MyModelA.config_class, MyConfigA) + self.assertIs(MyModelB.config_class, MyConfigB) + self.assertIs(MyModelC.config_class, MyConfigC) + self.assertIs(MyModelD.config_class, MyConfigA) + + +@slow +@require_torch +class ModelOnTheFlyConversionTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.user = "huggingface-hub-ci" + cls.token = os.getenv("HUGGINGFACE_PRODUCTION_USER_TOKEN", None) + + if cls.token is None: + raise ValueError("Cannot run tests as secret isn't setup.") + + cls.api = HfApi(token=cls.token) + + def setUp(self) -> None: + self.repo_name = f"{self.user}/test-model-on-the-fly-{uuid.uuid4()}" + + def tearDown(self) -> None: + self.api.delete_repo(self.repo_name) + + def test_safetensors_on_the_fly_conversion(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, "SFconvertbot") + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_conversion_private(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False, private=True) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name, token=self.token) + discussion = next(discussions) + self.assertEqual(discussion.author, self.user) + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_conversion_gated(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False) + headers = {"Authorization": f"Bearer {self.token}"} + requests.put( + f"https://huggingface.co/api/models/{self.repo_name}/settings", json={"gated": "auto"}, headers=headers + ) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, "SFconvertbot") + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_sharded_conversion(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False, max_shard_size="200kb") + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, "SFconvertbot") + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_sharded_conversion_private(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub( + self.repo_name, token=self.token, safe_serialization=False, max_shard_size="200kb", private=True + ) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, self.user) + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_sharded_conversion_gated(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, max_shard_size="200kb", safe_serialization=False) + headers = {"Authorization": f"Bearer {self.token}"} + requests.put( + f"https://huggingface.co/api/models/{self.repo_name}/settings", json={"gated": "auto"}, headers=headers + ) + converted_model = BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("Initial and converted models are equal"): + for p1, p2 in zip(initial_model.parameters(), converted_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, "SFconvertbot") + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + @unittest.skip(reason="Edge case, should work once the Space is updated`") + def test_safetensors_on_the_fly_wrong_user_opened_pr(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False, private=True) + BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + # This should have opened a PR with the user's account + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + discussion = next(discussions) + self.assertEqual(discussion.author, self.user) + self.assertEqual(discussion.title, "Adding `safetensors` variant of this model") + + # We now switch the repo visibility to public + self.api.update_repo_settings(self.repo_name, private=False) + + # We once again call from_pretrained, which should call the bot to open a PR + BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token) + + with self.subTest("PR was open with the safetensors account"): + discussions = self.api.get_repo_discussions(self.repo_name) + + bot_opened_pr = None + bot_opened_pr_title = None + + for discussion in discussions: + if discussion.author == "SFconvertbot": + bot_opened_pr = True + bot_opened_pr_title = discussion.title + + self.assertTrue(bot_opened_pr) + self.assertEqual(bot_opened_pr_title, "Adding `safetensors` variant of this model") + + def test_safetensors_on_the_fly_specific_revision(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + # Push a model on `main` + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False) + + # Push a model on a given revision + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False, revision="new-branch") + + # Try to convert the model on that revision should raise + with self.assertRaises(EnvironmentError): + BertModel.from_pretrained(self.repo_name, use_safetensors=True, token=self.token, revision="new-branch") + + def test_absence_of_safetensors_triggers_conversion(self): + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + # Push a model on `main` + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False) + + # Download the model that doesn't have safetensors + BertModel.from_pretrained(self.repo_name, token=self.token) + + for thread in threading.enumerate(): + if thread.name == "Thread-autoconversion": + thread.join(timeout=10) + + discussions = self.api.get_repo_discussions(self.repo_name) + + bot_opened_pr = None + bot_opened_pr_title = None + + for discussion in discussions: + if discussion.author == "SFconvertbot": + bot_opened_pr = True + bot_opened_pr_title = discussion.title + + self.assertTrue(bot_opened_pr) + self.assertEqual(bot_opened_pr_title, "Adding `safetensors` variant of this model") + + @mock.patch("transformers.safetensors_conversion.spawn_conversion") + def test_absence_of_safetensors_triggers_conversion_failed(self, spawn_conversion_mock): + spawn_conversion_mock.side_effect = HTTPError() + + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + initial_model = BertModel(config) + + # Push a model on `main` + initial_model.push_to_hub(self.repo_name, token=self.token, safe_serialization=False) + + # The auto conversion is mocked to always raise; ensure that it doesn't raise in the main thread + BertModel.from_pretrained(self.repo_name, token=self.token) + + +@require_torch +@is_staging_test +class ModelPushToHubTester(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + @unittest.skip(reason="This test is flaky") + def test_push_to_hub(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + model.push_to_hub(tmp_repo.repo_id, token=self._token) + + new_model = BertModel.from_pretrained(tmp_repo.repo_id) + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + @unittest.skip(reason="This test is flaky") + def test_push_to_hub_via_save_pretrained(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) + + new_model = BertModel.from_pretrained(tmp_repo.repo_id) + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + def test_push_to_hub_with_description(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + COMMIT_DESCRIPTION = """ +The commit description supports markdown synthax see: +```python +>>> form transformers import AutoConfig +>>> config = AutoConfig.from_pretrained("google-bert/bert-base-uncased") +``` +""" + commit_details = model.push_to_hub( + tmp_repo.repo_id, use_auth_token=self._token, create_pr=True, commit_description=COMMIT_DESCRIPTION + ) + self.assertEqual(commit_details.commit_description, COMMIT_DESCRIPTION) + + @unittest.skip(reason="This test is flaky") + def test_push_to_hub_in_organization(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + model.push_to_hub(tmp_repo.repo_id, token=self._token) + + new_model = BertModel.from_pretrained(tmp_repo.repo_id) + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + @unittest.skip(reason="This test is flaky") + def test_push_to_hub_in_organization_via_save_pretrained(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + config = BertConfig( + vocab_size=99, hidden_size=32, num_hidden_layers=5, num_attention_heads=4, intermediate_size=37 + ) + model = BertModel(config) + # Push to hub via save_pretrained + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir, push_to_hub=True, token=self._token, repo_id=tmp_repo.repo_id) + + new_model = BertModel.from_pretrained(tmp_repo.repo_id) + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + def test_push_to_hub_dynamic_model(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + CustomConfig.register_for_auto_class() + CustomModel.register_for_auto_class() + + config = CustomConfig(hidden_size=32) + model = CustomModel(config) + + model.push_to_hub(tmp_repo.repo_id, token=self._token) + # checks + self.assertDictEqual( + config.auto_map, + {"AutoConfig": "custom_configuration.CustomConfig", "AutoModel": "custom_modeling.CustomModel"}, + ) + + new_model = AutoModel.from_pretrained(tmp_repo.repo_id, trust_remote_code=True) + # Can't make an isinstance check because the new_model is from the CustomModel class of a dynamic module + self.assertEqual(new_model.__class__.__name__, "CustomModel") + for p1, p2 in zip(model.parameters(), new_model.parameters()): + self.assertTrue(torch.equal(p1, p2)) + + config = AutoConfig.from_pretrained(tmp_repo.repo_id, trust_remote_code=True) + new_model = AutoModel.from_config(config, trust_remote_code=True) + self.assertEqual(new_model.__class__.__name__, "CustomModel") + + def test_push_to_hub_with_tags(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + from huggingface_hub import ModelCard + + new_tags = ["tag-1", "tag-2"] + + CustomConfig.register_for_auto_class() + CustomModel.register_for_auto_class() + + config = CustomConfig(hidden_size=32) + model = CustomModel(config) + + self.assertTrue(model.model_tags is None) + + model.add_model_tags(new_tags) + + self.assertTrue(model.model_tags == new_tags) + + model.push_to_hub(tmp_repo.repo_id, token=self._token) + + loaded_model_card = ModelCard.load(tmp_repo.repo_id) + self.assertEqual(loaded_model_card.data.tags, new_tags) + + +@require_torch +class AttentionMaskTester(unittest.TestCase): + def check_non_causal(self, bsz, q_len, kv_len, mask_2d, mask_4d): + mask_indices = (mask_2d != 1)[:, None].broadcast_to((bsz, q_len, kv_len)) + mask_4d_values = mask_4d[:, 0][mask_indices] + is_inf = mask_4d_values == -float("inf") + is_min = mask_4d_values == torch.finfo(mask_4d.dtype).min + assert torch.logical_or(is_inf, is_min).all() + + def check_to_4d(self, mask_converter, q_len, kv_len, additional_mask=None, bsz=3): + mask_2d = torch.ones((bsz, kv_len), device=torch_device, dtype=torch.long) + + if additional_mask is not None: + for bsz_idx, seq_idx in additional_mask: + mask_2d[bsz_idx, seq_idx] = 0 + + mask_4d = mask_converter.to_4d(mask_2d, query_length=q_len, key_value_length=kv_len, dtype=torch.float32) + + assert mask_4d.shape == (bsz, 1, q_len, kv_len) + + # make sure there are no overflows + assert mask_4d.min() != float("-inf") + + context = mask_converter.sliding_window + if mask_converter.is_causal and context is None: + # k * (k+1) / 2 tokens are masked in triangualar masks + num_tokens_masked = bsz * (q_len * (q_len - 1) // 2) + + if 0 not in mask_2d: + assert (mask_4d != 0).sum().item() == num_tokens_masked + if 0 in mask_2d: + # at least causal mask + maybe more + assert (mask_4d != 0).sum().item() >= num_tokens_masked + self.check_non_causal(bsz, q_len, kv_len, mask_2d, mask_4d) + elif not mask_converter.is_causal and context is None: + if 0 not in mask_2d: + assert (mask_4d != 0).sum().item() == 0 + if 0 in mask_2d: + self.check_non_causal(bsz, q_len, kv_len, mask_2d, mask_4d) + elif mask_converter.is_causal and context is not None: + # k * (k+1) / 2 tokens are masked in triangualar masks + num_tokens_masked = (q_len * (q_len - 1) // 2) + self.compute_num_context_mask(kv_len, context, q_len) + num_tokens_masked = bsz * num_tokens_masked + + if 0 not in mask_2d: + assert (mask_4d != 0).sum().item() == num_tokens_masked + if 0 in mask_2d: + # at least causal mask + maybe more + assert (mask_4d != 0).sum().item() >= num_tokens_masked + self.check_non_causal(bsz, q_len, kv_len, mask_2d, mask_4d) + + def check_to_causal(self, mask_converter, q_len, kv_len, bsz=3): + mask_4d = mask_converter.to_causal_4d( + bsz, query_length=q_len, key_value_length=kv_len, device=torch_device, dtype=torch.float32 + ) + + if q_len == 1 and mask_converter.sliding_window is None: + # no causal mask if q_len is 1 + assert mask_4d is None + return + + context = mask_converter.sliding_window + if mask_converter.is_causal and context is None: + # k * (k+1) / 2 tokens are masked in triangualar masks + num_tokens_masked = bsz * (q_len * (q_len - 1) // 2) + + assert (mask_4d != 0).sum().item() == num_tokens_masked + elif not mask_converter.is_causal and context is None: + assert (mask_4d != 0).sum().item() == 0 + elif mask_converter.is_causal and context is not None: + # k * (k+1) / 2 tokens are masked in triangualar masks + num_tokens_masked = (q_len * (q_len - 1) // 2) + self.compute_num_context_mask(kv_len, context, q_len) + num_tokens_masked = bsz * num_tokens_masked + + assert (mask_4d != 0).sum().item() == num_tokens_masked + + def compute_num_context_mask(self, kv_len, context, q_len): + # This function computes the # of attention tokens that are added for + # the sliding window + c_mask_len = kv_len - context - 1 + num_mask_triangle = c_mask_len * (c_mask_len + 1) // 2 + cut_mask_len = max(c_mask_len - q_len, 0) + num_cut_mask = cut_mask_len * (cut_mask_len + 1) // 2 + return num_mask_triangle - num_cut_mask + + def test_2d_to_4d_causal(self): + mask_converter = AttentionMaskConverter(is_causal=True) + + # auto-regressive use case + self.check_to_4d(mask_converter, q_len=1, kv_len=7) + # special auto-regressive case + self.check_to_4d(mask_converter, q_len=3, kv_len=7) + # non auto-regressive case + self.check_to_4d(mask_converter, q_len=7, kv_len=7) + + # same with extra attention masks + self.check_to_4d(mask_converter, q_len=1, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + self.check_to_4d(mask_converter, q_len=3, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + self.check_to_4d(mask_converter, q_len=7, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + + # check that the mask does not overflow on causal masked tokens + self.check_to_4d(mask_converter, q_len=7, kv_len=7, additional_mask=[(0, 0), (1, 0), (1, 1)]) + + def test_2d_to_4d(self): + mask_converter = AttentionMaskConverter(is_causal=False) + + # non auto-regressive case + self.check_to_4d(mask_converter, q_len=7, kv_len=7) + + # same with extra attention masks + self.check_to_4d(mask_converter, q_len=7, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + + def test_2d_to_4d_causal_sliding(self): + mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=5) + + # auto-regressive use case + self.check_to_4d(mask_converter, q_len=1, kv_len=7) + # special auto-regressive case + self.check_to_4d(mask_converter, q_len=3, kv_len=7) + # non auto-regressive case + self.check_to_4d(mask_converter, q_len=7, kv_len=7) + + # same with extra attention masks + self.check_to_4d(mask_converter, q_len=1, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + self.check_to_4d(mask_converter, q_len=3, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + self.check_to_4d(mask_converter, q_len=7, kv_len=7, additional_mask=[(0, 2), (1, 3), (2, 0)]) + + def test_causal_mask(self): + mask_converter = AttentionMaskConverter(is_causal=True) + + # auto-regressive use case + self.check_to_causal(mask_converter, q_len=1, kv_len=7) + # special auto-regressive case + self.check_to_causal(mask_converter, q_len=3, kv_len=7) + # non auto-regressive case + self.check_to_causal(mask_converter, q_len=7, kv_len=7) + + def test_causal_mask_sliding(self): + mask_converter = AttentionMaskConverter(is_causal=True, sliding_window=3) + + # auto-regressive use case + self.check_to_causal(mask_converter, q_len=1, kv_len=7) + # special auto-regressive case + self.check_to_causal(mask_converter, q_len=3, kv_len=7) + # non auto-regressive case + self.check_to_causal(mask_converter, q_len=7, kv_len=7) + + @pytest.mark.torch_compile_test + def test_torch_compile_fullgraph(self): + model = Prepare4dCausalAttentionMaskModel() + + inputs_embeds = torch.rand([1, 3, 32]) + res_non_compiled = model(inputs_embeds) + + compiled_model = torch.compile(model, fullgraph=True) + + res_compiled = compiled_model(inputs_embeds) + + self.assertTrue(torch.equal(res_non_compiled, res_compiled)) + + model = Create4dCausalAttentionMaskModel() + + inputs_embeds = torch.rand(2, 4, 16) + res_non_compiled = model(inputs_embeds) + + compiled_model = torch.compile(model, fullgraph=True) + res_compiled = compiled_model(inputs_embeds) + + self.assertTrue(torch.equal(res_non_compiled, res_compiled)) + + model = Prepare4dAttentionMaskModel() + + mask = torch.ones(2, 4) + mask[0, :2] = 0 + inputs_embeds = torch.rand(2, 4, 16) + + res_non_compiled = model(mask, inputs_embeds) + + compiled_model = torch.compile(model, fullgraph=True) + res_compiled = compiled_model(mask, inputs_embeds) + + self.assertTrue(torch.equal(res_non_compiled, res_compiled)) + + @require_torch + @slow + def test_unmask_unattended_left_padding(self): + attention_mask = torch.Tensor([[0, 0, 1], [1, 1, 1], [0, 1, 1]]).to(torch.int64) + + expanded_mask = torch.Tensor( + [ + [[[0, 0, 0], [0, 0, 0], [0, 0, 1]]], + [[[1, 0, 0], [1, 1, 0], [1, 1, 1]]], + [[[0, 0, 0], [0, 1, 0], [0, 1, 1]]], + ] + ).to(torch.int64) + + reference_output = torch.Tensor( + [ + [[[1, 1, 1], [1, 1, 1], [0, 0, 1]]], + [[[1, 0, 0], [1, 1, 0], [1, 1, 1]]], + [[[1, 1, 1], [0, 1, 0], [0, 1, 1]]], + ] + ).to(torch.int64) + + result = AttentionMaskConverter._unmask_unattended(expanded_mask, attention_mask, unmasked_value=1) + + self.assertTrue(torch.equal(result, reference_output)) + + attention_mask = torch.Tensor([[0, 0, 1, 1, 1], [1, 1, 1, 1, 1], [0, 1, 1, 1, 1]]).to(torch.int64) + + attn_mask_converter = AttentionMaskConverter(is_causal=True) + past_key_values_length = 0 + key_value_length = attention_mask.shape[-1] + past_key_values_length + + expanded_mask = attn_mask_converter.to_4d( + attention_mask, attention_mask.shape[-1], key_value_length=key_value_length, dtype=torch.float32 + ) + + result = AttentionMaskConverter._unmask_unattended(expanded_mask, attention_mask, unmasked_value=0) + min_inf = torch.finfo(torch.float32).min + reference_output = torch.Tensor( + [ + [ + [ + [0, 0, 0, 0, 0], + [0, 0, 0, 0, 0], + [min_inf, min_inf, 0, min_inf, min_inf], + [min_inf, min_inf, 0, 0, min_inf], + [min_inf, min_inf, 0, 0, 0], + ] + ], + [ + [ + [0, min_inf, min_inf, min_inf, min_inf], + [0, 0, min_inf, min_inf, min_inf], + [0, 0, 0, min_inf, min_inf], + [0, 0, 0, 0, min_inf], + [0, 0, 0, 0, 0], + ] + ], + [ + [ + [0, 0, 0, 0, 0], + [min_inf, 0, min_inf, min_inf, min_inf], + [min_inf, 0, 0, min_inf, min_inf], + [min_inf, 0, 0, 0, min_inf], + [min_inf, 0, 0, 0, 0], + ] + ], + ] + ) + + self.assertTrue(torch.equal(reference_output, result)) + + @require_torch + @slow + def test_unmask_unattended_right_padding(self): + attention_mask = torch.Tensor([[1, 1, 1, 0], [1, 1, 1, 1], [1, 1, 0, 0]]).to(torch.int64) + + attn_mask_converter = AttentionMaskConverter(is_causal=True) + past_key_values_length = 0 + key_value_length = attention_mask.shape[-1] + past_key_values_length + + expanded_mask = attn_mask_converter.to_4d( + attention_mask, attention_mask.shape[-1], key_value_length=key_value_length, dtype=torch.float32 + ) + + result = AttentionMaskConverter._unmask_unattended(expanded_mask, attention_mask, unmasked_value=0) + + self.assertTrue(torch.equal(expanded_mask, result)) + + @require_torch + @slow + def test_unmask_unattended_random_mask(self): + attention_mask = torch.Tensor([[1, 0, 1, 0], [1, 0, 1, 1], [1, 1, 0, 1]]).to(torch.int64) + + attn_mask_converter = AttentionMaskConverter(is_causal=True) + past_key_values_length = 0 + key_value_length = attention_mask.shape[-1] + past_key_values_length + + expanded_mask = attn_mask_converter.to_4d( + attention_mask, attention_mask.shape[-1], key_value_length=key_value_length, dtype=torch.float32 + ) + + result = AttentionMaskConverter._unmask_unattended(expanded_mask, attention_mask, unmasked_value=0) + + self.assertTrue(torch.equal(expanded_mask, result)) + + +@require_torch +class TestAttentionImplementation(unittest.TestCase): + @unittest.skip("Just a bit annoying") + def test_error_no_sdpa_available(self): + with self.assertRaises(ValueError) as cm: + _ = AutoModel.from_pretrained("hf-tiny-model-private/tiny-random-MCTCTModel", attn_implementation="sdpa") + + self.assertTrue( + "does not support an attention implementation through torch.nn.functional.scaled_dot_product_attention" + in str(cm.exception) + ) + + _ = AutoModel.from_pretrained("hf-tiny-model-private/tiny-random-MCTCTModel") + + def test_error_no_flash_available(self): + with self.assertRaises(ValueError) as cm: + _ = AutoModel.from_pretrained( + "hf-tiny-model-private/tiny-random-MCTCTModel", attn_implementation="flash_attention_2" + ) + + self.assertTrue("does not support Flash Attention 2.0" in str(cm.exception)) + + def test_error_no_flash_available_with_config(self): + with self.assertRaises(ValueError) as cm: + config = AutoConfig.from_pretrained("hf-tiny-model-private/tiny-random-MCTCTModel") + + _ = AutoModel.from_pretrained( + "hf-tiny-model-private/tiny-random-MCTCTModel", config=config, attn_implementation="flash_attention_2" + ) + + self.assertTrue("does not support Flash Attention 2.0" in str(cm.exception)) + + def test_error_wrong_attn_implementation(self): + with self.assertRaises(ValueError) as cm: + _ = AutoModel.from_pretrained("hf-tiny-model-private/tiny-random-MCTCTModel", attn_implementation="foo") + + self.assertTrue('The only possible arguments are `attn_implementation="eager"' in str(cm.exception)) + + def test_not_available_flash(self): + if is_flash_attn_2_available(): + self.skipTest(reason="Please uninstall flash-attn package to run test_not_available_flash") + + if is_torch_npu_available(): + self.skipTest( + reason="FlashAttention2 is supported on Ascend NPU without using package `flash-attn`, ignore this test case." + ) + + with self.assertRaises(ImportError) as cm: + _ = AutoModel.from_pretrained( + "hf-internal-testing/tiny-random-GPTBigCodeModel", attn_implementation="flash_attention_2" + ) + self.assertTrue("the package flash_attn seems to be not installed" in str(cm.exception)) + + def test_not_available_flash_with_config(self): + if is_flash_attn_2_available(): + self.skipTest(reason="Please uninstall flash-attn package to run test_not_available_flash") + + if is_torch_npu_available(): + self.skipTest( + reason="FlashAttention2 is supported on Ascend NPU without using package `flash-attn`, ignore this test case." + ) + + config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-GPTBigCodeModel") + + with self.assertRaises(ImportError) as cm: + _ = AutoModel.from_pretrained( + "hf-internal-testing/tiny-random-GPTBigCodeModel", + config=config, + attn_implementation="flash_attention_2", + ) + + self.assertTrue("the package flash_attn seems to be not installed" in str(cm.exception)) + + def test_not_available_sdpa(self): + if is_torch_sdpa_available(): + self.skipTest(reason="This test requires torch<=2.0") + + with self.assertRaises(ImportError) as cm: + _ = AutoModel.from_pretrained( + "hf-internal-testing/tiny-random-GPTBigCodeModel", attn_implementation="sdpa" + ) + + self.assertTrue("PyTorch SDPA requirements in Transformers are not met" in str(cm.exception)) + + +@require_torch +class TestTensorSharing(TestCasePlus): + def test_disjoint(self): + main = torch.zeros(10) + a = main[:5] + b = main[5:] + state_dict = {"a": a, "b": b} + + shared_names, disjoint_names = _find_disjoint([{"a", "b"}], state_dict) + self.assertEqual(shared_names, []) + self.assertEqual(disjoint_names, ["a", "b"]) + + a = main[::2] + b = main[1::2] + state_dict = {"a": a, "b": b} + + shared_names, disjoint_names = _find_disjoint([{"a", "b"}], state_dict) + self.assertEqual(shared_names, [{"a", "b"}]) + self.assertEqual(disjoint_names, []) + + def test_identical(self): + a = torch.zeros(10) + b = a + state_dict = {"a": a, "b": b} + + shared_names, identical_names = _find_identical([{"a", "b"}], state_dict) + self.assertEqual(shared_names, []) + self.assertEqual(identical_names, [{"a", "b"}]) + + b = a[:5] + state_dict = {"a": a, "b": b} + + shared_names, identical_names = _find_identical([{"a", "b"}], state_dict) + self.assertEqual(shared_names, [{"a", "b"}]) + self.assertEqual(identical_names, []) + + +@require_torch +class TestSaveAndLoadModelWithExtraState(TestCasePlus): + """ + This test checks that a model can be saved and loaded that uses the torch extra state API. + https://pytorch.org/docs/stable/generated/torch.nn.Module.html#torch.nn.Module.get_extra_state. + + Currently, only tensor-valued extra_states are supported. + """ + + def test_save_and_load_model_with_tensor_extra_state(self): + class MyConfig(PretrainedConfig): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + class MyModule(torch.nn.Module): + def __init__(self): + super().__init__() + self.some_counter = 0 + self.linear = torch.nn.Linear(320, 320) + + def get_extra_state(self): + return torch.tensor(self.some_counter) + + def set_extra_state(self, state): + self.some_counter = state.item() + + class MyModel(PreTrainedModel): + config_class = MyConfig + + def __init__(self, config: MyConfig): + super().__init__(config) + self.my_layer = MyModule() + + def forward(self, hidden_states, attention_mask): + return self.my_layer(hidden_states, attention_mask) + + config = MyConfig() + model = MyModel(config) + model.my_layer.some_counter = 42 + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = MyModel.from_pretrained(tmpdirname) + self.assertEqual(model.my_layer.some_counter, 42) + + @mark.xfail(reason="save and from_pretrained currently only supports tensor extra_state") + def test_save_and_load_model_with_dict_extra_state(self): + class MyConfig(PretrainedConfig): + def __init__(self, **kwargs): + super().__init__(**kwargs) + + class MyModule(torch.nn.Module): + def __init__(self): + super().__init__() + self.some_counter = 0 + self.linear = torch.nn.Linear(320, 320) + + def get_extra_state(self): + return {"some_counter": self.some_counter} + + def set_extra_state(self, state): + self.some_counter = state["some_counter"] + + class MyModel(PreTrainedModel): + config_class = MyConfig + + def __init__(self, config: MyConfig): + super().__init__(config) + self.my_layer = MyModule() + + def forward(self, hidden_states, attention_mask): + return self.my_layer(hidden_states, attention_mask) + + config = MyConfig() + model = MyModel(config) + model.my_layer.some_counter = 42 + + with tempfile.TemporaryDirectory() as tmpdirname: + model.save_pretrained(tmpdirname) + model = MyModel.from_pretrained(tmpdirname) + self.assertEqual(model.my_layer.some_counter, 42) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_offline.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_offline.py new file mode 100644 index 0000000000000000000000000000000000000000..357005eb575b51b24ba847559a270f3ef2d76b0d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_offline.py @@ -0,0 +1,220 @@ +# 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. + +import subprocess +import sys +import unittest + +from transformers import BertConfig, BertModel, BertTokenizer, pipeline +from transformers.testing_utils import TestCasePlus, require_torch + + +class OfflineTests(TestCasePlus): + @require_torch + @unittest.skip("This test is failing on main") # TODO matt/ydshieh, this test needs to be fixed + def test_offline_mode(self): + # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before + # `transformers` is loaded, and it's too late for inside pytest - so we are changing it + # while running an external program + + # python one-liner segments + + # this must be loaded before socket.socket is monkey-patched + load = """ +from transformers import BertConfig, BertModel, BertTokenizer, pipeline + """ + + run = """ +mname = "hf-internal-testing/tiny-random-bert" +BertConfig.from_pretrained(mname) +BertModel.from_pretrained(mname) +BertTokenizer.from_pretrained(mname) +pipe = pipeline(task="fill-mask", model=mname) +print("success") + """ + + mock = """ +import socket +def offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn't access internet") +socket.socket = offline_socket + """ + + # Force fetching the files so that we can use the cache + mname = "hf-internal-testing/tiny-random-bert" + BertConfig.from_pretrained(mname) + BertModel.from_pretrained(mname) + BertTokenizer.from_pretrained(mname) + pipeline(task="fill-mask", model=mname) + + # baseline - just load from_pretrained with normal network + # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files + stdout, _ = self._execute_with_env(load, run, mock, TRANSFORMERS_OFFLINE="1") + self.assertIn("success", stdout) + + @require_torch + def test_offline_mode_no_internet(self): + # python one-liner segments + # this must be loaded before socket.socket is monkey-patched + load = """ +from transformers import BertConfig, BertModel, BertTokenizer, pipeline + """ + + run = """ +mname = "hf-internal-testing/tiny-random-bert" +BertConfig.from_pretrained(mname) +BertModel.from_pretrained(mname) +BertTokenizer.from_pretrained(mname) +pipe = pipeline(task="fill-mask", model=mname) +print("success") + """ + + mock = """ +import socket +def offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet") +socket.socket = offline_socket + """ + + # Force fetching the files so that we can use the cache + mname = "hf-internal-testing/tiny-random-bert" + BertConfig.from_pretrained(mname) + BertModel.from_pretrained(mname) + BertTokenizer.from_pretrained(mname) + pipeline(task="fill-mask", model=mname) + + # baseline - just load from_pretrained with normal network + # should succeed + stdout, _ = self._execute_with_env(load, run, mock) + self.assertIn("success", stdout) + + @require_torch + def test_offline_mode_sharded_checkpoint(self): + # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before + # `transformers` is loaded, and it's too late for inside pytest - so we are changing it + # while running an external program + + # python one-liner segments + + # this must be loaded before socket.socket is monkey-patched + load = """ +from transformers import BertConfig, BertModel, BertTokenizer + """ + + run = """ +mname = "hf-internal-testing/tiny-random-bert-sharded" +BertConfig.from_pretrained(mname) +BertModel.from_pretrained(mname) +print("success") + """ + + mock = """ +import socket +def offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled") +socket.socket = offline_socket + """ + + # baseline - just load from_pretrained with normal network + # should succeed + stdout, _ = self._execute_with_env(load, run) + self.assertIn("success", stdout) + + # next emulate no network + # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this. + # self._execute_with_env(load, mock, run, should_fail=True, TRANSFORMERS_OFFLINE="0") + + # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files + stdout, _ = self._execute_with_env(load, mock, run, TRANSFORMERS_OFFLINE="1") + self.assertIn("success", stdout) + + @require_torch + def test_offline_mode_pipeline_exception(self): + load = """ +from transformers import pipeline + """ + run = """ +mname = "hf-internal-testing/tiny-random-bert" +pipe = pipeline(model=mname) + """ + + mock = """ +import socket +def offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled") +socket.socket = offline_socket + """ + + _, stderr = self._execute_with_env(load, mock, run, should_fail=True, TRANSFORMERS_OFFLINE="1") + self.assertIn( + "You cannot infer task automatically within `pipeline` when using offline mode", + stderr.replace("\n", ""), + ) + + @require_torch + def test_offline_model_dynamic_model(self): + load = """ +from transformers import AutoModel + """ + run = """ +mname = "hf-internal-testing/test_dynamic_model" +AutoModel.from_pretrained(mname, trust_remote_code=True) +print("success") + """ + + # baseline - just load from_pretrained with normal network + # should succeed + stdout, _ = self._execute_with_env(load, run) + self.assertIn("success", stdout) + + # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files + stdout, _ = self._execute_with_env(load, run, TRANSFORMERS_OFFLINE="1") + self.assertIn("success", stdout) + + def test_is_offline_mode(self): + """ + Test `_is_offline_mode` helper (should respect both HF_HUB_OFFLINE and legacy TRANSFORMERS_OFFLINE env vars) + """ + load = "from transformers.utils import is_offline_mode" + run = "print(is_offline_mode())" + + stdout, _ = self._execute_with_env(load, run) + self.assertIn("False", stdout) + + stdout, _ = self._execute_with_env(load, run, TRANSFORMERS_OFFLINE="1") + self.assertIn("True", stdout) + + stdout, _ = self._execute_with_env(load, run, HF_HUB_OFFLINE="1") + self.assertIn("True", stdout) + + def _execute_with_env(self, *commands: tuple[str, ...], should_fail: bool = False, **env) -> tuple[str, str]: + """Execute Python code with a given environment and return the stdout/stderr as strings. + + If `should_fail=True`, the command is expected to fail. Otherwise, it should succeed. + Environment variables can be passed as keyword arguments. + """ + # Build command + cmd = [sys.executable, "-c", "\n".join(commands)] + + # Configure env + new_env = self.get_env() + new_env.update(env) + + # Run command + result = subprocess.run(cmd, env=new_env, check=False, capture_output=True) + + # Check execution + if should_fail: + self.assertNotEqual(result.returncode, 0, result.stderr) + else: + self.assertEqual(result.returncode, 0, result.stderr) + + # Return output + return result.stdout.decode(), result.stderr.decode() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_skip_decorators.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_skip_decorators.py new file mode 100644 index 0000000000000000000000000000000000000000..2e5bdb80ac81de9d520285925f95106cdf1e9d60 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_skip_decorators.py @@ -0,0 +1,124 @@ +# Copyright 2019-present, the HuggingFace Inc. team. +# +# 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 test validates that we can stack skip decorators in groups and whether +# they work correctly with other decorators +# +# since the decorators have already built their decision params (like checking +# env[], we can't mock the env and test each of the combinations), so ideally +# the following 4 should be run. But since we have different CI jobs running +# different configs, all combinations should get covered +# +# RUN_SLOW=1 pytest -rA tests/test_skip_decorators.py +# RUN_SLOW=1 CUDA_VISIBLE_DEVICES="" pytest -rA tests/test_skip_decorators.py +# RUN_SLOW=0 pytest -rA tests/test_skip_decorators.py +# RUN_SLOW=0 CUDA_VISIBLE_DEVICES="" pytest -rA tests/test_skip_decorators.py + +import os +import unittest + +import pytest +from parameterized import parameterized + +from transformers.testing_utils import require_torch, require_torch_accelerator, slow, torch_device + + +# skipping in unittest tests + +params = [(1,)] + + +# test that we can stack our skip decorators with 3rd party decorators +def check_slow(): + run_slow = bool(os.getenv("RUN_SLOW", "0")) + if run_slow: + assert True + else: + assert False, "should have been skipped" + + +# test that we can stack our skip decorators +def check_slow_torch_cuda(): + run_slow = bool(os.getenv("RUN_SLOW", "0")) + if run_slow and torch_device == "cuda": + assert True + else: + assert False, "should have been skipped" + + +def check_slow_torch_accelerator(): + run_slow = bool(os.getenv("RUN_SLOW", "0")) + assert run_slow and torch_device in ["cuda", "xpu"], "should have been skipped" + + +@require_torch +class SkipTester(unittest.TestCase): + @slow + @require_torch_accelerator + def test_2_skips_slow_first(self): + check_slow_torch_accelerator() + + @require_torch_accelerator + @slow + def test_2_skips_slow_last(self): + check_slow_torch_accelerator() + + # The combination of any skip decorator, followed by parameterized fails to skip the tests + # 1. @slow manages to correctly skip `test_param_slow_first` + # 2. but then `parameterized` creates new tests, with a unique name for each parameter groups. + # It has no idea that they are to be skipped and so they all run, ignoring @slow + # Therefore skip decorators must come after `parameterized` + # + # @slow + # @parameterized.expand(params) + # def test_param_slow_first(self, param=None): + # check_slow() + + # This works as expected: + # 1. `parameterized` creates new tests with unique names + # 2. each of them gets an opportunity to be skipped + @parameterized.expand(params) + @slow + def test_param_slow_last(self, param=None): + check_slow() + + +# skipping in non-unittest tests +# no problem at all here + + +@slow +@require_torch_accelerator +def test_pytest_2_skips_slow_first(): + check_slow_torch_accelerator() + + +@require_torch_accelerator +@slow +def test_pytest_2_skips_slow_last(): + check_slow_torch_accelerator() + + +@slow +@pytest.mark.parametrize("param", [1]) +def test_pytest_param_slow_first(param): + check_slow() + + +@pytest.mark.parametrize("param", [1]) +@slow +def test_pytest_param_slow_last(param): + check_slow() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_tokenization_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_tokenization_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ff0f6499fe132ad9eeaaa5a95b657c4e65e6c11d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_tokenization_utils.py @@ -0,0 +1,303 @@ +# Copyright 2019 HuggingFace 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. + +import os +import sys +import tempfile +import unittest +import unittest.mock as mock +from pathlib import Path + +from huggingface_hub import HfFolder +from huggingface_hub.file_download import http_get +from requests.exceptions import HTTPError + +from transformers import ( + AlbertTokenizer, + AutoTokenizer, + BertTokenizer, + BertTokenizerFast, + GPT2TokenizerFast, + is_tokenizers_available, +) +from transformers.testing_utils import TOKEN, TemporaryHubRepo, is_staging_test, require_tokenizers +from transformers.tokenization_utils import ExtensionsTrie, Trie + + +sys.path.append(str(Path(__file__).parent.parent.parent / "utils")) + +from test_module.custom_tokenization import CustomTokenizer # noqa E402 + + +if is_tokenizers_available(): + from test_module.custom_tokenization_fast import CustomTokenizerFast + + +class TokenizerUtilTester(unittest.TestCase): + def test_cached_files_are_used_when_internet_is_down(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") + + # Under the mock environment we get a 500 error when trying to reach the tokenizer. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = BertTokenizer.from_pretrained("hf-internal-testing/tiny-random-bert") + # This check we did call the fake head request + mock_head.assert_called() + + @require_tokenizers + def test_cached_files_are_used_when_internet_is_down_missing_files(self): + # A mock response for an HTTP head request to emulate server down + response_mock = mock.Mock() + response_mock.status_code = 500 + response_mock.headers = {} + response_mock.raise_for_status.side_effect = HTTPError + response_mock.json.return_value = {} + + # Download this model to make sure it's in the cache. + _ = GPT2TokenizerFast.from_pretrained("openai-community/gpt2") + + # Under the mock environment we get a 500 error when trying to reach the tokenizer. + with mock.patch("requests.Session.request", return_value=response_mock) as mock_head: + _ = GPT2TokenizerFast.from_pretrained("openai-community/gpt2") + # This check we did call the fake head request + mock_head.assert_called() + + def test_legacy_load_from_one_file(self): + # This test is for deprecated behavior and can be removed in v5 + try: + tmp_file = tempfile.NamedTemporaryFile(delete=False).name + with open(tmp_file, "wb") as f: + http_get("https://huggingface.co/albert/albert-base-v1/resolve/main/spiece.model", f) + + _ = AlbertTokenizer.from_pretrained(tmp_file) + finally: + os.remove(tmp_file) + + # Supporting this legacy load introduced a weird bug where the tokenizer would load local files if they are in + # the current folder and have the right name. + if os.path.isfile("tokenizer.json"): + # We skip the test if the user has a `tokenizer.json` in this folder to avoid deleting it. + self.skipTest(reason="Skipping test as there is a `tokenizer.json` file in the current folder.") + try: + with open("tokenizer.json", "wb") as f: + http_get("https://huggingface.co/hf-internal-testing/tiny-random-bert/blob/main/tokenizer.json", f) + tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-gpt2") + # The tiny random BERT has a vocab size of 1024, tiny openai-community/gpt2 as a vocab size of 1000 + self.assertEqual(tokenizer.vocab_size, 1000) + # Tokenizer should depend on the remote checkpoint, not the local tokenizer.json file. + + finally: + os.remove("tokenizer.json") + + +@is_staging_test +class TokenizerPushToHubTester(unittest.TestCase): + vocab_tokens = ["[UNK]", "[CLS]", "[SEP]", "[PAD]", "[MASK]", "bla", "blou"] + + @classmethod + def setUpClass(cls): + cls._token = TOKEN + HfFolder.save_token(TOKEN) + + def test_push_to_hub(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = BertTokenizer(vocab_file) + + tokenizer.push_to_hub(tmp_repo.repo_id, token=self._token) + new_tokenizer = BertTokenizer.from_pretrained(tmp_repo.repo_id) + self.assertDictEqual(new_tokenizer.vocab, tokenizer.vocab) + + def test_push_to_hub_via_save_pretrained(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = BertTokenizer(vocab_file) + + # Push to hub via save_pretrained + tokenizer.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) + + new_tokenizer = BertTokenizer.from_pretrained(tmp_repo.repo_id) + self.assertDictEqual(new_tokenizer.vocab, tokenizer.vocab) + + def test_push_to_hub_in_organization(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = BertTokenizer(vocab_file) + + tokenizer.push_to_hub(tmp_repo.repo_id, token=self._token) + new_tokenizer = BertTokenizer.from_pretrained(tmp_repo.repo_id) + self.assertDictEqual(new_tokenizer.vocab, tokenizer.vocab) + + def test_push_to_hub_in_organization_via_save_pretrained(self): + with TemporaryHubRepo(namespace="valid_org", token=self._token) as tmp_repo: + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = BertTokenizer(vocab_file) + + # Push to hub via save_pretrained + tokenizer.save_pretrained(tmp_dir, repo_id=tmp_repo.repo_id, push_to_hub=True, token=self._token) + + new_tokenizer = BertTokenizer.from_pretrained(tmp_repo.repo_id) + self.assertDictEqual(new_tokenizer.vocab, tokenizer.vocab) + + @require_tokenizers + def test_push_to_hub_dynamic_tokenizer(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + CustomTokenizer.register_for_auto_class() + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + tokenizer = CustomTokenizer(vocab_file) + + # No fast custom tokenizer + tokenizer.push_to_hub(tmp_repo.repo_id, token=self._token) + + tokenizer = AutoTokenizer.from_pretrained(tmp_repo.repo_id, trust_remote_code=True) + # Can't make an isinstance check because the new_model.config is from the CustomTokenizer class of a dynamic module + self.assertEqual(tokenizer.__class__.__name__, "CustomTokenizer") + + @require_tokenizers + def test_push_to_hub_dynamic_tokenizer_with_both_slow_and_fast_classes(self): + with TemporaryHubRepo(token=self._token) as tmp_repo: + CustomTokenizer.register_for_auto_class() + + # Fast and slow custom tokenizer + CustomTokenizerFast.register_for_auto_class() + + with tempfile.TemporaryDirectory() as tmp_dir: + vocab_file = os.path.join(tmp_dir, "vocab.txt") + with open(vocab_file, "w", encoding="utf-8") as vocab_writer: + vocab_writer.write("".join([x + "\n" for x in self.vocab_tokens])) + + bert_tokenizer = BertTokenizerFast.from_pretrained(tmp_dir) + bert_tokenizer.save_pretrained(tmp_dir) + tokenizer = CustomTokenizerFast.from_pretrained(tmp_dir) + + tokenizer.push_to_hub(tmp_repo.repo_id, token=self._token) + + tokenizer = AutoTokenizer.from_pretrained(tmp_repo.repo_id, trust_remote_code=True) + # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module + self.assertEqual(tokenizer.__class__.__name__, "CustomTokenizerFast") + tokenizer = AutoTokenizer.from_pretrained(tmp_repo.repo_id, use_fast=False, trust_remote_code=True) + # Can't make an isinstance check because the new_model.config is from the FakeConfig class of a dynamic module + self.assertEqual(tokenizer.__class__.__name__, "CustomTokenizer") + + +class TrieTest(unittest.TestCase): + def test_trie(self): + trie = Trie() + trie.add("Hello 友達") + self.assertEqual(trie.data, {"H": {"e": {"l": {"l": {"o": {" ": {"友": {"達": {"": 1}}}}}}}}}) + trie.add("Hello") + self.assertEqual(trie.data, {"H": {"e": {"l": {"l": {"o": {"": 1, " ": {"友": {"達": {"": 1}}}}}}}}}) + + def test_trie_split(self): + trie = Trie() + self.assertEqual(trie.split("[CLS] This is a extra_id_100"), ["[CLS] This is a extra_id_100"]) + trie.add("[CLS]") + trie.add("extra_id_1") + trie.add("extra_id_100") + self.assertEqual(trie.split("[CLS] This is a extra_id_100"), ["[CLS]", " This is a ", "extra_id_100"]) + + def test_trie_single(self): + trie = Trie() + trie.add("A") + self.assertEqual(trie.split("ABC"), ["A", "BC"]) + self.assertEqual(trie.split("BCA"), ["BC", "A"]) + + def test_trie_final(self): + trie = Trie() + trie.add("TOKEN]") + trie.add("[SPECIAL_TOKEN]") + self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"), ["This is something ", "[SPECIAL_TOKEN]"]) + + def test_trie_subtokens(self): + trie = Trie() + trie.add("A") + trie.add("P") + trie.add("[SPECIAL_TOKEN]") + self.assertEqual(trie.split("This is something [SPECIAL_TOKEN]"), ["This is something ", "[SPECIAL_TOKEN]"]) + + def test_trie_suffix_tokens(self): + trie = Trie() + trie.add("AB") + trie.add("B") + trie.add("C") + self.assertEqual(trie.split("ABC"), ["AB", "C"]) + + def test_trie_skip(self): + trie = Trie() + trie.add("ABC") + trie.add("B") + trie.add("CD") + self.assertEqual(trie.split("ABCD"), ["ABC", "D"]) + + def test_cut_text_hardening(self): + # Even if the offsets are wrong, we necessarily output correct string + # parts. + trie = Trie() + parts = trie.cut_text("ABC", [0, 0, 2, 1, 2, 3]) + self.assertEqual(parts, ["AB", "C"]) + + +class ExtensionsTrieTest(unittest.TestCase): + def test_extensions(self): + # Test searching by prefix + trie = ExtensionsTrie() + trie.add("foo") + trie.add("food") + trie.add("foodie") + trie.add("helium") + self.assertEqual(trie.extensions("foo"), ["foo", "food", "foodie"]) + self.assertEqual(trie.extensions("helium"), ["helium"]) + + def test_empty_prefix(self): + trie = ExtensionsTrie() + # Test searching with an empty prefix returns all values + trie.add("hello") + trie.add("bye") + self.assertEqual(trie.extensions(""), ["hello", "bye"]) + + def test_no_extension_match(self): + trie = ExtensionsTrie() + # Test searching for a prefix that doesn't match any key + values = trie.extensions("unknown") + + self.assertEqual(len(values), 0) + + def test_update_value(self): + trie = ExtensionsTrie() + # Test updating the value of an existing key + trie.add("hi") + trie.add("hi") + self.assertEqual(trie.extensions("hi"), ["hi"]) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_versions_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_versions_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..c485c4e84bc7557175da86f14a10da2940dc693d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_versions_utils.py @@ -0,0 +1,97 @@ +# 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. + +import importlib.metadata +import sys + +from transformers.testing_utils import TestCasePlus +from transformers.utils.versions import require_version, require_version_core + + +numpy_ver = importlib.metadata.version("numpy") +python_ver = ".".join([str(x) for x in sys.version_info[:3]]) + + +class DependencyVersionCheckTest(TestCasePlus): + def test_core(self): + # lt + different version strings + require_version_core("numpy<1000.4.5") + require_version_core("numpy<1000.4") + require_version_core("numpy<1000") + + # le + require_version_core("numpy<=1000.4.5") + require_version_core(f"numpy<={numpy_ver}") + + # eq + require_version_core(f"numpy=={numpy_ver}") + + # ne + require_version_core("numpy!=1000.4.5") + + # ge + require_version_core("numpy>=1.0") + require_version_core("numpy>=1.0.0") + require_version_core(f"numpy>={numpy_ver}") + + # gt + require_version_core("numpy>1.0.0") + + # mix + require_version_core("numpy>1.0.0,<1000") + + # requirement w/o version + require_version_core("numpy") + + # unmet requirements due to version conflict + for req in ["numpy==1.0.0", "numpy>=1000.0.0", f"numpy<{numpy_ver}"]: + try: + require_version_core(req) + except ImportError as e: + self.assertIn(f"{req} is required", str(e)) + self.assertIn("but found", str(e)) + + # unmet requirements due to missing module + for req in ["numpipypie>1", "numpipypie2"]: + try: + require_version_core(req) + except importlib.metadata.PackageNotFoundError as e: + self.assertIn(f"The '{req}' distribution was not found and is required by this application", str(e)) + self.assertIn("Try: `pip install transformers -U`", str(e)) + + # bogus requirements formats: + # 1. whole thing + for req in ["numpy??1.0.0", "numpy1.0.0"]: + try: + require_version_core(req) + except ValueError as e: + self.assertIn("requirement needs to be in the pip package format", str(e)) + # 2. only operators + for req in ["numpy=1.0.0", "numpy == 1.00", "numpy<>1.0.0", "numpy><1.00", "numpy>>1.0.0"]: + try: + require_version_core(req) + except ValueError as e: + self.assertIn("need one of ", str(e)) + + def test_python(self): + # matching requirement + require_version("python>=3.9.0") + + # not matching requirements + for req in ["python>9.9.9", "python<3.0.0"]: + try: + require_version_core(req) + except ImportError as e: + self.assertIn(f"{req} is required", str(e)) + self.assertIn(f"but found python=={python_ver}", str(e)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_video_utils.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_video_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7c598222bd6b2fe6c126f6f259dab90e9a5999b6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/test_video_utils.py @@ -0,0 +1,346 @@ +# coding=utf-8 +# Copyright 2025 HuggingFace 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. + +import unittest + +import numpy as np +from huggingface_hub import hf_hub_download + +from transformers import is_torch_available, is_vision_available +from transformers.image_processing_utils import get_size_dict +from transformers.image_utils import SizeDict +from transformers.processing_utils import VideosKwargs +from transformers.testing_utils import ( + require_av, + require_cv2, + require_decord, + require_torch, + require_torchcodec, + require_torchvision, + require_vision, +) +from transformers.video_utils import group_videos_by_shape, make_batched_videos, reorder_videos + + +if is_torch_available(): + import torch + +if is_vision_available(): + import PIL + + from transformers import BaseVideoProcessor + from transformers.video_utils import VideoMetadata, load_video + + +def get_random_video(height, width, num_frames=8, return_torch=False): + random_frame = np.random.randint(0, 256, (height, width, 3), dtype=np.uint8) + video = np.array([random_frame] * num_frames) + if return_torch: + # move channel first + return torch.from_numpy(video).permute(0, 3, 1, 2) + return video + + +@require_vision +@require_torchvision +class BaseVideoProcessorTester(unittest.TestCase): + """ + Tests that the `transforms` can be applied to a 4-dim array directly, i.e. to a whole video. + """ + + def test_make_batched_videos_pil(self): + # Test a single image is converted to a list of 1 video with 1 frame + video = get_random_video(16, 32) + pil_image = PIL.Image.fromarray(video[0]) + videos_list = make_batched_videos(pil_image) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], np.ndarray) + self.assertEqual(videos_list[0].shape, (1, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0][0], np.array(pil_image))) + + # Test a list of videos is converted to a list of 1 video + video = get_random_video(16, 32) + pil_video = [PIL.Image.fromarray(frame) for frame in video] + videos_list = make_batched_videos(pil_video) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], np.ndarray) + self.assertEqual(videos_list[0].shape, (8, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0], video)) + + # Test a nested list of videos is not modified + video = get_random_video(16, 32) + pil_video = [PIL.Image.fromarray(frame) for frame in video] + videos = [pil_video, pil_video] + videos_list = make_batched_videos(videos) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], np.ndarray) + self.assertEqual(videos_list[0].shape, (8, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0], video)) + + def test_make_batched_videos_numpy(self): + # Test a single image is converted to a list of 1 video with 1 frame + video = get_random_video(16, 32)[0] + videos_list = make_batched_videos(video) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], np.ndarray) + self.assertEqual(videos_list[0].shape, (1, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0][0], video)) + + # Test a 4d array of videos is converted to a a list of 1 video + video = get_random_video(16, 32) + videos_list = make_batched_videos(video) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], np.ndarray) + self.assertEqual(videos_list[0].shape, (8, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0], video)) + + # Test a list of videos is converted to a list of videos + video = get_random_video(16, 32) + videos = [video, video] + videos_list = make_batched_videos(videos) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], np.ndarray) + self.assertEqual(videos_list[0].shape, (8, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0], video)) + + @require_torch + def test_make_batched_videos_torch(self): + # Test a single image is converted to a list of 1 video with 1 frame + video = get_random_video(16, 32)[0] + torch_video = torch.from_numpy(video) + videos_list = make_batched_videos(torch_video) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], np.ndarray) + self.assertEqual(videos_list[0].shape, (1, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0][0], video)) + + # Test a 4d array of videos is converted to a a list of 1 video + video = get_random_video(16, 32) + torch_video = torch.from_numpy(video) + videos_list = make_batched_videos(torch_video) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], torch.Tensor) + self.assertEqual(videos_list[0].shape, (8, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0], video)) + + # Test a list of videos is converted to a list of videos + video = get_random_video(16, 32) + torch_video = torch.from_numpy(video) + videos = [torch_video, torch_video] + videos_list = make_batched_videos(videos) + self.assertIsInstance(videos_list, list) + self.assertIsInstance(videos_list[0], torch.Tensor) + self.assertEqual(videos_list[0].shape, (8, 16, 32, 3)) + self.assertTrue(np.array_equal(videos_list[0], video)) + + def test_resize(self): + video_processor = BaseVideoProcessor(model_init_kwargs=VideosKwargs) + video = get_random_video(16, 32, return_torch=True) + + # Size can be an int or a tuple of ints. + size_dict = SizeDict(**get_size_dict((8, 8), param_name="size")) + resized_video = video_processor.resize(video, size=size_dict) + self.assertIsInstance(resized_video, torch.Tensor) + self.assertEqual(resized_video.shape, (8, 3, 8, 8)) + + def test_normalize(self): + video_processor = BaseVideoProcessor(model_init_kwargs=VideosKwargs) + array = torch.randn(4, 3, 16, 32) + mean = [0.1, 0.5, 0.9] + std = [0.2, 0.4, 0.6] + + # mean and std can be passed as lists or NumPy arrays. + expected = (array - torch.tensor(mean)[:, None, None]) / torch.tensor(std)[:, None, None] + normalized_array = video_processor.normalize(array, mean, std) + torch.testing.assert_close(normalized_array, expected) + + def test_center_crop(self): + video_processor = BaseVideoProcessor(model_init_kwargs=VideosKwargs) + video = get_random_video(16, 32, return_torch=True) + + # Test various crop sizes: bigger on all dimensions, on one of the dimensions only and on both dimensions. + crop_sizes = [8, (8, 64), 20, (32, 64)] + for size in crop_sizes: + size_dict = SizeDict(**get_size_dict(size, default_to_square=True, param_name="crop_size")) + cropped_video = video_processor.center_crop(video, size_dict) + self.assertIsInstance(cropped_video, torch.Tensor) + + expected_size = (size, size) if isinstance(size, int) else size + self.assertEqual(cropped_video.shape, (8, 3, *expected_size)) + + def test_convert_to_rgb(self): + video_processor = BaseVideoProcessor(model_init_kwargs=VideosKwargs) + video = get_random_video(20, 20, return_torch=True) + + rgb_video = video_processor.convert_to_rgb(video[:, :1]) + self.assertEqual(rgb_video.shape, (8, 3, 20, 20)) + + rgb_video = video_processor.convert_to_rgb(torch.cat([video, video[:, :1]], dim=1)) + self.assertEqual(rgb_video.shape, (8, 3, 20, 20)) + + def test_group_and_reorder_videos(self): + """Tests that videos can be grouped by frame size and number of frames""" + video_1 = get_random_video(20, 20, num_frames=3, return_torch=True) + video_2 = get_random_video(20, 20, num_frames=5, return_torch=True) + + # Group two videos of same size but different number of frames + grouped_videos, grouped_videos_index = group_videos_by_shape([video_1, video_2]) + self.assertEqual(len(grouped_videos), 2) + + regrouped_videos = reorder_videos(grouped_videos, grouped_videos_index) + self.assertTrue(len(regrouped_videos), 2) + self.assertEqual(video_1.shape, regrouped_videos[0].shape) + + # Group two videos of different size but same number of frames + video_3 = get_random_video(15, 20, num_frames=3, return_torch=True) + grouped_videos, grouped_videos_index = group_videos_by_shape([video_1, video_3]) + self.assertEqual(len(grouped_videos), 2) + + regrouped_videos = reorder_videos(grouped_videos, grouped_videos_index) + self.assertTrue(len(regrouped_videos), 2) + self.assertEqual(video_1.shape, regrouped_videos[0].shape) + + # Group all three videos where some have same size or same frame count + # But since none have frames and sizes identical, we'll have 3 groups + grouped_videos, grouped_videos_index = group_videos_by_shape([video_1, video_2, video_3]) + self.assertEqual(len(grouped_videos), 3) + + regrouped_videos = reorder_videos(grouped_videos, grouped_videos_index) + self.assertTrue(len(regrouped_videos), 3) + self.assertEqual(video_1.shape, regrouped_videos[0].shape) + + # Group if we had some videos with identical shapes + grouped_videos, grouped_videos_index = group_videos_by_shape([video_1, video_1, video_3]) + self.assertEqual(len(grouped_videos), 2) + + regrouped_videos = reorder_videos(grouped_videos, grouped_videos_index) + self.assertTrue(len(regrouped_videos), 2) + self.assertEqual(video_1.shape, regrouped_videos[0].shape) + + # Group if we had all videos with identical shapes + grouped_videos, grouped_videos_index = group_videos_by_shape([video_1, video_1, video_1]) + self.assertEqual(len(grouped_videos), 1) + + regrouped_videos = reorder_videos(grouped_videos, grouped_videos_index) + self.assertTrue(len(regrouped_videos), 1) + self.assertEqual(video_1.shape, regrouped_videos[0].shape) + + +@require_vision +@require_av +class LoadVideoTester(unittest.TestCase): + def test_load_video_url(self): + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", + ) + self.assertEqual(video.shape, (243, 360, 640, 3)) # 243 frames is the whole video, no sampling applied + + def test_load_video_local(self): + video_file_path = hf_hub_download( + repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset" + ) + video, _ = load_video(video_file_path) + self.assertEqual(video.shape, (243, 360, 640, 3)) # 243 frames is the whole video, no sampling applied + + # FIXME: @raushan, yt-dlp downloading works for for some reason it cannot redirect to out buffer? + # @requires_yt_dlp + # def test_load_video_youtube(self): + # video = load_video("https://www.youtube.com/watch?v=QC8iQqtG0hg") + # self.assertEqual(video.shape, (243, 360, 640, 3)) # 243 frames is the whole video, no sampling applied + + @require_decord + @require_torchvision + @require_torchcodec + @require_cv2 + def test_load_video_backend_url(self): + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", + backend="decord", + ) + self.assertEqual(video.shape, (243, 360, 640, 3)) + + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", + backend="torchcodec", + ) + self.assertEqual(video.shape, (243, 360, 640, 3)) + + # Can't use certain backends with url + with self.assertRaises(ValueError): + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", + backend="opencv", + ) + with self.assertRaises(ValueError): + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", + backend="torchvision", + ) + + @require_decord + @require_torchvision + @require_torchcodec + @require_cv2 + def test_load_video_backend_local(self): + video_file_path = hf_hub_download( + repo_id="raushan-testing-hf/videos-test", filename="sample_demo_1.mp4", repo_type="dataset" + ) + video, metadata = load_video(video_file_path, backend="decord") + self.assertEqual(video.shape, (243, 360, 640, 3)) + self.assertIsInstance(metadata, VideoMetadata) + + video, metadata = load_video(video_file_path, backend="opencv") + self.assertEqual(video.shape, (243, 360, 640, 3)) + self.assertIsInstance(metadata, VideoMetadata) + + video, metadata = load_video(video_file_path, backend="torchvision") + self.assertEqual(video.shape, (243, 360, 640, 3)) + self.assertIsInstance(metadata, VideoMetadata) + + video, metadata = load_video(video_file_path, backend="torchcodec") + self.assertEqual(video.shape, (243, 360, 640, 3)) + self.assertIsInstance(metadata, VideoMetadata) + + def test_load_video_num_frames(self): + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", + num_frames=16, + ) + self.assertEqual(video.shape, (16, 360, 640, 3)) + + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", + num_frames=22, + ) + self.assertEqual(video.shape, (22, 360, 640, 3)) + + def test_load_video_fps(self): + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", fps=1 + ) + self.assertEqual(video.shape, (9, 360, 640, 3)) + + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", fps=2 + ) + self.assertEqual(video.shape, (19, 360, 640, 3)) + + # `num_frames` is mutually exclusive with `video_fps` + with self.assertRaises(ValueError): + video, _ = load_video( + "https://huggingface.co/datasets/raushan-testing-hf/videos-test/resolve/main/sample_demo_1.mp4", + fps=1, + num_frames=10, + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/tiny_model_summary.json b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/tiny_model_summary.json new file mode 100644 index 0000000000000000000000000000000000000000..6c36448e5aba7e964fcffecbeba7464bd801c930 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/tests/utils/tiny_model_summary.json @@ -0,0 +1,7246 @@ +{ + "ASTForAudioClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ASTFeatureExtractor" + ], + "model_classes": [ + "ASTForAudioClassification" + ], + "sha": "83d6e076db7768a3645401bad3204624985e1d08" + }, + "ASTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ASTFeatureExtractor" + ], + "model_classes": [ + "ASTModel" + ], + "sha": "75e68f956f6f2c0709b01e596e7a6aecb1b29dce" + }, + "AlbertForMaskedLM": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForMaskedLM", + "TFAlbertForMaskedLM" + ], + "sha": "d29de71ac29e1019c3a7762f7357f750730cb037" + }, + "AlbertForMultipleChoice": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForMultipleChoice", + "TFAlbertForMultipleChoice" + ], + "sha": "242aecce6a589a2964c0f695621fa22a83751579" + }, + "AlbertForPreTraining": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForPreTraining", + "TFAlbertForPreTraining" + ], + "sha": "41330be4b271687f4d88ddc96346c12aa11de983" + }, + "AlbertForQuestionAnswering": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForQuestionAnswering", + "TFAlbertForQuestionAnswering" + ], + "sha": "040b81c15f437f4722349dc5b41fccd17ebd7fdc" + }, + "AlbertForSequenceClassification": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForSequenceClassification", + "TFAlbertForSequenceClassification" + ], + "sha": "39c1a0e2c1c2623106d3211d751e9b32f23a91a0" + }, + "AlbertForTokenClassification": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertForTokenClassification", + "TFAlbertForTokenClassification" + ], + "sha": "359c3f4a311a4053a6f6d6a880db5f82c8e3ff1f" + }, + "AlbertModel": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "AlbertModel", + "TFAlbertModel" + ], + "sha": "34a63314686b64aaeb595ddb95006f1ff2ffda17" + }, + "AlignModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "EfficientNetImageProcessor" + ], + "model_classes": [ + "AlignModel" + ], + "sha": "68a4f9d3f493f44efa7c1dde6fcca23350e2c92b" + }, + "AltCLIPModel": { + "tokenizer_classes": [ + "XLMRobertaTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "AltCLIPModel" + ], + "sha": "3106af0fd503970717c05f27218e5cacf19ba872" + }, + "BarkModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BarkModel" + ], + "sha": "187e590fd87359cea47693e8cb11a604cd7b673c" + }, + "BartForCausalLM": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartForCausalLM" + ], + "sha": "c25526ac67d2dbe79fe5462af4b7908ca2fbc3ff" + }, + "BartForConditionalGeneration": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartForConditionalGeneration", + "TFBartForConditionalGeneration" + ], + "sha": "3a489a21e4b04705f4a6047924b7616a67be7e37" + }, + "BartForQuestionAnswering": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartForQuestionAnswering" + ], + "sha": "3ebf9aab39a57ceab55128d5fc6f61e4db0dadd4" + }, + "BartForSequenceClassification": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartForSequenceClassification", + "TFBartForSequenceClassification" + ], + "sha": "ea452fd9a928cfebd71723afa50feb20326917bc" + }, + "BartModel": { + "tokenizer_classes": [ + "BartTokenizer", + "BartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BartModel", + "TFBartModel" + ], + "sha": "e5df6d1aa75f03833b2df328b9c35463f73a421b" + }, + "BeitForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "BeitForImageClassification" + ], + "sha": "e997587bb890f82faad4bd25eb23d85ba21ecaaa" + }, + "BeitForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "BeitForSemanticSegmentation" + ], + "sha": "d4afa9e21e3fe5b087578ed68974d9b3ffc1fb22" + }, + "BeitModel": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "BeitModel" + ], + "sha": "5c4a051f0cca6f64d02c6168deb88413cae10d2c" + }, + "BertForMaskedLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForMaskedLM", + "TFBertForMaskedLM" + ], + "sha": "3e32baa52ce044c75edfb5c28abd51ee8d051282" + }, + "BertForMultipleChoice": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForMultipleChoice", + "TFBertForMultipleChoice" + ], + "sha": "0b8c3a6d411d1e19e5fd98d4d8631ae7616eeeaa" + }, + "BertForNextSentencePrediction": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForNextSentencePrediction", + "TFBertForNextSentencePrediction" + ], + "sha": "628e70debf8864bd0b63aff7901d17d9c4f7612c" + }, + "BertForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForPreTraining", + "TFBertForPreTraining" + ], + "sha": "c748ad37e6a200a6f64b2764191bfe13f976032f" + }, + "BertForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForQuestionAnswering", + "TFBertForQuestionAnswering" + ], + "sha": "4671ad0c21493b97c5eb2f0201192704c29876d5" + }, + "BertForSequenceClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForSequenceClassification", + "TFBertForSequenceClassification" + ], + "sha": "37a9d44022264c12bdf3ec257778f953b63d4aaf" + }, + "BertForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertForTokenClassification", + "TFBertForTokenClassification" + ], + "sha": "d7dc3a0793ff6dfcb794b21130ee0f185d2c61a2" + }, + "BertLMHeadModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertLMHeadModel", + "TFBertLMHeadModel" + ], + "sha": "b4e3acc1990f3e365ffddbd54b620a26d9fb4b09" + }, + "BertModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BertModel", + "TFBertModel" + ], + "sha": "3956d303d3cddf0708ff20660c1ea5f6ec30e434" + }, + "BigBirdForCausalLM": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForCausalLM" + ], + "sha": "5c7a487af5248d9c01b45d5481b7d7bb9b36e1b5" + }, + "BigBirdForMaskedLM": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForMaskedLM" + ], + "sha": "476ef8225c0f69270b577706ad4f1dda13e4dde5" + }, + "BigBirdForMultipleChoice": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForMultipleChoice" + ], + "sha": "cf93eaa1019987112c171a407745bc183a20513a" + }, + "BigBirdForPreTraining": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForPreTraining" + ], + "sha": "5fb9efa13334431e7c186a9fa314b89c4a1eee72" + }, + "BigBirdForQuestionAnswering": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForQuestionAnswering" + ], + "sha": "f82f88bd71fba819a8ffb0692915d3529e705417" + }, + "BigBirdForSequenceClassification": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForSequenceClassification" + ], + "sha": "ea398090858f9af93b54fc9a8d65cfed78ac27ff" + }, + "BigBirdForTokenClassification": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdForTokenClassification" + ], + "sha": "2cdea118999fa58ba9fb0162d99e2ffa146c3df1" + }, + "BigBirdModel": { + "tokenizer_classes": [ + "BigBirdTokenizer", + "BigBirdTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdModel" + ], + "sha": "9c55989f31df156194e6997606fb14d9897e0300" + }, + "BigBirdPegasusForCausalLM": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusForCausalLM" + ], + "sha": "49bc8816c666dee32e27cd8e00136b604eb85243" + }, + "BigBirdPegasusForConditionalGeneration": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusForConditionalGeneration" + ], + "sha": "e791aa6d1af5a76ca0926d95b1f28bd2d8adf376" + }, + "BigBirdPegasusForQuestionAnswering": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusForQuestionAnswering" + ], + "sha": "7650e076713ca707a37062adc8c9c1cd60dad7c7" + }, + "BigBirdPegasusForSequenceClassification": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusForSequenceClassification" + ], + "sha": "02500e8ebd9c53528750013fb963fbdc2be34034" + }, + "BigBirdPegasusModel": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BigBirdPegasusModel" + ], + "sha": "b07c5304dfba673cf8b9cf5cd1aa45fbfea1c2f3" + }, + "BioGptForCausalLM": { + "tokenizer_classes": [ + "BioGptTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BioGptForCausalLM" + ], + "sha": "07073b31da84054fd12226e3cae4cb3beb2547f9" + }, + "BioGptForSequenceClassification": { + "tokenizer_classes": [ + "BioGptTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BioGptForSequenceClassification" + ], + "sha": "8e18ad6218abd795e050dec324a8c827ccedacb4" + }, + "BioGptForTokenClassification": { + "tokenizer_classes": [ + "BioGptTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BioGptForTokenClassification" + ], + "sha": "67f8173c1a17273064d452a9031a51b67f327b6a" + }, + "BioGptModel": { + "tokenizer_classes": [ + "BioGptTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BioGptModel" + ], + "sha": "fe18551d0743538a990520b75707294ec57b4ebe" + }, + "BitBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "BitBackbone" + ], + "sha": "2f06f6b4395b6dce2b00ac839ff757410e743cd7" + }, + "BitForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "BitForImageClassification" + ], + "sha": "d0d8476f2d285ddda7c42c0d4a8e4bf6f5d2bfdf" + }, + "BitModel": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "BitModel" + ], + "sha": "30a8a9b1a6b253cc500c01cf41bc1fc9581ea5e5" + }, + "BlenderbotForCausalLM": { + "tokenizer_classes": [ + "BlenderbotTokenizer", + "BlenderbotTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotForCausalLM" + ], + "sha": "8aad2e13e8920bca3cf988ba45f8a7b008b51a81" + }, + "BlenderbotForConditionalGeneration": { + "tokenizer_classes": [ + "BlenderbotTokenizer", + "BlenderbotTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotForConditionalGeneration", + "TFBlenderbotForConditionalGeneration" + ], + "sha": "e8532878b9924fa02fb4b059b7f6e7fa372fff91" + }, + "BlenderbotModel": { + "tokenizer_classes": [ + "BlenderbotTokenizer", + "BlenderbotTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotModel", + "TFBlenderbotModel" + ], + "sha": "ff848a40c30ca98eb7c6870bbb02677d5af9db55" + }, + "BlenderbotSmallForCausalLM": { + "tokenizer_classes": [ + "BlenderbotSmallTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotSmallForCausalLM" + ], + "sha": "4c57c106630932eb9de4d76210a540d04616304d" + }, + "BlenderbotSmallForConditionalGeneration": { + "tokenizer_classes": [ + "BlenderbotSmallTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotSmallForConditionalGeneration", + "TFBlenderbotSmallForConditionalGeneration" + ], + "sha": "b8db01fcf3e37a5b369cd50e169bf383b8e905d8" + }, + "BlenderbotSmallModel": { + "tokenizer_classes": [ + "BlenderbotSmallTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "BlenderbotSmallModel", + "TFBlenderbotSmallModel" + ], + "sha": "0a10c70e225ec63278faffa8fabf759f063f0e55" + }, + "Blip2ForConditionalGeneration": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [ + "BlipImageProcessor" + ], + "model_classes": [ + "Blip2ForConditionalGeneration" + ], + "sha": "d0de11fd1f8ca481231c07ee0934924be96cb281" + }, + "Blip2Model": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [ + "BlipImageProcessor" + ], + "model_classes": [ + "Blip2Model" + ], + "sha": "c23378f225be31872fff33c103cf0ebc2454ffcc" + }, + "BlipForConditionalGeneration": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "BlipImageProcessor" + ], + "model_classes": [ + "BlipForConditionalGeneration", + "TFBlipForConditionalGeneration" + ], + "sha": "eaf32bc0369349deef0c777442fc185119171d1f" + }, + "BlipModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "BlipImageProcessor" + ], + "model_classes": [ + "BlipModel", + "TFBlipModel" + ], + "sha": "3d1d1c15eff22d6b2664a2d15757fa6f5d93827d" + }, + "BloomForCausalLM": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomForCausalLM" + ], + "sha": "0f4f06f162cd67d34d03ee156484e4001d468500" + }, + "BloomForQuestionAnswering": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomForQuestionAnswering" + ], + "sha": "23f369f163eef8c9c9685900440b0cbb0f3439fd" + }, + "BloomForSequenceClassification": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomForSequenceClassification" + ], + "sha": "b2280eef7172835f39b265eb0c46623257f67bbe" + }, + "BloomForTokenClassification": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomForTokenClassification" + ], + "sha": "9796aa45f99adff987c978089e11c0bd9d7b997f" + }, + "BloomModel": { + "tokenizer_classes": [ + "BloomTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BloomModel" + ], + "sha": "28b600fcfdc4f4938406fb518abf895620048cb2" + }, + "BrosForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BrosForTokenClassification" + ], + "sha": "4ec2c91936f96b93667e8946fc7abbdeeb08a6d7" + }, + "BrosModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "BrosModel" + ], + "sha": "e2464830b1874eeaf9f4b425fbe0ce8e7c7643e9" + }, + "CLIPModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "CLIPModel", + "TFCLIPModel" + ], + "sha": "0452d344074485d0e7eb5d5c12447b7c9dbc9619" + }, + "CLIPSegModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "CLIPSegModel" + ], + "sha": "7b1305214ccc85d29b776ffbee06748693852a04" + }, + "CTRLForSequenceClassification": { + "tokenizer_classes": [ + "CTRLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CTRLForSequenceClassification", + "TFCTRLForSequenceClassification" + ], + "sha": "280b5a3502d607c55c9f8d9f198fe9c2802d6f73" + }, + "CTRLLMHeadModel": { + "tokenizer_classes": [ + "CTRLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CTRLLMHeadModel", + "TFCTRLLMHeadModel" + ], + "sha": "662381663b216f1dd3c9cd30e2e83cb4c6fc9552" + }, + "CTRLModel": { + "tokenizer_classes": [ + "CTRLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CTRLModel", + "TFCTRLModel" + ], + "sha": "68b19b4f132d5a191a73acd78d983cbdcf068e9c" + }, + "CanineForMultipleChoice": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineForMultipleChoice" + ], + "sha": "fa0451453ed202f903ff7dcf6071aab6630fb89f" + }, + "CanineForQuestionAnswering": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineForQuestionAnswering" + ], + "sha": "5e1012bb086ac2e0b1497eeb7ed14eb2183d4ecb" + }, + "CanineForSequenceClassification": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineForSequenceClassification" + ], + "sha": "75336dc9179153869c38a8047ce4b1e02677a260" + }, + "CanineForTokenClassification": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineForTokenClassification" + ], + "sha": "65a622ea8e12597e12f45e59d46d8dbe8461fc10" + }, + "CanineModel": { + "tokenizer_classes": [ + "CanineTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "CanineModel" + ], + "sha": "531ef67ad4f0b3dc7a9e5d722c774096b7401b1b" + }, + "ChineseCLIPModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "ChineseCLIPImageProcessor" + ], + "model_classes": [ + "ChineseCLIPModel" + ], + "sha": "504271a3c5fd9c2e877f5b4c01848bc18778c7c3" + }, + "ClapModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [ + "ClapFeatureExtractor" + ], + "model_classes": [ + "ClapModel" + ], + "sha": "a7874595b900f9b2ddc79130dafc3ff48f4fbfb9" + }, + "ClvpModelForConditionalGeneration": { + "tokenizer_classes": [ + "ClvpTokenizer" + ], + "processor_classes": [ + "ClvpFeatureExtractor" + ], + "model_classes": [], + "sha": "45df7581535be337ff781707b6c20994ca221f05" + }, + "CodeGenForCausalLM": { + "tokenizer_classes": [ + "CodeGenTokenizer", + "CodeGenTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "CodeGenForCausalLM" + ], + "sha": "a3fc69d757fd1f0aa01bcbc4337f586651c7cb10" + }, + "CodeGenModel": { + "tokenizer_classes": [ + "CodeGenTokenizer", + "CodeGenTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "CodeGenModel" + ], + "sha": "dad4941a2b7429fc6e8206fcc4a04fc40f4a0beb" + }, + "ConditionalDetrForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "ConditionalDetrImageProcessor" + ], + "model_classes": [ + "ConditionalDetrForObjectDetection" + ], + "sha": "762c213a0285edc84eb813a2ed90063cf971ca43" + }, + "ConditionalDetrModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConditionalDetrImageProcessor" + ], + "model_classes": [ + "ConditionalDetrModel" + ], + "sha": "18b75874158cac520c63605293b06e0b1327c263" + }, + "ConvBertForMaskedLM": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForMaskedLM", + "TFConvBertForMaskedLM" + ], + "sha": "307c70e32c3d3c18aeb45e0cbdc9fcd2957d9aba" + }, + "ConvBertForMultipleChoice": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForMultipleChoice", + "TFConvBertForMultipleChoice" + ], + "sha": "d6561a21ffdb82d03c1822af0510eb7482ce5026" + }, + "ConvBertForQuestionAnswering": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForQuestionAnswering", + "TFConvBertForQuestionAnswering" + ], + "sha": "8a056da5cc421415c2a24b9f644dd95ca279411d" + }, + "ConvBertForSequenceClassification": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForSequenceClassification", + "TFConvBertForSequenceClassification" + ], + "sha": "8bb8b20e51d282d777cc567cacadd97a35f0811e" + }, + "ConvBertForTokenClassification": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertForTokenClassification", + "TFConvBertForTokenClassification" + ], + "sha": "8db0dd3c2b8ccc958fa9a84801f4f837b42fcf2c" + }, + "ConvBertModel": { + "tokenizer_classes": [ + "ConvBertTokenizer", + "ConvBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ConvBertModel", + "TFConvBertModel" + ], + "sha": "c9c5b1a74f0e468d8467473cabeaa67fcdbaddb7" + }, + "ConvNextBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextBackbone" + ], + "sha": "499c7d6a97825b79e19663b70f3b60c4813b6bf2" + }, + "ConvNextForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextForImageClassification", + "TFConvNextForImageClassification" + ], + "sha": "0b490fd6b19cdbf721025dbd6ee45dcc5828e6e3" + }, + "ConvNextModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextModel", + "TFConvNextModel" + ], + "sha": "7b3b47a57b9a9120e022b91d6067daeac55b794f" + }, + "ConvNextV2Backbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextV2Backbone" + ], + "sha": "c82fc526949dfd892a1fee3c34be6f8d80c4d3df" + }, + "ConvNextV2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextV2ForImageClassification", + "TFConvNextV2ForImageClassification" + ], + "sha": "ee22bae1cbb87d66fc7f62f7e15a43d6ff80d3cc" + }, + "ConvNextV2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ConvNextV2Model", + "TFConvNextV2Model" + ], + "sha": "c4dd68ee1102cba05bcc483da2a88e39427b7249" + }, + "CvtForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "CvtForImageClassification", + "TFCvtForImageClassification" + ], + "sha": "4b1938e252fdb26a06c1f5755e07fa8f6eed2d75" + }, + "CvtModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "CvtModel", + "TFCvtModel" + ], + "sha": "27fed12c174f4f4f1fe27075d1c29602fe0669f0" + }, + "DPRQuestionEncoder": { + "tokenizer_classes": [ + "DPRQuestionEncoderTokenizer", + "DPRQuestionEncoderTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DPRQuestionEncoder", + "TFDPRQuestionEncoder" + ], + "sha": "09ae0269780271e0a4916f7bab1dbc4f8a76070d" + }, + "DPTForDepthEstimation": { + "tokenizer_classes": [], + "processor_classes": [ + "DPTImageProcessor" + ], + "model_classes": [ + "DPTForDepthEstimation" + ], + "sha": "11b7735d64d95b6599811631b012d2dec6eaa2c1" + }, + "DPTForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "DPTImageProcessor" + ], + "model_classes": [ + "DPTForSemanticSegmentation" + ], + "sha": "e140c3c716a4bf11dad875e5f5f0abd2bd4cbbcb" + }, + "DPTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DPTImageProcessor" + ], + "model_classes": [ + "DPTModel" + ], + "sha": "1d6ae6c0b60868dffbef0dddeda381c51c6dcba5" + }, + "Data2VecAudioForAudioFrameClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioForAudioFrameClassification" + ], + "sha": "a64828b27e73fc8dd95aeb315108ca2f6a66b55f" + }, + "Data2VecAudioForCTC": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioForCTC" + ], + "sha": "bb161b6a181bd2c22cf30222f46fa6ef42225744" + }, + "Data2VecAudioForSequenceClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioForSequenceClassification" + ], + "sha": "8de17e0a959eca5f72b2ea59a11bc1fa744785d9" + }, + "Data2VecAudioForXVector": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioForXVector" + ], + "sha": "dcb92484cf28fb4fe1dcf5d6e8d78e04382fdce9" + }, + "Data2VecAudioModel": { + "tokenizer_classes": [], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Data2VecAudioModel" + ], + "sha": "73f503fdff73b7616154f64dbe38a685cc48e8eb" + }, + "Data2VecTextForCausalLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForCausalLM" + ], + "sha": "1f3658ce623653338cd31516551e8181aa08bb38" + }, + "Data2VecTextForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForMaskedLM" + ], + "sha": "fb41ac30d0faa0899bf5afaa0986df8993395ca6" + }, + "Data2VecTextForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForMultipleChoice" + ], + "sha": "e7556d520ad90ebae5ad88554d45a37488d00040" + }, + "Data2VecTextForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForQuestionAnswering" + ], + "sha": "9630833d76a1fd7e96b904d87bb11b7c00ccd021" + }, + "Data2VecTextForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForSequenceClassification" + ], + "sha": "156e4019c37d9592f193ba80553cd245cbccecb3" + }, + "Data2VecTextForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextForTokenClassification" + ], + "sha": "55b3a49fdbf22479d6eb939261d4b884ea288270" + }, + "Data2VecTextModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "Data2VecTextModel" + ], + "sha": "c21be3e4f88e8357bf33bfba8f8e05ae2e735124" + }, + "Data2VecVisionForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "Data2VecVisionForImageClassification", + "TFData2VecVisionForImageClassification" + ], + "sha": "d640e7ced7a3fbbb8c8661a4f67b934e55406172" + }, + "Data2VecVisionForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "Data2VecVisionForSemanticSegmentation", + "TFData2VecVisionForSemanticSegmentation" + ], + "sha": "3eba3cd694fab6530b7e5da8f49d3951301c816a" + }, + "Data2VecVisionModel": { + "tokenizer_classes": [], + "processor_classes": [ + "BeitImageProcessor" + ], + "model_classes": [ + "Data2VecVisionModel", + "TFData2VecVisionModel" + ], + "sha": "2a7ad25e4359970dc70494a2f3eb98e2a3c9806d" + }, + "DebertaForMaskedLM": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaForMaskedLM", + "TFDebertaForMaskedLM" + ], + "sha": "e0f9ada9e0f6d4d7cc39d7cbd58369b0c84de33d" + }, + "DebertaForQuestionAnswering": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaForQuestionAnswering", + "TFDebertaForQuestionAnswering" + ], + "sha": "a3eb69cdb0b52f7d0fb730e882f1a54b9a7442ea" + }, + "DebertaForSequenceClassification": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaForSequenceClassification", + "TFDebertaForSequenceClassification" + ], + "sha": "32af91d12c4e9b6d62b420bee93311fd77d3c933" + }, + "DebertaForTokenClassification": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaForTokenClassification", + "TFDebertaForTokenClassification" + ], + "sha": "ba62ba2726d813e60e512476fc1b178aa3858175" + }, + "DebertaModel": { + "tokenizer_classes": [ + "DebertaTokenizer", + "DebertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaModel", + "TFDebertaModel" + ], + "sha": "4273294e14cd04c0e2cd1dcff5cf7e5d4fe906ba" + }, + "DebertaV2ForMaskedLM": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForMaskedLM", + "TFDebertaV2ForMaskedLM" + ], + "sha": "a053dedc2cdf32918a84277cb0c05186604496a5" + }, + "DebertaV2ForMultipleChoice": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForMultipleChoice", + "TFDebertaV2ForMultipleChoice" + ], + "sha": "07e39f520ce239b39ef8cb24cd7874d06c791063" + }, + "DebertaV2ForQuestionAnswering": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForQuestionAnswering", + "TFDebertaV2ForQuestionAnswering" + ], + "sha": "9cecb3a7fc6b95099122283644ea1f8ced287d1b" + }, + "DebertaV2ForSequenceClassification": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForSequenceClassification", + "TFDebertaV2ForSequenceClassification" + ], + "sha": "df9ea1f5c0f2ccd139b21cfb3963a5a5ebfb5b81" + }, + "DebertaV2ForTokenClassification": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2ForTokenClassification", + "TFDebertaV2ForTokenClassification" + ], + "sha": "51fe01989df38a540ac1abca5ee71a51365defd5" + }, + "DebertaV2Model": { + "tokenizer_classes": [ + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DebertaV2Model", + "TFDebertaV2Model" + ], + "sha": "211df4bd1a4a9b66c97af3f9231a5d2af8de7b9f" + }, + "DeformableDetrForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "DeformableDetrImageProcessor" + ], + "model_classes": [ + "DeformableDetrForObjectDetection" + ], + "sha": "8fa0db215c458f60ae4d455d6fb067c1c5e39fdc" + }, + "DeformableDetrModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DeformableDetrImageProcessor" + ], + "model_classes": [ + "DeformableDetrModel" + ], + "sha": "0faac5624696b03edd14694642f9804f2cd8f3da" + }, + "DeiTForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "DeiTImageProcessor" + ], + "model_classes": [ + "DeiTForImageClassification", + "TFDeiTForImageClassification" + ], + "sha": "21fc864199dafa0130f16a45769c6b6ca22c7784" + }, + "DeiTForImageClassificationWithTeacher": { + "tokenizer_classes": [], + "processor_classes": [ + "DeiTImageProcessor" + ], + "model_classes": [ + "DeiTForImageClassificationWithTeacher", + "TFDeiTForImageClassificationWithTeacher" + ], + "sha": "5a5738a109e27f3d4b78a0db4cb1d3331140c10e" + }, + "DeiTForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "DeiTImageProcessor" + ], + "model_classes": [ + "DeiTForMaskedImageModeling", + "TFDeiTForMaskedImageModeling" + ], + "sha": "d5df5c538fe1efb8d668a3893d1691d505a0de06" + }, + "DeiTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DeiTImageProcessor" + ], + "model_classes": [ + "DeiTModel", + "TFDeiTModel" + ], + "sha": "0fdbff6f44b7c6933c2027fec1d7f87bec06b590" + }, + "DetaForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "DetaImageProcessor" + ], + "model_classes": [ + "DetaForObjectDetection" + ], + "sha": "a15ad6ce64fbcb5021b2b99e9587c4011ef3341d" + }, + "DetaModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DetaImageProcessor" + ], + "model_classes": [ + "DetaModel" + ], + "sha": "8820f2297ec0dec8f1875054559c8b7a162098e3" + }, + "DetrForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "DetrForObjectDetection" + ], + "sha": "7dc967c53f4b3f07904c42b255346b744d0ad84e" + }, + "DetrForSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "DetrForSegmentation" + ], + "sha": "e34330acdae359588ef853e961a78d419dc4e8eb" + }, + "DetrModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "DetrModel" + ], + "sha": "f15ce38a10c7447e8048b1681e4811322a005722" + }, + "DinatBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "DinatBackbone" + ], + "sha": "3ba13790a0796d90104c207f75bb3d5d79723d51" + }, + "DinatForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "DinatForImageClassification" + ], + "sha": "624cf2d864a7ea2f90e24014a213e34597e8bd76" + }, + "DinatModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "DinatModel" + ], + "sha": "d6c75bc51196f0a683afb12de6310fdda13efefd" + }, + "Dinov2Backbone": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "Dinov2Backbone" + ], + "sha": "dbf8d2ff3092ac53c11e6525e6cbae7ace84769a" + }, + "Dinov2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "Dinov2ForImageClassification" + ], + "sha": "ae44840966456aae33641df2c8c8a4af5b457b24" + }, + "Dinov2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "Dinov2Model" + ], + "sha": "6f560b1cc9806bcf84fe0b0c60b5faf9c29be959" + }, + "DistilBertForMaskedLM": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForMaskedLM", + "TFDistilBertForMaskedLM" + ], + "sha": "b2dfda30b012821996e6e603729562d9c900bc0f" + }, + "DistilBertForMultipleChoice": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForMultipleChoice", + "TFDistilBertForMultipleChoice" + ], + "sha": "ec6b83129a7d1be2a6b8d58303abcca5541a5cb3" + }, + "DistilBertForQuestionAnswering": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForQuestionAnswering", + "TFDistilBertForQuestionAnswering" + ], + "sha": "812406b226415044469b0e0a84c4fe0ff338c5d3" + }, + "DistilBertForSequenceClassification": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForSequenceClassification", + "TFDistilBertForSequenceClassification" + ], + "sha": "6f427ce7b3e5aaa596938fbd98437d3875581b7b" + }, + "DistilBertForTokenClassification": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertForTokenClassification", + "TFDistilBertForTokenClassification" + ], + "sha": "166dbe3f5d6ecd871762567069454d6ec65234b4" + }, + "DistilBertModel": { + "tokenizer_classes": [ + "DistilBertTokenizer", + "DistilBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "DistilBertModel", + "TFDistilBertModel" + ], + "sha": "cc4425ad0676f3ec00e8bffe485fe83cae61041a" + }, + "DonutSwinModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DonutImageProcessor" + ], + "model_classes": [ + "DonutSwinModel" + ], + "sha": "1b10654fbfe2f2ea410a672ab605bd5c60d3f284" + }, + "EfficientFormerForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientFormerImageProcessor" + ], + "model_classes": [ + "EfficientFormerForImageClassification", + "TFEfficientFormerForImageClassification" + ], + "sha": "ebadb628e12f268e321fcc756fa4606f7b5b3178" + }, + "EfficientFormerForImageClassificationWithTeacher": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientFormerImageProcessor" + ], + "model_classes": [ + "EfficientFormerForImageClassificationWithTeacher", + "TFEfficientFormerForImageClassificationWithTeacher" + ], + "sha": "1beabce6da9cb4ebbeafcd1ef23fac36b4a269e2" + }, + "EfficientFormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientFormerImageProcessor" + ], + "model_classes": [ + "EfficientFormerModel", + "TFEfficientFormerModel" + ], + "sha": "200fae5b875844d09c8a91d1c155b72b06a517f6" + }, + "EfficientNetForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientNetImageProcessor" + ], + "model_classes": [ + "EfficientNetForImageClassification" + ], + "sha": "993d088cf937b8a90b61f68677cd8f261321c745" + }, + "EfficientNetModel": { + "tokenizer_classes": [], + "processor_classes": [ + "EfficientNetImageProcessor" + ], + "model_classes": [ + "EfficientNetModel" + ], + "sha": "eb03c90d4aaad98af0f19e0dfbdc41106297ffff" + }, + "ElectraForCausalLM": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForCausalLM" + ], + "sha": "c78396bc8cdd8db247892339de8da80d691d1d04" + }, + "ElectraForMaskedLM": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForMaskedLM", + "TFElectraForMaskedLM" + ], + "sha": "631337703dbd8d41904c39891a41c6f1edd31813" + }, + "ElectraForMultipleChoice": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForMultipleChoice", + "TFElectraForMultipleChoice" + ], + "sha": "66fdea6e22cfcbd3caa49ea82f31871c460612fa" + }, + "ElectraForPreTraining": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForPreTraining", + "TFElectraForPreTraining" + ], + "sha": "7b2d0fa8726b1180c7d6cde4f4afc3800eba7e6f" + }, + "ElectraForQuestionAnswering": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForQuestionAnswering", + "TFElectraForQuestionAnswering" + ], + "sha": "c6b127fd9f3019462e4ca2373762836207e39ce2" + }, + "ElectraForSequenceClassification": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForSequenceClassification", + "TFElectraForSequenceClassification" + ], + "sha": "41f0089ab7876abe0e28dbbd565144acb31f8127" + }, + "ElectraForTokenClassification": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraForTokenClassification", + "TFElectraForTokenClassification" + ], + "sha": "1fdbbe70c1ddd16503820a1443d6a379a15ed777" + }, + "ElectraModel": { + "tokenizer_classes": [ + "ElectraTokenizer", + "ElectraTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ElectraModel", + "TFElectraModel" + ], + "sha": "312b532cbef26610d80f2bd008650160cae4f7a1" + }, + "EncodecModel": { + "tokenizer_classes": [], + "processor_classes": [ + "EncodecFeatureExtractor" + ], + "model_classes": [ + "EncodecModel" + ], + "sha": "e14c5a2fd6529c85cd4ac5a05ee9e550ced6a006" + }, + "EncoderDecoderModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "EncoderDecoderModel", + "TFEncoderDecoderModel" + ], + "sha": "1038be9fd1b87b2e0a8f33721ff8e4612d34b3b6" + }, + "ErnieForCausalLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForCausalLM" + ], + "sha": "b49e00112ff06c2f0a0e54499921dddcf8c3c6a8" + }, + "ErnieForMaskedLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForMaskedLM" + ], + "sha": "30429830d1997222d885dcfdbd36d5e02d0d34b1" + }, + "ErnieForMultipleChoice": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForMultipleChoice" + ], + "sha": "5a21144bf35dfb60560ff8249116ad4459c0069a" + }, + "ErnieForNextSentencePrediction": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForNextSentencePrediction" + ], + "sha": "ed5868efb39bf6afb29f0cf444deafcf1e50b5bc" + }, + "ErnieForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForPreTraining" + ], + "sha": "e4ad30d291c310fea25e6f91f91393f993513b42" + }, + "ErnieForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForQuestionAnswering" + ], + "sha": "fe7c74b763f63a9fd864dad325385075df7c80c8" + }, + "ErnieForSequenceClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForSequenceClassification" + ], + "sha": "84e0be05fcd52f54e96a69f67a2481323a58a9db" + }, + "ErnieForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieForTokenClassification" + ], + "sha": "91cf62c43a5a83332552ffa2d8e5e44d63a224ea" + }, + "ErnieMForMultipleChoice": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMForMultipleChoice" + ], + "sha": "c42ee7fcb132a323ace314c32e63c8a7d36ce18f" + }, + "ErnieMForQuestionAnswering": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMForQuestionAnswering" + ], + "sha": "2b90dee75ca87b214f96db00002aa18244ec8e84" + }, + "ErnieMForSequenceClassification": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMForSequenceClassification" + ], + "sha": "d8368646d8b1c67b1460af9c6ec13fd9d894cae6" + }, + "ErnieMForTokenClassification": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMForTokenClassification" + ], + "sha": "a9e29ba60fa0b7bedc2ed26a6b9911427df1ca6b" + }, + "ErnieMModel": { + "tokenizer_classes": [ + "ErnieMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ErnieMModel" + ], + "sha": "7306eac3f38c3cf6211f0e741fdb81c6cc92bc09" + }, + "ErnieModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ErnieModel" + ], + "sha": "b51478a9f40e353c41be3a29ccef103dcfe22b4b" + }, + "EsmForMaskedLM": { + "tokenizer_classes": [ + "EsmTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "EsmForMaskedLM", + "TFEsmForMaskedLM" + ], + "sha": "b56297b6cd64b9ba7c613d0cd146f1ecbea8115e" + }, + "EsmForSequenceClassification": { + "tokenizer_classes": [ + "EsmTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "EsmForSequenceClassification", + "TFEsmForSequenceClassification" + ], + "sha": "cc6d7ef0a4763540d67b7a4fb31bede9a7d3f245" + }, + "EsmForTokenClassification": { + "tokenizer_classes": [ + "EsmTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "EsmForTokenClassification", + "TFEsmForTokenClassification" + ], + "sha": "498953f66e260b974c504abbc863ee266d6c84a9" + }, + "EsmModel": { + "tokenizer_classes": [ + "EsmTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "EsmModel", + "TFEsmModel" + ], + "sha": "183838263b70809310117a0761542501acf64c21" + }, + "FNetForMaskedLM": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForMaskedLM" + ], + "sha": "91eaae1eac894af5d96c0221ec9bcef7f1af41c8" + }, + "FNetForMultipleChoice": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForMultipleChoice" + ], + "sha": "c15d98d5f7a6f3ef3099b1257949bee208d5466e" + }, + "FNetForNextSentencePrediction": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForNextSentencePrediction" + ], + "sha": "c59440b44d07d61fc45a90ded7fc11d6f25b143d" + }, + "FNetForPreTraining": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForPreTraining" + ], + "sha": "c05f55ccfb2f2533babd3c6e99de7749bc8081da" + }, + "FNetForQuestionAnswering": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForQuestionAnswering" + ], + "sha": "47788e49dd435653fa2aa4b3ccae3572a870758e" + }, + "FNetForSequenceClassification": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForSequenceClassification" + ], + "sha": "a3049b896ea6c5a32c364989c3afe604ee58b9fc" + }, + "FNetForTokenClassification": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetForTokenClassification" + ], + "sha": "3bcdafca57d544bb81e2f7eead1e512c168582fc" + }, + "FNetModel": { + "tokenizer_classes": [ + "FNetTokenizer", + "FNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FNetModel" + ], + "sha": "48fa66de37df126504db3b658806135eb877f505" + }, + "FSMTForConditionalGeneration": { + "tokenizer_classes": [ + "FSMTTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FSMTForConditionalGeneration" + ], + "sha": "6a1a981b29c8a98c1fd31bd0ad809f5575ca6c7a" + }, + "FSMTModel": { + "tokenizer_classes": [ + "FSMTTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FSMTModel" + ], + "sha": "683f6f73a2ab87801f1695a72d1af63cf173ab7c" + }, + "FalconForCausalLM": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconForCausalLM" + ], + "sha": "60076d5dafc5e33ba9c90dcd05e7c0834e44049a" + }, + "FalconForQuestionAnswering": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconForQuestionAnswering" + ], + "sha": "b1ee9cd5fad2d177ea5a46df4611cd02f66ae788" + }, + "FalconForSequenceClassification": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconForSequenceClassification" + ], + "sha": "007838c0991c2b6a87dc49a8a5c20f29149a00fa" + }, + "FalconForTokenClassification": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconForTokenClassification" + ], + "sha": "0ea6ae548773daa6e3317fddc058957e956eebf4" + }, + "FalconModel": { + "tokenizer_classes": [ + "PreTrainedTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FalconModel" + ], + "sha": "ca15a579c946eb00c5b39cc8e0ea63d0c1460f84" + }, + "FlaubertForMultipleChoice": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertForMultipleChoice", + "TFFlaubertForMultipleChoice" + ], + "sha": "8b12bd87a63f2e86c3482431742f6d8abf6ec4fd" + }, + "FlaubertForQuestionAnsweringSimple": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertForQuestionAnsweringSimple", + "TFFlaubertForQuestionAnsweringSimple" + ], + "sha": "5c0e7ad1efae7e3497f5cd6d2d9519403df49d37" + }, + "FlaubertForSequenceClassification": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertForSequenceClassification", + "TFFlaubertForSequenceClassification" + ], + "sha": "762f12a8c99690be8ed2663b7af3011660174a7c" + }, + "FlaubertForTokenClassification": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertForTokenClassification", + "TFFlaubertForTokenClassification" + ], + "sha": "d2ab741c937bb69ef27c89e4c86a8c9d444874ca" + }, + "FlaubertModel": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertModel", + "TFFlaubertModel" + ], + "sha": "bdc2f8e17bb869393053429ec8c1c842bfeabb07" + }, + "FlaubertWithLMHeadModel": { + "tokenizer_classes": [ + "FlaubertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "FlaubertWithLMHeadModel", + "TFFlaubertWithLMHeadModel" + ], + "sha": "f20eb0932c90061003c9cc4e109c6ea22559c4f2" + }, + "FlavaForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "FlavaImageProcessor" + ], + "model_classes": [ + "FlavaForPreTraining" + ], + "sha": "6e9b2094060a5fa27984c7b49e5d0e820a88b487" + }, + "FlavaModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "FlavaImageProcessor" + ], + "model_classes": [ + "FlavaModel" + ], + "sha": "31ebf1b7a0ef1fd5059b98e28e5ab1c366d2c482" + }, + "FocalNetBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "FocalNetBackbone" + ], + "sha": "eb8c580969443cb87de7dd9a256deaface03692f" + }, + "FocalNetForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "FocalNetForImageClassification" + ], + "sha": "28d30ded26a3213e8fb7011a455afc3aa98b0a95" + }, + "FocalNetForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "FocalNetForMaskedImageModeling" + ], + "sha": "0ea7626d19c9dd2f3113d977f643a1babc720bd3" + }, + "FocalNetModel": { + "tokenizer_classes": [], + "processor_classes": [ + "BitImageProcessor" + ], + "model_classes": [ + "FocalNetModel" + ], + "sha": "107b004e6aa14108a359b7d22bdb9aa141ec05d5" + }, + "FunnelBaseModel": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelBaseModel", + "TFFunnelBaseModel" + ], + "sha": "87fed4252812df23315a56531625333e315681c6" + }, + "FunnelForMaskedLM": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForMaskedLM", + "TFFunnelForMaskedLM" + ], + "sha": "5543daf29f185cd45f2599bd6f38c96064c9c8de" + }, + "FunnelForMultipleChoice": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForMultipleChoice", + "TFFunnelForMultipleChoice" + ], + "sha": "a8bf597e37dbefb1ac5c97c4cb162c3d522a33a1" + }, + "FunnelForPreTraining": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForPreTraining", + "TFFunnelForPreTraining" + ], + "sha": "cbcb300d60aacd5950a45409b6e3f0f240c9082e" + }, + "FunnelForQuestionAnswering": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForQuestionAnswering", + "TFFunnelForQuestionAnswering" + ], + "sha": "6a5675305e096434e818486a13892cb55daffd13" + }, + "FunnelForSequenceClassification": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForSequenceClassification", + "TFFunnelForSequenceClassification" + ], + "sha": "1bc557a1e4314da21a44dee57b799e95a7025e5c" + }, + "FunnelForTokenClassification": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelForTokenClassification", + "TFFunnelForTokenClassification" + ], + "sha": "693bc1217a224efd558f410ddc8ffc63739bebc3" + }, + "FunnelModel": { + "tokenizer_classes": [ + "FunnelTokenizer", + "FunnelTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "FunnelModel", + "TFFunnelModel" + ], + "sha": "bfbaa8fa21c3abf80b94e7168b5ecff8ec5b5f76" + }, + "FuyuForCausalLM": { + "tokenizer_classes": [ + "LlamaTokenizerFast" + ], + "processor_classes": [ + "FuyuImageProcessor" + ], + "model_classes": [ + "FuyuForCausalLM" + ], + "sha": "685d78258ea95c5c82e0e4555d0d4a2270ab8bff" + }, + "GLPNForDepthEstimation": { + "tokenizer_classes": [], + "processor_classes": [ + "GLPNImageProcessor" + ], + "model_classes": [ + "GLPNForDepthEstimation" + ], + "sha": "32ca1c1ef5d33242e5e7c0433bcd773c082f0260" + }, + "GLPNModel": { + "tokenizer_classes": [], + "processor_classes": [ + "GLPNImageProcessor" + ], + "model_classes": [ + "GLPNModel" + ], + "sha": "24a8dbb48b1aa0ba2eba44324fcd0c78cca64dd4" + }, + "GPT2ForQuestionAnswering": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2ForQuestionAnswering" + ], + "sha": "a5bdd6bd4d79feece85ea9a8bd4ee5fe54c1d45b" + }, + "GPT2ForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2ForSequenceClassification", + "TFGPT2ForSequenceClassification" + ], + "sha": "90a2d78e5c7f288152f8456c3d58a43b40a58449" + }, + "GPT2ForTokenClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2ForTokenClassification" + ], + "sha": "da78bc95b45fab2da9d43f2ca27164996e31ade1" + }, + "GPT2LMHeadModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2LMHeadModel", + "TFGPT2LMHeadModel" + ], + "sha": "78f56535d4ce19e9d7c0992e390085c5a4196b37" + }, + "GPT2Model": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPT2Model", + "TFGPT2Model" + ], + "sha": "d6694b0d8fe17978761c9305dc151780506b192e" + }, + "GPTBigCodeForCausalLM": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTBigCodeForCausalLM" + ], + "sha": "99f7aaadf9c29669c63ef6c16f6bc5c07dbb9126" + }, + "GPTBigCodeForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTBigCodeForSequenceClassification" + ], + "sha": "64a7398d5763161037b818314c60dd83d93d03e9" + }, + "GPTBigCodeForTokenClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTBigCodeForTokenClassification" + ], + "sha": "310537ecd22d45f71bf594b17922cf2abc338eaf" + }, + "GPTBigCodeModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTBigCodeModel" + ], + "sha": "3069419084a9dc36802d47de9df3d314ccfc2f28" + }, + "GPTJForCausalLM": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTJForCausalLM", + "TFGPTJForCausalLM" + ], + "sha": "1fff390baa45cb187903ebdd269c975bb9ed7386" + }, + "GPTJForQuestionAnswering": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTJForQuestionAnswering", + "TFGPTJForQuestionAnswering" + ], + "sha": "3d4ec61dbed01f844d4c309971eeb5ad722c6c84" + }, + "GPTJForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTJForSequenceClassification", + "TFGPTJForSequenceClassification" + ], + "sha": "4b5db259cd16ca84ae2cd79aa4851cdd14479128" + }, + "GPTJModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTJModel", + "TFGPTJModel" + ], + "sha": "d8e1db30d08fbf57da6fc139aea3ffd63ab6226e" + }, + "GPTNeoForCausalLM": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoForCausalLM" + ], + "sha": "e88934e402c15195dd99b2947632415dd7645268" + }, + "GPTNeoForQuestionAnswering": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoForQuestionAnswering" + ], + "sha": "623883e94bd08caf9b3f839b98debeea72d5bc2b" + }, + "GPTNeoForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoForSequenceClassification" + ], + "sha": "bf2090d5d91a70eb37ba51fbdcf23afc7031fea8" + }, + "GPTNeoForTokenClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoForTokenClassification" + ], + "sha": "d5208e73e24a1671219776b50fe5f96e0e4cd218" + }, + "GPTNeoModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoModel" + ], + "sha": "72a7cd49da613c3125a90884df4763545c594e56" + }, + "GPTNeoXForCausalLM": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXForCausalLM" + ], + "sha": "0229cfaaa843c6b492ac2abffabb00f1ff1936f8" + }, + "GPTNeoXForQuestionAnswering": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXForQuestionAnswering" + ], + "sha": "7d2f08c959c211129952ee03b5562add09fe6864" + }, + "GPTNeoXForSequenceClassification": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXForSequenceClassification" + ], + "sha": "17c4b845ee2e0bb780ca2dea2d59a3d9d5d3c651" + }, + "GPTNeoXForTokenClassification": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXForTokenClassification" + ], + "sha": "3aa4fe8a562f32230041d6d3616aa5ecc3f30192" + }, + "GPTNeoXJapaneseForCausalLM": { + "tokenizer_classes": [ + "GPTNeoXJapaneseTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXJapaneseForCausalLM" + ], + "sha": "5fca2479f1064fd22e17f944c8fcc14f7e73f1d5" + }, + "GPTNeoXJapaneseModel": { + "tokenizer_classes": [ + "GPTNeoXJapaneseTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXJapaneseModel" + ], + "sha": "5c6ed124150df845cfc701d70b97fdcde687be52" + }, + "GPTNeoXModel": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "GPTNeoXModel" + ], + "sha": "33114ba2f72189d5a2bd63f0cdb78551189242ff" + }, + "GPTSanJapaneseForConditionalGeneration": { + "tokenizer_classes": [ + "GPTSanJapaneseTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "GPTSanJapaneseForConditionalGeneration" + ], + "sha": "ff6a41faaa713c7fbd5d9a1a50539745f9e1178e" + }, + "GitForCausalLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "GitForCausalLM" + ], + "sha": "60f9c50466ae0beeb11776ca5bfeb6473f441554" + }, + "GitModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "GitModel" + ], + "sha": "3d2eb6bddf95bb4a4e59b045d4e464c730c07f41" + }, + "GroupViTModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "GroupViTModel", + "TFGroupViTModel" + ], + "sha": "05a3a02dd46cb9eb078608dec98f633c0cf559ef" + }, + "HubertForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "HubertForCTC" + ], + "sha": "13431b76106f993eedcff48a75bae590a09b14f7" + }, + "HubertForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "HubertForSequenceClassification" + ], + "sha": "d23f46607a900b1a55dfee4b7ed205a6823035b1" + }, + "HubertModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "HubertModel", + "TFHubertModel" + ], + "sha": "3224562c86c4669db65ae7defdc5fb555b113e95" + }, + "IBertForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForMaskedLM" + ], + "sha": "e333a9c9d375f4d839b7e9e21d1a1c8dad58d7d1" + }, + "IBertForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForMultipleChoice" + ], + "sha": "a81f7d64cd7ce5fe6cd726b23d9d14ac5d17bf53" + }, + "IBertForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForQuestionAnswering" + ], + "sha": "7b66d13d4d6801a82cbeb7f9fd853ca1630d1f8b" + }, + "IBertForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForSequenceClassification" + ], + "sha": "309d57145c40f889222fe5df62f14dddf4496b38" + }, + "IBertForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertForTokenClassification" + ], + "sha": "b032e9bff4b081b78c098b2d8bc610ac035c6ddf" + }, + "IBertModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "IBertModel" + ], + "sha": "6749164c678d4883d455f98b1dfc98c62da8f08b" + }, + "IdeficsForVisionText2Text": { + "tokenizer_classes": [ + "LlamaTokenizerFast" + ], + "processor_classes": [ + "IdeficsImageProcessor" + ], + "model_classes": [ + "IdeficsForVisionText2Text" + ], + "sha": "a6be81294ff7a3d44f3aef0ed18e42b97c426831" + }, + "IdeficsModel": { + "tokenizer_classes": [ + "LlamaTokenizerFast" + ], + "processor_classes": [ + "IdeficsImageProcessor" + ], + "model_classes": [ + "IdeficsModel" + ], + "sha": "649df2e35e067efd573ff2d083784a5cf876545e" + }, + "ImageGPTForCausalImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "ImageGPTImageProcessor" + ], + "model_classes": [ + "ImageGPTForCausalImageModeling" + ], + "sha": "9a7d1fc04439ab1d9d690de9c3e7673f08568cdf" + }, + "ImageGPTForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ImageGPTImageProcessor" + ], + "model_classes": [ + "ImageGPTForImageClassification" + ], + "sha": "d92c7aed4ba5de74a1f542b736010090e4a58b42" + }, + "ImageGPTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ImageGPTImageProcessor" + ], + "model_classes": [ + "ImageGPTModel" + ], + "sha": "5a7983e48d5841704733dd0756177680ed50c074" + }, + "Kosmos2ForConditionalGeneration": { + "tokenizer_classes": [ + "XLMRobertaTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "Kosmos2ForConditionalGeneration" + ], + "sha": "d1d4607782b911411676f1ee79997dee645def58" + }, + "Kosmos2Model": { + "tokenizer_classes": [ + "XLMRobertaTokenizerFast" + ], + "processor_classes": [ + "CLIPImageProcessor" + ], + "model_classes": [ + "Kosmos2Model" + ], + "sha": "379d8944a65312094d9ab1c4b8a82058a2d3274e" + }, + "LEDForConditionalGeneration": { + "tokenizer_classes": [ + "LEDTokenizer", + "LEDTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LEDForConditionalGeneration", + "TFLEDForConditionalGeneration" + ], + "sha": "a354b49a79351f3ea8ae7776d9f8352ae26cfc14" + }, + "LEDForQuestionAnswering": { + "tokenizer_classes": [ + "LEDTokenizer", + "LEDTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LEDForQuestionAnswering" + ], + "sha": "47c7a75a1e650dae60ff6e9bbab0f2386946670c" + }, + "LEDForSequenceClassification": { + "tokenizer_classes": [ + "LEDTokenizer", + "LEDTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LEDForSequenceClassification" + ], + "sha": "3571e2c9d9f2f2ec0b8fe47090330b128be05126" + }, + "LEDModel": { + "tokenizer_classes": [ + "LEDTokenizer", + "LEDTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LEDModel", + "TFLEDModel" + ], + "sha": "3c3f6eb142545afc570187bfdabfe65d43dafbe4" + }, + "LayoutLMForMaskedLM": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMForMaskedLM", + "TFLayoutLMForMaskedLM" + ], + "sha": "0368bd9bd8fd3eb43b8a3b38962b5345b8765514" + }, + "LayoutLMForQuestionAnswering": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMForQuestionAnswering", + "TFLayoutLMForQuestionAnswering" + ], + "sha": "0d6a4bc614fccfa313c1fb6d132a250929518f85" + }, + "LayoutLMForSequenceClassification": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMForSequenceClassification", + "TFLayoutLMForSequenceClassification" + ], + "sha": "1bd68c73dbf6c8c0526d24fbe2831be82998c440" + }, + "LayoutLMForTokenClassification": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMForTokenClassification", + "TFLayoutLMForTokenClassification" + ], + "sha": "155e7da3f1d786aa39d957b16080c52de4a7efd7" + }, + "LayoutLMModel": { + "tokenizer_classes": [ + "LayoutLMTokenizer", + "LayoutLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LayoutLMModel", + "TFLayoutLMModel" + ], + "sha": "14f77b30d267910f11f0fd532a91a6b85ab3a4de" + }, + "LayoutLMv2ForQuestionAnswering": { + "tokenizer_classes": [ + "LayoutLMv2Tokenizer", + "LayoutLMv2TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv2ImageProcessor" + ], + "model_classes": [ + "LayoutLMv2ForQuestionAnswering" + ], + "sha": "f452e28dd34d3c38cce046b1cc7b0ada69f587b1" + }, + "LayoutLMv2ForSequenceClassification": { + "tokenizer_classes": [ + "LayoutLMv2Tokenizer", + "LayoutLMv2TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv2ImageProcessor" + ], + "model_classes": [ + "LayoutLMv2ForSequenceClassification" + ], + "sha": "b483e08fd143113629ecda3dbfd57e69bfeb5f11" + }, + "LayoutLMv2ForTokenClassification": { + "tokenizer_classes": [ + "LayoutLMv2Tokenizer", + "LayoutLMv2TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv2ImageProcessor" + ], + "model_classes": [ + "LayoutLMv2ForTokenClassification" + ], + "sha": "0721ae69bff00ecfff1b3d1521a475cde0253299" + }, + "LayoutLMv2Model": { + "tokenizer_classes": [ + "LayoutLMv2Tokenizer", + "LayoutLMv2TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv2ImageProcessor" + ], + "model_classes": [ + "LayoutLMv2Model" + ], + "sha": "6a1b510769b344979a910a7d0bade613a9ec2dfc" + }, + "LayoutLMv3ForQuestionAnswering": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv3ImageProcessor" + ], + "model_classes": [ + "LayoutLMv3ForQuestionAnswering", + "TFLayoutLMv3ForQuestionAnswering" + ], + "sha": "4640242388e69cf77ea2dd3ac36ec6f1b26628c8" + }, + "LayoutLMv3ForSequenceClassification": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv3ImageProcessor" + ], + "model_classes": [ + "LayoutLMv3ForSequenceClassification", + "TFLayoutLMv3ForSequenceClassification" + ], + "sha": "96515f699874cfbfbec7a64c539ae92419e4c6dc" + }, + "LayoutLMv3ForTokenClassification": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv3ImageProcessor" + ], + "model_classes": [ + "LayoutLMv3ForTokenClassification", + "TFLayoutLMv3ForTokenClassification" + ], + "sha": "ed4ffc464f2028fe50dfc6823f4eda78d34be7e6" + }, + "LayoutLMv3Model": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [ + "LayoutLMv3ImageProcessor" + ], + "model_classes": [ + "LayoutLMv3Model", + "TFLayoutLMv3Model" + ], + "sha": "69725e5e2445e5c1c3aa8a2aa49cfd72e0a44565" + }, + "LevitForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "LevitImageProcessor" + ], + "model_classes": [ + "LevitForImageClassification" + ], + "sha": "5ae8ccaa1fe1c947cb8ae6499e4a150c668bb9f0" + }, + "LevitForImageClassificationWithTeacher": { + "tokenizer_classes": [], + "processor_classes": [ + "LevitImageProcessor" + ], + "model_classes": [ + "LevitForImageClassificationWithTeacher" + ], + "sha": "568cc0d965b9bd293f240e7724314db6d50f6722" + }, + "LevitModel": { + "tokenizer_classes": [], + "processor_classes": [ + "LevitImageProcessor" + ], + "model_classes": [ + "LevitModel" + ], + "sha": "172efa52b50c75c3b3e498fa638f55e65b2ebf87" + }, + "LiltForQuestionAnswering": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LiltForQuestionAnswering" + ], + "sha": "0a348441999e98ec003b29fc4d5a67ad22ee6ca2" + }, + "LiltForSequenceClassification": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LiltForSequenceClassification" + ], + "sha": "c53ab0ba33536fe564a4a1e4f1674d990c01b83a" + }, + "LiltForTokenClassification": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LiltForTokenClassification" + ], + "sha": "14f85076f9b3f7016917e324d51ebd22511a2ae5" + }, + "LiltModel": { + "tokenizer_classes": [ + "LayoutLMv3Tokenizer", + "LayoutLMv3TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LiltModel" + ], + "sha": "3f1166cc14c532388df7e82336a8e575a813bd3f" + }, + "LongT5ForConditionalGeneration": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongT5ForConditionalGeneration" + ], + "sha": "c685cbbe706ad5c9a28689631765726a1874dcc7" + }, + "LongT5Model": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongT5Model" + ], + "sha": "6b468e55e2490565e6155690201086ac00c72062" + }, + "LongformerForMaskedLM": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForMaskedLM", + "TFLongformerForMaskedLM" + ], + "sha": "929d3bda9a1485d9bae41f9dbfc1d149c1c4e78e" + }, + "LongformerForMultipleChoice": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForMultipleChoice", + "TFLongformerForMultipleChoice" + ], + "sha": "60b1ecac6b9385ce18c7e6978ab161cce8e7f9d4" + }, + "LongformerForQuestionAnswering": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForQuestionAnswering", + "TFLongformerForQuestionAnswering" + ], + "sha": "be45ab1321b703f2200cbbcae560aaf2e2afef88" + }, + "LongformerForSequenceClassification": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForSequenceClassification", + "TFLongformerForSequenceClassification" + ], + "sha": "8bc0de0b0f740bf397eb2770ec3ce3a24f3d7af9" + }, + "LongformerForTokenClassification": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerForTokenClassification", + "TFLongformerForTokenClassification" + ], + "sha": "efa33a9b6f47f0f7979af08ae8d04a5a7363a14b" + }, + "LongformerModel": { + "tokenizer_classes": [ + "LongformerTokenizer", + "LongformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LongformerModel", + "TFLongformerModel" + ], + "sha": "b023d531688e8655fc09300ac36742588efb3240" + }, + "LukeForMaskedLM": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForMaskedLM" + ], + "sha": "954cf6cd2bf1f298a3956b10c36656c57387506d" + }, + "LukeForMultipleChoice": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForMultipleChoice" + ], + "sha": "d1310a9174ad50d60b30ad6049e165deb2539034" + }, + "LukeForQuestionAnswering": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForQuestionAnswering" + ], + "sha": "3ea38da4e32cb4e45bea82b2e81a8639aeba2c35" + }, + "LukeForSequenceClassification": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForSequenceClassification" + ], + "sha": "b5b11248aeb4f5976379d15a977aeb2677e0c0f9" + }, + "LukeForTokenClassification": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeForTokenClassification" + ], + "sha": "8aab1a33ad26a344a6f4dfd68630e9661e174471" + }, + "LukeModel": { + "tokenizer_classes": [ + "LukeTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "LukeModel" + ], + "sha": "ae23a674e7297d41f33c9af86e039757dfd2d531" + }, + "LxmertForPreTraining": { + "tokenizer_classes": [ + "LxmertTokenizer", + "LxmertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LxmertForPreTraining", + "TFLxmertForPreTraining" + ], + "sha": "7b0843403c187aef00f20d5087086468d9613d2c" + }, + "LxmertForQuestionAnswering": { + "tokenizer_classes": [ + "LxmertTokenizer", + "LxmertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LxmertForQuestionAnswering" + ], + "sha": "27a74bd2cd156e46656c43ceb432c4deda0df5c1" + }, + "LxmertModel": { + "tokenizer_classes": [ + "LxmertTokenizer", + "LxmertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "LxmertModel", + "TFLxmertModel" + ], + "sha": "97612a0d6b14406ea9bfd7672e6974e0961cbef1" + }, + "M2M100ForConditionalGeneration": { + "tokenizer_classes": [ + "M2M100Tokenizer" + ], + "processor_classes": [], + "model_classes": [ + "M2M100ForConditionalGeneration" + ], + "sha": "32ac347092d51f658b41ffc111b67d49acdeab46" + }, + "M2M100Model": { + "tokenizer_classes": [ + "M2M100Tokenizer" + ], + "processor_classes": [], + "model_classes": [ + "M2M100Model" + ], + "sha": "e95c2ae168c7ba19f8114def40e1b1edd953b2f5" + }, + "MBartForCausalLM": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartForCausalLM" + ], + "sha": "a45044f8056328d20a764356eca3d0746a7a195e" + }, + "MBartForConditionalGeneration": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartForConditionalGeneration", + "TFMBartForConditionalGeneration" + ], + "sha": "171e918962d6c0ee56c6b070858e19e16c8dd09f" + }, + "MBartForQuestionAnswering": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartForQuestionAnswering" + ], + "sha": "1ee08565d24777335595e0d2940e454abdcff731" + }, + "MBartForSequenceClassification": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartForSequenceClassification" + ], + "sha": "53e9c88ecfa2475d27afe099ffa7a8bcdb7ef7e4" + }, + "MBartModel": { + "tokenizer_classes": [ + "MBartTokenizer", + "MBartTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MBartModel", + "TFMBartModel" + ], + "sha": "2d492b34d69dd63b411990d5c8bb692fd637e91c" + }, + "MCTCTForCTC": { + "tokenizer_classes": [], + "processor_classes": [ + "MCTCTFeatureExtractor" + ], + "model_classes": [ + "MCTCTForCTC" + ], + "sha": "895a3d74f87b344b1f0a71eae4f085941d51b5cf" + }, + "MCTCTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "MCTCTFeatureExtractor" + ], + "model_classes": [ + "MCTCTModel" + ], + "sha": "ce73d5c2b6fe163de778697d7b0543bf00d7ffa8" + }, + "MPNetForMaskedLM": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForMaskedLM", + "TFMPNetForMaskedLM" + ], + "sha": "50af96e7d0202aef86e396c136e4c4fde8afe183" + }, + "MPNetForMultipleChoice": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForMultipleChoice", + "TFMPNetForMultipleChoice" + ], + "sha": "af4ff8bf296a3a51f5ab6cd9f56741e4c732487c" + }, + "MPNetForQuestionAnswering": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForQuestionAnswering", + "TFMPNetForQuestionAnswering" + ], + "sha": "3e1a25c0d3243f78f81580c312ada3b39c06b428" + }, + "MPNetForSequenceClassification": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForSequenceClassification", + "TFMPNetForSequenceClassification" + ], + "sha": "43da45c0a0d73c5a5567b4c7ec512ec5023e52dd" + }, + "MPNetForTokenClassification": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetForTokenClassification", + "TFMPNetForTokenClassification" + ], + "sha": "4e825eff24df533321ebab823eb66ce67e4ab3d9" + }, + "MPNetModel": { + "tokenizer_classes": [ + "MPNetTokenizer", + "MPNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MPNetModel", + "TFMPNetModel" + ], + "sha": "847c68344c2922e9a71fa8835b87a0f6f72b9f47" + }, + "MarianForCausalLM": { + "tokenizer_classes": [ + "MarianTokenizer" + ], + "processor_classes": [], + "model_classes": [], + "sha": "5fb205e6db8e18e3c6cdd4e4709be292ba4599f3" + }, + "MarianMTModel": { + "tokenizer_classes": [ + "MarianTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "MarianMTModel", + "TFMarianMTModel" + ], + "sha": "0405f542b31561592231a86e3009d05256cbf49f" + }, + "MarianModel": { + "tokenizer_classes": [ + "MarianTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "MarianModel", + "TFMarianModel" + ], + "sha": "3649748c0286c6d5179a7013a716f7314db182a8" + }, + "MarkupLMForQuestionAnswering": { + "tokenizer_classes": [ + "MarkupLMTokenizer", + "MarkupLMTokenizerFast" + ], + "processor_classes": [ + "MarkupLMFeatureExtractor" + ], + "model_classes": [ + "MarkupLMForQuestionAnswering" + ], + "sha": "c8bb9f93591d980362547b0bdca9f23ace2f383e" + }, + "MarkupLMForSequenceClassification": { + "tokenizer_classes": [ + "MarkupLMTokenizer", + "MarkupLMTokenizerFast" + ], + "processor_classes": [ + "MarkupLMFeatureExtractor" + ], + "model_classes": [ + "MarkupLMForSequenceClassification" + ], + "sha": "c2cb7245d68d76e0a5f993fc8a3de099ecebc68b" + }, + "MarkupLMForTokenClassification": { + "tokenizer_classes": [ + "MarkupLMTokenizer", + "MarkupLMTokenizerFast" + ], + "processor_classes": [ + "MarkupLMFeatureExtractor" + ], + "model_classes": [ + "MarkupLMForTokenClassification" + ], + "sha": "b9f924e82f400de0b34b46ee4ba276d686bd4890" + }, + "MarkupLMModel": { + "tokenizer_classes": [ + "MarkupLMTokenizer", + "MarkupLMTokenizerFast" + ], + "processor_classes": [ + "MarkupLMFeatureExtractor" + ], + "model_classes": [ + "MarkupLMModel" + ], + "sha": "9687ba29f1c59d978e3d4b0fa702031f88eff53b" + }, + "Mask2FormerForUniversalSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "Mask2FormerImageProcessor" + ], + "model_classes": [ + "Mask2FormerForUniversalSegmentation" + ], + "sha": "6429a7349527c9ef140ae691b83c47702cce1bc0" + }, + "Mask2FormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "Mask2FormerImageProcessor" + ], + "model_classes": [ + "Mask2FormerModel" + ], + "sha": "9bee8709204024b3669d503cdfe8890182f2a075" + }, + "MaskFormerForInstanceSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "MaskFormerImageProcessor" + ], + "model_classes": [ + "MaskFormerForInstanceSegmentation" + ], + "sha": "f844aaa81f55cb199c115f1bf95c217a70685570" + }, + "MaskFormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "MaskFormerImageProcessor" + ], + "model_classes": [ + "MaskFormerModel" + ], + "sha": "473b54a464bc0ccee29bc23b4f6610f32eec05af" + }, + "MegaForCausalLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForCausalLM" + ], + "sha": "6642b9da860f8b62abcfb0660feabcebf6698418" + }, + "MegaForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForMaskedLM" + ], + "sha": "6b2d47ba03bec9e6f7eefdd4a67351fa191aae6f" + }, + "MegaForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForMultipleChoice" + ], + "sha": "2b1e751da36a4410473eef07a62b09227a26d504" + }, + "MegaForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForQuestionAnswering" + ], + "sha": "612acd9a53c351c42514adb3c04f2057d2870be7" + }, + "MegaForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForSequenceClassification" + ], + "sha": "4871572da1613b7e9cfd3640c6d1129af004eefb" + }, + "MegaForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaForTokenClassification" + ], + "sha": "450d3722c3b995215d06b9c12544c99f958581c7" + }, + "MegaModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegaModel" + ], + "sha": "ca0862db27428893fe22f9bb5d2eb0875c2156f3" + }, + "MegatronBertForCausalLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForCausalLM" + ], + "sha": "ff08d05ef8f98fdccf1f01560ec6ec4adbc8a3e3" + }, + "MegatronBertForMaskedLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForMaskedLM" + ], + "sha": "2ed25e2681d26b51b404ef1347a385c5f2c86a9a" + }, + "MegatronBertForMultipleChoice": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForMultipleChoice" + ], + "sha": "1485af4b75f8f234d2b4b5aea50ab2ec55223a15" + }, + "MegatronBertForNextSentencePrediction": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForNextSentencePrediction" + ], + "sha": "52bc9ee1d5145344f66b088ed278f07ed3d90584" + }, + "MegatronBertForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForPreTraining" + ], + "sha": "e580d0efd54e1c92789e39b32929234e36ee427f" + }, + "MegatronBertForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForQuestionAnswering" + ], + "sha": "7342ba042a3c30c15382d00fcb0521533fc43841" + }, + "MegatronBertForSequenceClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForSequenceClassification" + ], + "sha": "6a7cd480511d817a1e221c8f7558c55a93baed1b" + }, + "MegatronBertForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertForTokenClassification" + ], + "sha": "8b5334b6ec5f025293ca861de474b57ca84bc005" + }, + "MegatronBertModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MegatronBertModel" + ], + "sha": "f2457fbe535ba97ea13db049f53618b42e13f047" + }, + "MgpstrForSceneTextRecognition": { + "tokenizer_classes": [], + "processor_classes": [ + "MgpstrProcessor" + ], + "model_classes": [ + "MgpstrForSceneTextRecognition" + ], + "sha": "f197d5bfa1fe27b5f28a6e6d4e3ad229b753450a" + }, + "MistralForCausalLM": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MistralForCausalLM" + ], + "sha": "f7e06aeedbba8f4f665b438b868ed932d451f64b" + }, + "MistralForSequenceClassification": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MistralForSequenceClassification" + ], + "sha": "65045444ea1933309270d8b08b21d3fa94a84290" + }, + "MistralModel": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MistralModel" + ], + "sha": "becd727ad72b1e8a7c0fa0ea39b61904fa68aeac" + }, + "MobileBertForMaskedLM": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForMaskedLM", + "TFMobileBertForMaskedLM" + ], + "sha": "d689e737d73ad23aed3aabd3177591fc827d1c62" + }, + "MobileBertForMultipleChoice": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForMultipleChoice", + "TFMobileBertForMultipleChoice" + ], + "sha": "403d1f88be7eb0c769ff3a8e57eab21cc3e75afb" + }, + "MobileBertForNextSentencePrediction": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForNextSentencePrediction", + "TFMobileBertForNextSentencePrediction" + ], + "sha": "b4d8836a0f259ee3bca9f230093836c9117c5e4d" + }, + "MobileBertForPreTraining": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForPreTraining", + "TFMobileBertForPreTraining" + ], + "sha": "fbaa13ea6f9fcebb9fde620dd009d12510440d17" + }, + "MobileBertForQuestionAnswering": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForQuestionAnswering", + "TFMobileBertForQuestionAnswering" + ], + "sha": "ba6a55cf2daec55bfb220c9bab0bc4ad96510087" + }, + "MobileBertForSequenceClassification": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForSequenceClassification", + "TFMobileBertForSequenceClassification" + ], + "sha": "17ab35603bec351457e035eef2d0426538071f72" + }, + "MobileBertForTokenClassification": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertForTokenClassification", + "TFMobileBertForTokenClassification" + ], + "sha": "dee83e820e6c4f069886a5d1875bf6775897313e" + }, + "MobileBertModel": { + "tokenizer_classes": [ + "MobileBertTokenizer", + "MobileBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MobileBertModel", + "TFMobileBertModel" + ], + "sha": "09b2db33ea798a762eeaf7e727e95f9ea8a6d14f" + }, + "MobileNetV1ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV1ImageProcessor" + ], + "model_classes": [ + "MobileNetV1ForImageClassification" + ], + "sha": "55023dbd0935f147bf1bccf960cea01ca07e0f0c" + }, + "MobileNetV1Model": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV1ImageProcessor" + ], + "model_classes": [ + "MobileNetV1Model" + ], + "sha": "178bd24528147a028938d6ee5c7e65c969ea37b0" + }, + "MobileNetV2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV2ImageProcessor" + ], + "model_classes": [ + "MobileNetV2ForImageClassification" + ], + "sha": "ff907f740cf9ea91bc3cdf403a94ae28fbb2548a" + }, + "MobileNetV2ForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV2ImageProcessor" + ], + "model_classes": [ + "MobileNetV2ForSemanticSegmentation" + ], + "sha": "48adbc340e42882f52b54d4f5dd045e16e9ef2d6" + }, + "MobileNetV2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileNetV2ImageProcessor" + ], + "model_classes": [ + "MobileNetV2Model" + ], + "sha": "e876885828825472a80ef1796d89d60b901813ba" + }, + "MobileViTForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTForImageClassification", + "TFMobileViTForImageClassification" + ], + "sha": "7d0b31864f856e00f9e34e8c6781dcc7a8cdaf1e" + }, + "MobileViTForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTForSemanticSegmentation", + "TFMobileViTForSemanticSegmentation" + ], + "sha": "215f727caa3c3fc94fa4df486aa706e5d99d4194" + }, + "MobileViTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTModel", + "TFMobileViTModel" + ], + "sha": "b3a1452e7cb44b600b21ee14f3d5382366855a46" + }, + "MobileViTV2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTV2ForImageClassification" + ], + "sha": "25752b0967ad594341d1b685401450d7f698433c" + }, + "MobileViTV2ForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTV2ForSemanticSegmentation" + ], + "sha": "13b953f50be33219d55a12f1098be38b88000897" + }, + "MobileViTV2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "MobileViTImageProcessor" + ], + "model_classes": [ + "MobileViTV2Model" + ], + "sha": "2f46357659db2d6d54d870e28073deeea1c8cb64" + }, + "MptForCausalLM": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptForCausalLM" + ], + "sha": "500c869b956c65f6b1a7b4867727f124c6f5728a" + }, + "MptForQuestionAnswering": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptForQuestionAnswering" + ], + "sha": "6ee46572bf61eb5e7dbbdaf00b73c4d37efc42d9" + }, + "MptForSequenceClassification": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptForSequenceClassification" + ], + "sha": "f0b9153413b5dfceeb96b67d4b0f22c94bbaf64a" + }, + "MptForTokenClassification": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptForTokenClassification" + ], + "sha": "3f7c3ccd67cd0b2aae56d37613429a64ef813246" + }, + "MptModel": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MptModel" + ], + "sha": "ea747f234556661b0c8b84a626f267066ce586bf" + }, + "MraForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForMaskedLM" + ], + "sha": "c00ee46cfd2b8fed29cc37f0a4ead40ad51a439c" + }, + "MraForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForMultipleChoice" + ], + "sha": "f397469ba8109f64dab2d75335ea7bf0c2dbeb74" + }, + "MraForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForQuestionAnswering" + ], + "sha": "c2ed75acd20e5440a76d6504d9a3ebc2513011f0" + }, + "MraForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForSequenceClassification" + ], + "sha": "f47672d3708508bda7774215bee44a92ec16ab2f" + }, + "MraForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraForTokenClassification" + ], + "sha": "f0961ab5818bca473607fb94b391c186dc1d3492" + }, + "MraModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MraModel" + ], + "sha": "315f34f30bcc4b0b66b11987726df2a80c50e271" + }, + "MusicgenForCausalLM": { + "tokenizer_classes": [ + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [], + "sha": "f67d387eaaa7c71ddf88af95eda4bf14ace08d49" + }, + "MusicgenForConditionalGeneration": { + "tokenizer_classes": [ + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MusicgenForConditionalGeneration" + ], + "sha": "16102cdf580e70cf0b4e0e2cda5bc75b934da92c" + }, + "MvpForCausalLM": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpForCausalLM" + ], + "sha": "105e5f2c8a0f20d404cb71795539cda5dd49716d" + }, + "MvpForConditionalGeneration": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpForConditionalGeneration" + ], + "sha": "b0b706f14b2f8aae288cba30ae0064e0be7e888b" + }, + "MvpForQuestionAnswering": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpForQuestionAnswering" + ], + "sha": "82f152b36a40a4c22edcb146e6eaec636d84fa2d" + }, + "MvpForSequenceClassification": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpForSequenceClassification" + ], + "sha": "506b68544d064001929ee9e6db3752e62972a6aa" + }, + "MvpModel": { + "tokenizer_classes": [ + "MvpTokenizer", + "MvpTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "MvpModel" + ], + "sha": "3f4653184721a2bc029b27706d335ef7ddd219d5" + }, + "NatBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "NatBackbone" + ], + "sha": "d5cc5eccba4da609c82e9f5c649301b9f9fee9fb" + }, + "NatForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "NatForImageClassification" + ], + "sha": "2ff4c9e73c49c392c02a467e87b5511fd924242a" + }, + "NatModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "NatModel" + ], + "sha": "75e9756bb94d0ccdce98a8e963eeecbc66f9d573" + }, + "NezhaForMaskedLM": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForMaskedLM" + ], + "sha": "5991cca4b78f0ed7299259a71f3eeed3f3452b72" + }, + "NezhaForMultipleChoice": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForMultipleChoice" + ], + "sha": "0f6e9ec791d85ad4503acdec50b3a120f984016b" + }, + "NezhaForNextSentencePrediction": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForNextSentencePrediction" + ], + "sha": "9a34316c14ec8ecc98ff08e46760915c80098a57" + }, + "NezhaForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForPreTraining" + ], + "sha": "6259db427a0073061de352ea819d38a74798edd7" + }, + "NezhaForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForQuestionAnswering" + ], + "sha": "31c6a34e85ae8c41294e0f4ef25044e00e511c4d" + }, + "NezhaForSequenceClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForSequenceClassification" + ], + "sha": "db057c308ba2e05f223404de11e1816ce4bd62a9" + }, + "NezhaForTokenClassification": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaForTokenClassification" + ], + "sha": "235f4e10b4a59709650c2bece3e342ec153d9cfc" + }, + "NezhaModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NezhaModel" + ], + "sha": "80e05ba7c55bcdd7f4d1387ef9a09a7a8e95b5ac" + }, + "NllbMoeForConditionalGeneration": { + "tokenizer_classes": [ + "NllbTokenizer", + "NllbTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NllbMoeForConditionalGeneration" + ], + "sha": "2a7f87dffe826af3d52086888f3f3773246e5528" + }, + "NllbMoeModel": { + "tokenizer_classes": [ + "NllbTokenizer", + "NllbTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NllbMoeModel" + ], + "sha": "9f7a2261eed4658e1aa5623be4672ba64bee7da5" + }, + "NystromformerForMaskedLM": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForMaskedLM" + ], + "sha": "37036847783f1e65e81ecd43803270a1ecb276f3" + }, + "NystromformerForMultipleChoice": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForMultipleChoice" + ], + "sha": "42a077d5ab6830e20560466eaccc525eff10c3ae" + }, + "NystromformerForQuestionAnswering": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForQuestionAnswering" + ], + "sha": "1cfaf79051731824db4f09989f093f87f4fceec5" + }, + "NystromformerForSequenceClassification": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForSequenceClassification" + ], + "sha": "d75231203066df41e9b6b25dbee9ad40e8515c18" + }, + "NystromformerForTokenClassification": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerForTokenClassification" + ], + "sha": "5a499dc96e106bf41fc9166f2ad06527ec7ca14e" + }, + "NystromformerModel": { + "tokenizer_classes": [ + "AlbertTokenizer", + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "NystromformerModel" + ], + "sha": "2b6adb37ec473b15d71e2eb459acea08df6940ce" + }, + "OPTForCausalLM": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OPTForCausalLM", + "TFOPTForCausalLM" + ], + "sha": "190d1f4fc0011d2eaeaa05282e0fbd2445e4b11f" + }, + "OPTForQuestionAnswering": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OPTForQuestionAnswering" + ], + "sha": "0fa9277ce10dbc3d0922b354befb684a136af00b" + }, + "OPTForSequenceClassification": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OPTForSequenceClassification" + ], + "sha": "784ab288ab7280b1853ee400ef10ee2a965df352" + }, + "OPTModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OPTModel", + "TFOPTModel" + ], + "sha": "901d92b8f51edb0ec9614cb185fb66a8b5d364c3" + }, + "OneFormerForUniversalSegmentation": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "OneFormerImageProcessor" + ], + "model_classes": [ + "OneFormerForUniversalSegmentation" + ], + "sha": "fee1cfd676acc40f09017702ddac6504f3090d14" + }, + "OneFormerModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "OneFormerImageProcessor" + ], + "model_classes": [ + "OneFormerModel" + ], + "sha": "4163a79328c78f93ec57942598698a138c19a577" + }, + "OpenAIGPTForSequenceClassification": { + "tokenizer_classes": [ + "OpenAIGPTTokenizer", + "OpenAIGPTTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OpenAIGPTForSequenceClassification", + "TFOpenAIGPTForSequenceClassification" + ], + "sha": "c513f7f952935085f7573bf70a1ac3ad8f33434c" + }, + "OpenAIGPTLMHeadModel": { + "tokenizer_classes": [ + "OpenAIGPTTokenizer", + "OpenAIGPTTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OpenAIGPTLMHeadModel", + "TFOpenAIGPTLMHeadModel" + ], + "sha": "33f59ecd860f7a998483ec7631fe32d257235461" + }, + "OpenAIGPTModel": { + "tokenizer_classes": [ + "OpenAIGPTTokenizer", + "OpenAIGPTTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "OpenAIGPTModel", + "TFOpenAIGPTModel" + ], + "sha": "00f6ec0a3a5276af71d08a26199e0ccbf2556fc9" + }, + "OwlViTForObjectDetection": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "OwlViTImageProcessor" + ], + "model_classes": [ + "OwlViTForObjectDetection" + ], + "sha": "af958c9164f23d0f12921a8edf687f9aaa6af90e" + }, + "OwlViTModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "OwlViTImageProcessor" + ], + "model_classes": [ + "OwlViTModel" + ], + "sha": "f0e27b2b4e53ba70e05d13dcfea8e85272b292a5" + }, + "Owlv2ForObjectDetection": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "Owlv2ImageProcessor" + ], + "model_classes": [ + "Owlv2ForObjectDetection" + ], + "sha": "30439c0b2749726468dc13a755261e8101170052" + }, + "Owlv2Model": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "Owlv2ImageProcessor" + ], + "model_classes": [ + "Owlv2Model" + ], + "sha": "7aeebdad5f72b36cb07c74355afad8e6052e2377" + }, + "PLBartForCausalLM": { + "tokenizer_classes": [ + "PLBartTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "PLBartForCausalLM" + ], + "sha": "6ee51133246dbdb18fc3681ebd62d21e421b9bb4" + }, + "PLBartForConditionalGeneration": { + "tokenizer_classes": [ + "PLBartTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "PLBartForConditionalGeneration" + ], + "sha": "ba191d28f4678d20b4dfed5fca5944018282cf20" + }, + "PLBartForSequenceClassification": { + "tokenizer_classes": [ + "PLBartTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "PLBartForSequenceClassification" + ], + "sha": "02063b3d9707fcff619a4e37a0d6e58f76e39b18" + }, + "PLBartModel": { + "tokenizer_classes": [ + "PLBartTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "PLBartModel" + ], + "sha": "cfbba29169b3f40d800403fc1b53982e1f88c5f8" + }, + "PegasusForCausalLM": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusForCausalLM" + ], + "sha": "6e685a698302a3ba33e5379d3a37eb0bc1ae2f70" + }, + "PegasusForConditionalGeneration": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusForConditionalGeneration", + "TFPegasusForConditionalGeneration" + ], + "sha": "15e58ee2ebc14b6e80ef2891259057ee5f049be2" + }, + "PegasusModel": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusModel", + "TFPegasusModel" + ], + "sha": "fa36b24523db411ef77903453346b8be81ef73fe" + }, + "PegasusXForConditionalGeneration": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusXForConditionalGeneration" + ], + "sha": "7588a8120f26a36c1687c14bdf1e9f9656891c1a" + }, + "PegasusXModel": { + "tokenizer_classes": [ + "PegasusTokenizer", + "PegasusTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PegasusXModel" + ], + "sha": "a0bdff627416ac3c39c22d081f5d88d8b8fd99cc" + }, + "PerceiverForImageClassificationConvProcessing": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForImageClassificationConvProcessing" + ], + "sha": "2c1e5e62ebc9d0c931adc8c665fb05bde6c1c1f1" + }, + "PerceiverForImageClassificationFourier": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForImageClassificationFourier" + ], + "sha": "88da41b8851b76b8be0dacdb3de023db02bb031a" + }, + "PerceiverForImageClassificationLearned": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForImageClassificationLearned" + ], + "sha": "879bd1fa38d3baddb027bb2cacba2d160a741375" + }, + "PerceiverForMaskedLM": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForMaskedLM" + ], + "sha": "1d2459cbd281ef72da5682e65102aaca96183045" + }, + "PerceiverForSequenceClassification": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverForSequenceClassification" + ], + "sha": "576f1f96348f0343458499fbf53d4102b5c0f2ff" + }, + "PerceiverModel": { + "tokenizer_classes": [ + "PerceiverTokenizer" + ], + "processor_classes": [ + "PerceiverImageProcessor" + ], + "model_classes": [ + "PerceiverModel" + ], + "sha": "83ec4d2d61ed62525ee033e13d144817beb29d19" + }, + "PersimmonForCausalLM": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PersimmonForCausalLM" + ], + "sha": "454234d6496c3857f5bf3eafb784616e2cd3ea82" + }, + "PersimmonForSequenceClassification": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PersimmonForSequenceClassification" + ], + "sha": "1d2674846543a181ca67bafa8b8f3a48bd2eefd1" + }, + "PersimmonModel": { + "tokenizer_classes": [ + "LlamaTokenizer", + "LlamaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "PersimmonModel" + ], + "sha": "b8c8d479e29e9ee048e2d0b05b001ac835ad8859" + }, + "Pix2StructForConditionalGeneration": { + "tokenizer_classes": [ + "T5TokenizerFast" + ], + "processor_classes": [ + "Pix2StructImageProcessor", + "Pix2StructProcessor" + ], + "model_classes": [ + "Pix2StructForConditionalGeneration" + ], + "sha": "42b3de00ad535076c4893e4ac5ae2d2748cc4ccb" + }, + "PoolFormerForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "PoolFormerImageProcessor" + ], + "model_classes": [ + "PoolFormerForImageClassification" + ], + "sha": "ef04de5a6896100d457fb9553dd9789c09cca98e" + }, + "PoolFormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "PoolFormerImageProcessor" + ], + "model_classes": [ + "PoolFormerModel" + ], + "sha": "e8037215ebdbf795329ef6525cdc6aa547f04ace" + }, + "ProphetNetForCausalLM": { + "tokenizer_classes": [ + "ProphetNetTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ProphetNetForCausalLM" + ], + "sha": "d40b1e75bbc5ea0839563457aff6eee5bc0bb03e" + }, + "ProphetNetForConditionalGeneration": { + "tokenizer_classes": [ + "ProphetNetTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ProphetNetForConditionalGeneration" + ], + "sha": "d842875c41278032af39c03c66902786bb5ff2c7" + }, + "ProphetNetModel": { + "tokenizer_classes": [ + "ProphetNetTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "ProphetNetModel" + ], + "sha": "f1ddbbcc768c7ba54c4d75b319540c1635e65937" + }, + "PvtForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "PvtImageProcessor" + ], + "model_classes": [ + "PvtForImageClassification" + ], + "sha": "589b37bd6941aff6dd248259f9eee3c422a41fde" + }, + "PvtModel": { + "tokenizer_classes": [], + "processor_classes": [ + "PvtImageProcessor" + ], + "model_classes": [ + "PvtModel" + ], + "sha": "c40765c382515ae627652d60e9077b6478448d48" + }, + "ReformerForMaskedLM": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ReformerForMaskedLM" + ], + "sha": "1e6431e42c676b525e3215e9e3cc8f1404f9f82b" + }, + "ReformerForQuestionAnswering": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ReformerForQuestionAnswering" + ], + "sha": "62b43977f244474bd6982c6327d0c57310258fcd" + }, + "ReformerForSequenceClassification": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ReformerForSequenceClassification" + ], + "sha": "67bd534a990a7dcfa02406987e7f066caa2a30e8" + }, + "ReformerModel": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "ReformerModel" + ], + "sha": "a34ddb1389067448e9bc1323de674951cfb4cff1" + }, + "ReformerModelWithLMHead": { + "tokenizer_classes": [ + "ReformerTokenizer", + "ReformerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [], + "sha": "e7a8addaea8407d4c55e144e48aee04be6cca618" + }, + "RegNetForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "RegNetForImageClassification", + "TFRegNetForImageClassification" + ], + "sha": "5ec67c84fc7944c0c5b386bd26820bc4d1f3b32a" + }, + "RegNetModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "RegNetModel", + "TFRegNetModel" + ], + "sha": "72375e1401dc8271d4abb6295c9cee376f7b8f1a" + }, + "RemBertForCausalLM": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForCausalLM", + "TFRemBertForCausalLM" + ], + "sha": "8d9ae3d74a0e0a8958b4ee8c9dca3632abf52ef9" + }, + "RemBertForMaskedLM": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForMaskedLM", + "TFRemBertForMaskedLM" + ], + "sha": "b7c27d01e1cc3bef9ddd6a78627d700b3bffd759" + }, + "RemBertForMultipleChoice": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForMultipleChoice", + "TFRemBertForMultipleChoice" + ], + "sha": "2fe192677b9740cf24dd559339d46925e8ac23d4" + }, + "RemBertForQuestionAnswering": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForQuestionAnswering", + "TFRemBertForQuestionAnswering" + ], + "sha": "22b8ba44681b96292a1cf7f6df4ba6bb7937ec6e" + }, + "RemBertForSequenceClassification": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForSequenceClassification", + "TFRemBertForSequenceClassification" + ], + "sha": "20f3e89341ea15266d2685a8798142fba03c3f98" + }, + "RemBertForTokenClassification": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertForTokenClassification", + "TFRemBertForTokenClassification" + ], + "sha": "15712ff753708da3cf0550e76e73a5d0bba7784e" + }, + "RemBertModel": { + "tokenizer_classes": [ + "RemBertTokenizer", + "RemBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RemBertModel", + "TFRemBertModel" + ], + "sha": "59cc6d099b1ded0aaead8684457415b129f79e86" + }, + "ResNetBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ResNetBackbone" + ], + "sha": "c84a6bcf8af4b6a3403dea3cf4c55965ac39f239" + }, + "ResNetForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ResNetForImageClassification", + "TFResNetForImageClassification" + ], + "sha": "34a180ad24d80811d420d7aa4fbec4a17751aaf8" + }, + "ResNetModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "ResNetModel", + "TFResNetModel" + ], + "sha": "fafa6cdf9986c6cfbae360596b3574162430bcd3" + }, + "RoCBertForCausalLM": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForCausalLM" + ], + "sha": "194d8dafc4f4142f8d31e6b4be14b55d812f923b" + }, + "RoCBertForMaskedLM": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForMaskedLM" + ], + "sha": "8bc285f32f3b932dbd56ddf91b1170734d638eeb" + }, + "RoCBertForMultipleChoice": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForMultipleChoice" + ], + "sha": "bb54e5ae021d728022d34b12fee3f087d9486af9" + }, + "RoCBertForPreTraining": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForPreTraining" + ], + "sha": "86ebbd5b0bc84660ad7f505082eff19b86c137c8" + }, + "RoCBertForQuestionAnswering": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForQuestionAnswering" + ], + "sha": "1bfc2dc3d6e76170e6dca1ff32a54a0887ff28a3" + }, + "RoCBertForSequenceClassification": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForSequenceClassification" + ], + "sha": "c329038802241f454273894128fea38b60f7c739" + }, + "RoCBertForTokenClassification": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertForTokenClassification" + ], + "sha": "afe5ec22c2ad1d9ff6e3e64c87eb7555faaa936d" + }, + "RoCBertModel": { + "tokenizer_classes": [ + "RoCBertTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "RoCBertModel" + ], + "sha": "29de5580d5f5d3461a88673e7b4c492a9d8a67a4" + }, + "RoFormerForCausalLM": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForCausalLM", + "TFRoFormerForCausalLM" + ], + "sha": "6e074219c6dd8f8b221bbfda64fba100f729f88d" + }, + "RoFormerForMaskedLM": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForMaskedLM", + "TFRoFormerForMaskedLM" + ], + "sha": "a3a4d05f9b29601553a77244f2adcf8194f9367c" + }, + "RoFormerForMultipleChoice": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForMultipleChoice", + "TFRoFormerForMultipleChoice" + ], + "sha": "aca3999a1d14f09644faed44e2cdfb28ed68a3d3" + }, + "RoFormerForQuestionAnswering": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForQuestionAnswering", + "TFRoFormerForQuestionAnswering" + ], + "sha": "b8a20b3a788f178b9ef64e2eb9587f693dca1b69" + }, + "RoFormerForSequenceClassification": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForSequenceClassification", + "TFRoFormerForSequenceClassification" + ], + "sha": "d092e2d5e62012bf4ec921e763b37865d6189216" + }, + "RoFormerForTokenClassification": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerForTokenClassification", + "TFRoFormerForTokenClassification" + ], + "sha": "85d3a17062e1f3e0539abfe738a88203e25349b6" + }, + "RoFormerModel": { + "tokenizer_classes": [ + "RoFormerTokenizer", + "RoFormerTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RoFormerModel", + "TFRoFormerModel" + ], + "sha": "22e7df2f4cd66caf449f2342f63d176005afccc9" + }, + "RobertaForCausalLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForCausalLM", + "TFRobertaForCausalLM" + ], + "sha": "5d1d24d56f9735402e50a2ea513ffde44487733e" + }, + "RobertaForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForMaskedLM", + "TFRobertaForMaskedLM" + ], + "sha": "b21c9daf0b3b66530bf5d45d67df5ec392b5059c" + }, + "RobertaForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForMultipleChoice", + "TFRobertaForMultipleChoice" + ], + "sha": "10020d9546d4d7318f4d514fe13daaad07e6269f" + }, + "RobertaForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForQuestionAnswering", + "TFRobertaForQuestionAnswering" + ], + "sha": "eea4a81306891746bac9e7715f805a2d9dbf4be7" + }, + "RobertaForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForSequenceClassification", + "TFRobertaForSequenceClassification" + ], + "sha": "6a6f53fc6ab98e29ed539e76b1cb76d25a2cd720" + }, + "RobertaForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaForTokenClassification", + "TFRobertaForTokenClassification" + ], + "sha": "9190044c4091eb0d98ae7638c453e24846bca5d7" + }, + "RobertaModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaModel", + "TFRobertaModel" + ], + "sha": "181a0b8a7ad24500ec327ad07ddb225f0680ac0a" + }, + "RobertaPreLayerNormForCausalLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForCausalLM", + "TFRobertaPreLayerNormForCausalLM" + ], + "sha": "73b6d4531b41f295a5d310d7aa44736004a59865" + }, + "RobertaPreLayerNormForMaskedLM": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForMaskedLM", + "TFRobertaPreLayerNormForMaskedLM" + ], + "sha": "a61723c77e5ab7adc95285e7823a0a49b99af395" + }, + "RobertaPreLayerNormForMultipleChoice": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForMultipleChoice", + "TFRobertaPreLayerNormForMultipleChoice" + ], + "sha": "3dcfa62e0771358c60232a18135bfe7c7f6d715e" + }, + "RobertaPreLayerNormForQuestionAnswering": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForQuestionAnswering", + "TFRobertaPreLayerNormForQuestionAnswering" + ], + "sha": "a8e76a5a50f7df60055e5ed6a1c3af2e7d34cf01" + }, + "RobertaPreLayerNormForSequenceClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForSequenceClassification", + "TFRobertaPreLayerNormForSequenceClassification" + ], + "sha": "7509cb0286d146ef2fc6beb8867ae31b92fb1b16" + }, + "RobertaPreLayerNormForTokenClassification": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormForTokenClassification", + "TFRobertaPreLayerNormForTokenClassification" + ], + "sha": "3ad5814ba126b41e18c1978c970e396fab6da9bf" + }, + "RobertaPreLayerNormModel": { + "tokenizer_classes": [ + "RobertaTokenizer", + "RobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RobertaPreLayerNormModel", + "TFRobertaPreLayerNormModel" + ], + "sha": "4830db38fd310404c5ab70bd00684eca0bc06ca8" + }, + "RwkvForCausalLM": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RwkvForCausalLM" + ], + "sha": "2f452fd46b39e39b1a6a95fa1d8232405bbb3e96" + }, + "RwkvModel": { + "tokenizer_classes": [ + "GPTNeoXTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "RwkvModel" + ], + "sha": "88a52c9437dc3c06f65a8252490be7eb91197804" + }, + "SEWDForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWDForCTC" + ], + "sha": "5c7495c77ae9e0f12c0de05d3a5fb95bdcd91768" + }, + "SEWDForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWDForSequenceClassification" + ], + "sha": "d6cbf1164ce1999fdaf3deeb7a6eba19a3b1f873" + }, + "SEWDModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWDModel" + ], + "sha": "dde4e02219449f149bb3403bbeae127cafaf9c79" + }, + "SEWForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWForCTC" + ], + "sha": "4477c7a277059fba08772acf91cf3e3dd3cb073b" + }, + "SEWForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWForSequenceClassification" + ], + "sha": "3b90fbb1c0c3848fed18f91a0169bb297a3e6619" + }, + "SEWModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SEWModel" + ], + "sha": "0a0fbb844eeefa0dce62bd05db30a2bb91e5dc88" + }, + "SamModel": { + "tokenizer_classes": [], + "processor_classes": [ + "SamImageProcessor" + ], + "model_classes": [ + "SamModel", + "TFSamModel" + ], + "sha": "eca8651bc84e5ac3b1b62e784b744a6bd1b82575" + }, + "SegformerForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "SegformerImageProcessor" + ], + "model_classes": [ + "SegformerForImageClassification", + "TFSegformerForImageClassification" + ], + "sha": "c566ae0ed382be4ed61ed6dacffa2ba663e9cc19" + }, + "SegformerForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "SegformerImageProcessor" + ], + "model_classes": [ + "SegformerForSemanticSegmentation", + "TFSegformerForSemanticSegmentation" + ], + "sha": "b73798972cdf24daafa858994713aca60e2bf90d" + }, + "SegformerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "SegformerImageProcessor" + ], + "model_classes": [ + "SegformerModel", + "TFSegformerModel" + ], + "sha": "3d4ba8ed2bdf801e6afa855b9d77893f2b7f9e10" + }, + "Speech2TextForConditionalGeneration": { + "tokenizer_classes": [ + "Speech2TextTokenizer" + ], + "processor_classes": [ + "Speech2TextFeatureExtractor" + ], + "model_classes": [ + "Speech2TextForConditionalGeneration", + "TFSpeech2TextForConditionalGeneration" + ], + "sha": "1da80293ec78762e136cf6dd64b652693f9ab364" + }, + "Speech2TextModel": { + "tokenizer_classes": [ + "Speech2TextTokenizer" + ], + "processor_classes": [ + "Speech2TextFeatureExtractor" + ], + "model_classes": [ + "Speech2TextModel", + "TFSpeech2TextModel" + ], + "sha": "7c6e63bd0c15dd99ef01573d4c43f90e4920cc91" + }, + "SpeechEncoderDecoderModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "SpeechEncoderDecoderModel" + ], + "sha": "78602ae0857728e95de4042bdca8a31ef818890a" + }, + "SpeechT5ForSpeechToText": { + "tokenizer_classes": [ + "SpeechT5Tokenizer" + ], + "processor_classes": [ + "SpeechT5FeatureExtractor" + ], + "model_classes": [ + "SpeechT5ForSpeechToText" + ], + "sha": "d46f0a83324e5865420a27a738ef203292de3479" + }, + "SpeechT5ForTextToSpeech": { + "tokenizer_classes": [ + "SpeechT5Tokenizer" + ], + "processor_classes": [ + "SpeechT5FeatureExtractor" + ], + "model_classes": [ + "SpeechT5ForTextToSpeech" + ], + "sha": "922e748d9e1ea256a8d9259782021cd3820d5924" + }, + "SpeechT5Model": { + "tokenizer_classes": [ + "SpeechT5Tokenizer" + ], + "processor_classes": [ + "SpeechT5FeatureExtractor" + ], + "model_classes": [ + "SpeechT5Model" + ], + "sha": "7b248f77ca88ffddcdb538e772f6de63a86a4f9b" + }, + "SplinterForPreTraining": { + "tokenizer_classes": [ + "SplinterTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "SplinterForPreTraining" + ], + "sha": "e8a94efa740f1d685fa553f49132c6f022de5389" + }, + "SplinterForQuestionAnswering": { + "tokenizer_classes": [ + "SplinterTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "SplinterForQuestionAnswering" + ], + "sha": "d038b7b683face4a361ab0f474d8a5b111c44c4d" + }, + "SplinterModel": { + "tokenizer_classes": [ + "SplinterTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "SplinterModel" + ], + "sha": "a35b13cbb7faba46dc265761bb839267eb53d248" + }, + "SqueezeBertForMaskedLM": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForMaskedLM" + ], + "sha": "33ce239408c22d2c98be63c9ab4607ef9ceb6d49" + }, + "SqueezeBertForMultipleChoice": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForMultipleChoice" + ], + "sha": "7e9e666896420c7839e27dcb280981d034ba4da5" + }, + "SqueezeBertForQuestionAnswering": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForQuestionAnswering" + ], + "sha": "bceb045a9ac6eb2ded7d358ed577c6dc28ea487a" + }, + "SqueezeBertForSequenceClassification": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForSequenceClassification" + ], + "sha": "c5aeb1f454a1d059d41a5f8dacaf784b9de0b899" + }, + "SqueezeBertForTokenClassification": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertForTokenClassification" + ], + "sha": "70ba60ca44a380e6aa983a37b163c57217219df7" + }, + "SqueezeBertModel": { + "tokenizer_classes": [ + "SqueezeBertTokenizer", + "SqueezeBertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SqueezeBertModel" + ], + "sha": "e0a3ac56a4047da3f921638252ead5e44438bbdb" + }, + "SwiftFormerForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwiftFormerForImageClassification" + ], + "sha": "a249b14a525d29e675b6e4af4baacd9ba7df7598" + }, + "SwiftFormerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwiftFormerModel" + ], + "sha": "25ba2d88c770533f8c69811d2a454a00c1d09f5d" + }, + "Swin2SRForImageSuperResolution": { + "tokenizer_classes": [], + "processor_classes": [ + "Swin2SRImageProcessor" + ], + "model_classes": [ + "Swin2SRForImageSuperResolution" + ], + "sha": "3a2780de0b455084c018ac8a62b56040969e26ec" + }, + "Swin2SRModel": { + "tokenizer_classes": [], + "processor_classes": [ + "Swin2SRImageProcessor" + ], + "model_classes": [ + "Swin2SRModel" + ], + "sha": "c67f6ecff9ef8675c3869c987277b0a1e040f4be" + }, + "SwinBackbone": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwinBackbone" + ], + "sha": "89b28b8ec05a7b3357be75a77eb7809e6fd5cfef" + }, + "SwinForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwinForImageClassification", + "TFSwinForImageClassification" + ], + "sha": "e3c2e80f380ef79781313981da1a993dd8b8d34d" + }, + "SwinForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwinForMaskedImageModeling", + "TFSwinForMaskedImageModeling" + ], + "sha": "d84b061fbace1bc6e697e3253e222de42053f978" + }, + "SwinModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "SwinModel", + "TFSwinModel" + ], + "sha": "23ff641295660ec4fea399be8aa1bc14565961f8" + }, + "Swinv2ForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "Swinv2ForImageClassification" + ], + "sha": "3fd755cdf4cf611db83f72f9c9b00eb9257a38ca" + }, + "Swinv2ForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "Swinv2ForMaskedImageModeling" + ], + "sha": "8375c31eb6231fde36ec6533a34ba5b28e296163" + }, + "Swinv2Model": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "Swinv2Model" + ], + "sha": "70aeb72e8a266f668c8b51a517ec01003b8d6804" + }, + "SwitchTransformersForConditionalGeneration": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SwitchTransformersForConditionalGeneration" + ], + "sha": "c8fcd2bb735894c78db7f1e5b51afc78aced7adb" + }, + "SwitchTransformersModel": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "SwitchTransformersModel" + ], + "sha": "275bbf6d389bfd0540b9f824c609c6b22a577328" + }, + "T5EncoderModel": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5EncoderModel", + "TFT5EncoderModel" + ], + "sha": "1c75090036a2b3740dfe2d570b889332ad8e59e8" + }, + "T5ForConditionalGeneration": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5ForConditionalGeneration", + "TFT5ForConditionalGeneration" + ], + "sha": "593fd6072a4e265f5cc73b1973cd8af76b261f29" + }, + "T5ForQuestionAnswering": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5ForQuestionAnswering" + ], + "sha": "b9edf2de494244ff032f67d2d7bdf6c591000c94" + }, + "T5ForSequenceClassification": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5ForSequenceClassification" + ], + "sha": "105b5c4c8e1efe927444108f1388c4f102ebad15" + }, + "T5Model": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "T5Model", + "TFT5Model" + ], + "sha": "eb3d20dda0ba77c1de618d78116a1a0c784c515c" + }, + "TableTransformerForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "TableTransformerForObjectDetection" + ], + "sha": "9cf1e3f5c3555a727672a32b49f8b96c5aa20be6" + }, + "TableTransformerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "DetrImageProcessor" + ], + "model_classes": [ + "TableTransformerModel" + ], + "sha": "7b446244d8739b0c29d98f7d537b15ad578577d5" + }, + "TapasForMaskedLM": { + "tokenizer_classes": [ + "TapasTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTapasForMaskedLM", + "TapasForMaskedLM" + ], + "sha": "2cedb92dd9a3dc37ffb7d35ad5190b110992577c" + }, + "TapasForQuestionAnswering": { + "tokenizer_classes": [ + "TapasTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTapasForQuestionAnswering", + "TapasForQuestionAnswering" + ], + "sha": "4cc91b9e5db662e6e392d8052587ae419896d72b" + }, + "TapasForSequenceClassification": { + "tokenizer_classes": [ + "TapasTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTapasForSequenceClassification", + "TapasForSequenceClassification" + ], + "sha": "7c37bfb87a6fce2f8604bb3cab2a14e09a285e14" + }, + "TapasModel": { + "tokenizer_classes": [ + "TapasTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTapasModel", + "TapasModel" + ], + "sha": "bc004af0a415afe1f566c3afe8dd4d48d08c1ce0" + }, + "TimesformerForVideoClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "TimesformerForVideoClassification" + ], + "sha": "0b3b8e314618d7af34fb44477745491b44bf556d" + }, + "TimesformerModel": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "TimesformerModel" + ], + "sha": "ea51f7ebb6426ad2b1fa1396e83f8e8ad5bc3b44" + }, + "TransfoXLForSequenceClassification": { + "tokenizer_classes": [ + "TransfoXLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTransfoXLForSequenceClassification", + "TransfoXLForSequenceClassification" + ], + "sha": "f3d370184350667d74056b979081b0bf5b0083c1" + }, + "TransfoXLLMHeadModel": { + "tokenizer_classes": [ + "TransfoXLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTransfoXLLMHeadModel", + "TransfoXLLMHeadModel" + ], + "sha": "e0d4cebcdde52d8d4c81782a1edc606830bd6afd" + }, + "TransfoXLModel": { + "tokenizer_classes": [ + "TransfoXLTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFTransfoXLModel", + "TransfoXLModel" + ], + "sha": "6938eeae35662a862accb01412dfc486454bdc8f" + }, + "TvltForPreTraining": { + "tokenizer_classes": [], + "processor_classes": [ + "TvltProcessor" + ], + "model_classes": [ + "TvltForPreTraining" + ], + "sha": "f7bd2833764eb6d55a921aaed81d3f21119016ae" + }, + "TvltModel": { + "tokenizer_classes": [], + "processor_classes": [ + "TvltProcessor" + ], + "model_classes": [ + "TvltModel" + ], + "sha": "c3cbf7a6159c038f333ce7adda2480ea3396b2b3" + }, + "UMT5EncoderModel": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "UMT5EncoderModel" + ], + "sha": "2894e49c9fbd17ea4b3dab56ec388be354c1a5f0" + }, + "UMT5ForQuestionAnswering": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "UMT5ForQuestionAnswering" + ], + "sha": "b381aa068a44200db539f2f48f4e34a5ed1cb093" + }, + "UMT5ForSequenceClassification": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "UMT5ForSequenceClassification" + ], + "sha": "aa9f77b7b3cff21425b7512e7c0f478af7b5db14" + }, + "UMT5Model": { + "tokenizer_classes": [ + "T5Tokenizer", + "T5TokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "UMT5Model" + ], + "sha": "9180d850b24e5494442a4f7a8ca1a4c102f9babd" + }, + "UniSpeechForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechForCTC" + ], + "sha": "102b56d76f4d74cface309801c0ad80892583751" + }, + "UniSpeechForPreTraining": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechForPreTraining" + ], + "sha": "830be5b3e85aaae7bcc961218e417c29743d6042" + }, + "UniSpeechForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechForSequenceClassification" + ], + "sha": "a30ac1516944757ccd8efcbcf94033a03f8708bf" + }, + "UniSpeechModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechModel" + ], + "sha": "18e170eb1091715b74ace28c8c380b6bf2b6202d" + }, + "UniSpeechSatForAudioFrameClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForAudioFrameClassification" + ], + "sha": "7eba5a1c6cd610928b27ecb217bb17c729a07a57" + }, + "UniSpeechSatForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForCTC" + ], + "sha": "a8617538d3a2ae990f022bb0c36b8428a4870822" + }, + "UniSpeechSatForPreTraining": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForPreTraining" + ], + "sha": "a772f66db0ab49e1050e524d7fcbe5106ebdaf96" + }, + "UniSpeechSatForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForSequenceClassification" + ], + "sha": "f1c16567bd829a6d8a7a2d167d22e9653149e625" + }, + "UniSpeechSatForXVector": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatForXVector" + ], + "sha": "71cb3780cf3678f74fba00e19df82df76dca6133" + }, + "UniSpeechSatModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "UniSpeechSatModel" + ], + "sha": "ea755bbc7c6c6aa649c58b4b000f243acbbd6b5a" + }, + "UperNetForSemanticSegmentation": { + "tokenizer_classes": [], + "processor_classes": [ + "SegformerImageProcessor" + ], + "model_classes": [ + "UperNetForSemanticSegmentation" + ], + "sha": "f1871cb388bc0b203f5397bfc06a373736c2fb9c" + }, + "VanForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "VanForImageClassification" + ], + "sha": "694eb147bc4768aeabeffbfb97732281b71a621d" + }, + "VanModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ConvNextImageProcessor" + ], + "model_classes": [ + "VanModel" + ], + "sha": "d8ac60ce952020f2b0355fc566d634b2c5ba635d" + }, + "ViTForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFViTForImageClassification", + "ViTForImageClassification" + ], + "sha": "5b3b44a3ed492070c273e481e30ecf4deddc5ec3" + }, + "ViTForMaskedImageModeling": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "ViTForMaskedImageModeling" + ], + "sha": "d984e0b432fe195c2c26952d4f249031e7b1e2ea" + }, + "ViTHybridForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTHybridImageProcessor" + ], + "model_classes": [ + "ViTHybridForImageClassification" + ], + "sha": "69c7c396032ffe60d54953b584394899fb95ccc1" + }, + "ViTHybridModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTHybridImageProcessor" + ], + "model_classes": [ + "ViTHybridModel" + ], + "sha": "077443bfefe40d625314dbd274d2ff8089624797" + }, + "ViTMAEForPreTraining": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFViTMAEForPreTraining", + "ViTMAEForPreTraining" + ], + "sha": "2d98d80d9c45eef0d5b6f5426d7196bb546fe9fc" + }, + "ViTMAEModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFViTMAEModel", + "ViTMAEModel" + ], + "sha": "c7c2f12c19d2dbec08851a9dac7485909629a5fd" + }, + "ViTMSNForImageClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "ViTMSNForImageClassification" + ], + "sha": "feda819aa7dbb55d850130f4cf1d210858d7eb89" + }, + "ViTMSNModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "ViTMSNModel" + ], + "sha": "0733abf168cb47a149821fdd2113d546e15c47de" + }, + "ViTModel": { + "tokenizer_classes": [], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFViTModel", + "ViTModel" + ], + "sha": "31817b7a64ebc3333fcd4801dfbb356ab07b13dd" + }, + "VideoMAEForPreTraining": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "VideoMAEForPreTraining" + ], + "sha": "9de66c4bb759dc7269a7af17bf70b3194550acaa" + }, + "VideoMAEForVideoClassification": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "VideoMAEForVideoClassification" + ], + "sha": "d3f743408386bc0ffe2d979de35335e87bc34aec" + }, + "VideoMAEModel": { + "tokenizer_classes": [], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "VideoMAEModel" + ], + "sha": "a2be96beba888817d92b67525601569d830342ff" + }, + "ViltForQuestionAnswering": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "ViltImageProcessor" + ], + "model_classes": [ + "ViltForQuestionAnswering" + ], + "sha": "faeffbf43da6621717d8b13e7ebe87d58d750cb2" + }, + "ViltModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "ViltImageProcessor" + ], + "model_classes": [ + "ViltModel" + ], + "sha": "3a89b7b5782947c4f4125162ffe1c9cc18c9c800" + }, + "VisionEncoderDecoderModel": { + "tokenizer_classes": [ + "GPT2Tokenizer", + "GPT2TokenizerFast" + ], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFVisionEncoderDecoderModel", + "VisionEncoderDecoderModel" + ], + "sha": "23917761070cf16b26a6d033b6bff9100bbc618b" + }, + "VisionTextDualEncoderModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [ + "ViTImageProcessor" + ], + "model_classes": [ + "TFVisionTextDualEncoderModel", + "VisionTextDualEncoderModel" + ], + "sha": "c3569ef17f66acbacb76f7ceb6f71e02d075dd6c" + }, + "VisualBertForPreTraining": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "VisualBertForPreTraining" + ], + "sha": "ce5a4d93ce762971cd216cda9aef8b9ce3f0450b" + }, + "VisualBertModel": { + "tokenizer_classes": [ + "BertTokenizer", + "BertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "VisualBertModel" + ], + "sha": "85020189fb7bf1217eb9370b09bca8ec5bcfdafa" + }, + "VitsModel": { + "tokenizer_classes": [ + "VitsTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "VitsModel" + ], + "sha": "b9a20ca5b6a7874576e485850260578895587dd2" + }, + "Wav2Vec2ConformerForAudioFrameClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForAudioFrameClassification" + ], + "sha": "e316a18a1d165b4cb51a7f28f8e8dab676da4b56" + }, + "Wav2Vec2ConformerForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForCTC" + ], + "sha": "a2ecb2985fcbb9f3ed000c12c1af6da36f5eaa3a" + }, + "Wav2Vec2ConformerForPreTraining": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForPreTraining" + ], + "sha": "099279b69e5da19efb05589804ccee210a0e57ae" + }, + "Wav2Vec2ConformerForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForSequenceClassification" + ], + "sha": "e8c1bca543c54bf15a6c026cb3761993b52cf617" + }, + "Wav2Vec2ConformerForXVector": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerForXVector" + ], + "sha": "ba206a55998f16e134960728bd02006eaf39114f" + }, + "Wav2Vec2ConformerModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ConformerModel" + ], + "sha": "ef2fe3aa8c23e6f8696e6612061aaddecae49994" + }, + "Wav2Vec2ForAudioFrameClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForAudioFrameClassification" + ], + "sha": "ab219f119e10f56e1059966c66d23f0df3c2c343" + }, + "Wav2Vec2ForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForCTC" + ], + "sha": "6245fbb1cb99cea5c4de1e73f81fba978fb275ac" + }, + "Wav2Vec2ForMaskedLM": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForMaskedLM" + ], + "sha": "e083cf4fefec4df3c241dbbe5e17a84a794a89bd" + }, + "Wav2Vec2ForPreTraining": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForPreTraining" + ], + "sha": "a8d71e216334260353ccbf5ce84cd6924f7457da" + }, + "Wav2Vec2ForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "TFWav2Vec2ForSequenceClassification", + "Wav2Vec2ForSequenceClassification" + ], + "sha": "2000b2022abcc37100241485f5872126b70164c9" + }, + "Wav2Vec2ForXVector": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "Wav2Vec2ForXVector" + ], + "sha": "f4c422db53aae061ea609f4407af7cd5b33c8942" + }, + "Wav2Vec2Model": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "TFWav2Vec2Model", + "Wav2Vec2Model" + ], + "sha": "7a998ee3ee0619a52828a79c3eed6872fd053f37" + }, + "WavLMForAudioFrameClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMForAudioFrameClassification" + ], + "sha": "b135610f8d5de0b1a5bf5ed7212966135c63d6ec" + }, + "WavLMForCTC": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMForCTC" + ], + "sha": "f1139c5ddf34d2327ae1f6917edd7da180b06971" + }, + "WavLMForSequenceClassification": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMForSequenceClassification" + ], + "sha": "4ba5f2019b46866ce2011c993194ebda60afc028" + }, + "WavLMForXVector": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMForXVector" + ], + "sha": "faf9264eac56a56d5510a0984d7e1146e4c8cf62" + }, + "WavLMModel": { + "tokenizer_classes": [ + "Wav2Vec2CTCTokenizer" + ], + "processor_classes": [ + "Wav2Vec2FeatureExtractor" + ], + "model_classes": [ + "WavLMModel" + ], + "sha": "e932275e37cb643be271f655bd1d649f4f4b4bd5" + }, + "WhisperForAudioClassification": { + "tokenizer_classes": [ + "WhisperTokenizer" + ], + "processor_classes": [ + "WhisperFeatureExtractor" + ], + "model_classes": [ + "WhisperForAudioClassification" + ], + "sha": "d71b13674b1a67443cd19d0594a3b5b1e5968f0d" + }, + "WhisperForCausalLM": { + "tokenizer_classes": [ + "WhisperTokenizer" + ], + "processor_classes": [ + "WhisperFeatureExtractor" + ], + "model_classes": [ + "WhisperForCausalLM" + ], + "sha": "e7febfd7f4512e029293c677e6d2633e23fc459a" + }, + "WhisperForConditionalGeneration": { + "tokenizer_classes": [ + "WhisperTokenizer", + "WhisperTokenizerFast" + ], + "processor_classes": [ + "WhisperFeatureExtractor" + ], + "model_classes": [ + "TFWhisperForConditionalGeneration", + "WhisperForConditionalGeneration" + ], + "sha": "598101b885b24508042d9292e54aa04bff96318e" + }, + "WhisperModel": { + "tokenizer_classes": [ + "WhisperTokenizer", + "WhisperTokenizerFast" + ], + "processor_classes": [ + "WhisperFeatureExtractor" + ], + "model_classes": [ + "TFWhisperModel", + "WhisperModel" + ], + "sha": "c04c50216bb6b0a8f4d55f2fa9f9f4cf61c8a77c" + }, + "XCLIPModel": { + "tokenizer_classes": [ + "CLIPTokenizer", + "CLIPTokenizerFast" + ], + "processor_classes": [ + "VideoMAEImageProcessor" + ], + "model_classes": [ + "XCLIPModel" + ], + "sha": "299ffffc6b94c3558bf7dbc38e24074c99490046" + }, + "XGLMForCausalLM": { + "tokenizer_classes": [ + "XGLMTokenizer", + "XGLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXGLMForCausalLM", + "XGLMForCausalLM" + ], + "sha": "d5381ce297c249d559937c6bb6316cf1fdad2613" + }, + "XGLMModel": { + "tokenizer_classes": [ + "XGLMTokenizer", + "XGLMTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXGLMModel", + "XGLMModel" + ], + "sha": "2b5cef167822cfaa558d259af1722e2f785cd3d5" + }, + "XLMForMultipleChoice": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMForMultipleChoice", + "XLMForMultipleChoice" + ], + "sha": "f0c8cc6462449ac9eb9b4158e433bd3c923db3af" + }, + "XLMForQuestionAnsweringSimple": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMForQuestionAnsweringSimple", + "XLMForQuestionAnsweringSimple" + ], + "sha": "82e93a2653cf3646eaaf02d8cc5f8ff9a4551523" + }, + "XLMForSequenceClassification": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMForSequenceClassification", + "XLMForSequenceClassification" + ], + "sha": "2d6892f5f703be9b481bca91477032bd0e36dbe5" + }, + "XLMForTokenClassification": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMForTokenClassification", + "XLMForTokenClassification" + ], + "sha": "9a591395e7a0643a03f5d2debb98caa3966e021c" + }, + "XLMModel": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMModel", + "XLMModel" + ], + "sha": "022b86df246414ff712475d9ca55db690ff1d3bf" + }, + "XLMRobertaXLForCausalLM": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForCausalLM" + ], + "sha": "fc05408e5b33a31638476ef337719dfbb7615ef3" + }, + "XLMRobertaXLForMaskedLM": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForMaskedLM" + ], + "sha": "e96f198eede757e5ae2c87632fdcfb341073ef6e" + }, + "XLMRobertaXLForMultipleChoice": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForMultipleChoice" + ], + "sha": "52732625f1bfbbb7cb4ba1cf0963de596d81822d" + }, + "XLMRobertaXLForQuestionAnswering": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForQuestionAnswering" + ], + "sha": "da388fdd2d28e0757eb0c2b2c612a8ff03af2223" + }, + "XLMRobertaXLForSequenceClassification": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForSequenceClassification" + ], + "sha": "980721187633bcf21ac0b8edbed933527f4611df" + }, + "XLMRobertaXLForTokenClassification": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLForTokenClassification" + ], + "sha": "37a97280faf6fef0bd946d3934d77a1b60fbf473" + }, + "XLMRobertaXLModel": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XLMRobertaXLModel" + ], + "sha": "8fbeb39a984912e47f5d24a31be61639031a0fc3" + }, + "XLMWithLMHeadModel": { + "tokenizer_classes": [ + "XLMTokenizer" + ], + "processor_classes": [], + "model_classes": [ + "TFXLMWithLMHeadModel", + "XLMWithLMHeadModel" + ], + "sha": "db70bdefbaf095e88b8097e4b601d9105a511afa" + }, + "XLNetForMultipleChoice": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetForMultipleChoice", + "XLNetForMultipleChoice" + ], + "sha": "8bb7e28d0cd1e93154d3232baf5e9c79acaf9f1a" + }, + "XLNetForQuestionAnsweringSimple": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetForQuestionAnsweringSimple", + "XLNetForQuestionAnsweringSimple" + ], + "sha": "fabd06a45d947f3d46f1b8dce2186cf3b27776dc" + }, + "XLNetForSequenceClassification": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetForSequenceClassification", + "XLNetForSequenceClassification" + ], + "sha": "e3c194f24537ebf2c474ade60becb9397696edec" + }, + "XLNetForTokenClassification": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetForTokenClassification", + "XLNetForTokenClassification" + ], + "sha": "16aa15029aa667046d504c4a88ceddfdd5b5fb40" + }, + "XLNetLMHeadModel": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetLMHeadModel", + "XLNetLMHeadModel" + ], + "sha": "c9a98cc982a16ca162832a8cbea25116479bb938" + }, + "XLNetModel": { + "tokenizer_classes": [ + "XLNetTokenizer", + "XLNetTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "TFXLNetModel", + "XLNetModel" + ], + "sha": "1d6e231942135faf32b8d9a97773d8f6c85ca561" + }, + "XmodForCausalLM": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForCausalLM" + ], + "sha": "c6b746071f2f067099a8fb4f57ce3c27a7e4b67d" + }, + "XmodForMaskedLM": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForMaskedLM" + ], + "sha": "e1085818f4ed3c6073b2038635e5f3061208923d" + }, + "XmodForMultipleChoice": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForMultipleChoice" + ], + "sha": "c63042cdf196be3fed846421b345d439b2483f69" + }, + "XmodForQuestionAnswering": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForQuestionAnswering" + ], + "sha": "75acd3071fae9978c82618cd0f090c87aabc1f23" + }, + "XmodForSequenceClassification": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForSequenceClassification" + ], + "sha": "523a16570be048618913ac17ccd00d343bcb5e99" + }, + "XmodForTokenClassification": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodForTokenClassification" + ], + "sha": "a0f0a02732b4579670dad11a69ae244ebd777b49" + }, + "XmodModel": { + "tokenizer_classes": [ + "XLMRobertaTokenizer", + "XLMRobertaTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "XmodModel" + ], + "sha": "bc286de0035450e7dcd6bcce78098a967b9c2b6c" + }, + "YolosForObjectDetection": { + "tokenizer_classes": [], + "processor_classes": [ + "YolosImageProcessor" + ], + "model_classes": [ + "YolosForObjectDetection" + ], + "sha": "0a4aae25bfbe8b5edd4815cb00d697a6ba7d2126" + }, + "YolosModel": { + "tokenizer_classes": [], + "processor_classes": [ + "YolosImageProcessor" + ], + "model_classes": [ + "YolosModel" + ], + "sha": "339bc51f1914f031a550e5f95095ed4a4c22a7de" + }, + "YosoForMaskedLM": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForMaskedLM" + ], + "sha": "cb291bedcbec199ea195f086e3ebea6fab026bba" + }, + "YosoForMultipleChoice": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForMultipleChoice" + ], + "sha": "cf2d3a3f0628bc9d0da68ea8de26b12016453fee" + }, + "YosoForQuestionAnswering": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForQuestionAnswering" + ], + "sha": "e8c3091f674588adfa3371b3de0427a9b39dd03f" + }, + "YosoForSequenceClassification": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForSequenceClassification" + ], + "sha": "88132cbaa1a9a87f65b6f9813c388011377f18cf" + }, + "YosoForTokenClassification": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoForTokenClassification" + ], + "sha": "fd2219856608d3dba70dc7b1a06af629903dec31" + }, + "YosoModel": { + "tokenizer_classes": [ + "AlbertTokenizerFast" + ], + "processor_classes": [], + "model_classes": [ + "YosoModel" + ], + "sha": "e144d9f1fe39c21eda1177702640e126892605ce" + } +} diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/add_dates.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/add_dates.py new file mode 100644 index 0000000000000000000000000000000000000000..9efa831d30a584c83e3fe1b64a2ca9b464592e59 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/add_dates.py @@ -0,0 +1,282 @@ +import argparse +import os +import re +import subprocess +from typing import Optional + +from huggingface_hub import paper_info + + +ROOT = os.getcwd().split("utils")[0] +DOCS_PATH = os.path.join(ROOT, "docs/source/en/model_doc") +MODELS_PATH = os.path.join(ROOT, "src/transformers/models") + +COPYRIGHT_DISCLAIMER = """""" + +ARXIV_PAPERS_NOT_IN_HF_PAPERS = { + "gemma3n.md": "2506.06644", + "xmod.md": "2205.06266", +} + + +def get_modified_cards() -> list[str]: + """Get the list of model names from modified files in docs/source/en/model_doc/""" + + result = subprocess.check_output(["git", "status", "--porcelain"], text=True) + + model_names = [] + for line in result.strip().split("\n"): + if line: + # Split on whitespace and take the last part (filename) + filename = line.split()[-1] + if filename.startswith("docs/source/en/model_doc/") and filename.endswith(".md"): + model_name = os.path.splitext(os.path.basename(filename))[0] + if model_name not in ["auto", "timm_wrapper"]: + model_names.append(model_name) + + return model_names + + +def get_paper_link(model_card: Optional[str], path: Optional[str]) -> str: + """Get the first paper link from the model card content.""" + + if model_card is not None and not model_card.endswith(".md"): + model_card = f"{model_card}.md" + file_path = path or os.path.join(DOCS_PATH, f"{model_card}") + model_card = os.path.basename(file_path) + with open(file_path, "r", encoding="utf-8") as f: + content = f.read() + + if "blog" in content or "report" in content or "post" in content: + print(f"Insert the release date of the blog post or technical report at the top of {model_card}") + return "blog" + + # Find known paper links + paper_ids = re.findall(r"https://huggingface\.co/papers/\d+\.\d+", content) + paper_ids += re.findall(r"https://arxiv\.org/abs/\d+\.\d+", content) + + # If no known paper links are found, look for other potential paper links + if len(paper_ids) == 0: + # Find all https links + all_https_links = re.findall(r"https://[^\s\)]+", content) + + # Filter out huggingface.co and github links + other_paper_links = [] + for link in all_https_links: + link = link.rstrip(".,;!?)") + if "huggingface.co" not in link and "github.com" not in link: + other_paper_links.append(link) + + # Remove duplicates while preserving order + other_paper_links = list(dict.fromkeys(other_paper_links)) + + if other_paper_links: + print(f"No Hugging Face or Arxiv papers found. The possible paper links found in {model_card}:") + for link in other_paper_links: + print(f" - {link}") + + return "No_paper" + + return paper_ids[0] + + +def get_first_commit_date(model_name: Optional[str]) -> str: + """Get the first commit date of the model's init file or model.md. This date is considered as the date the model was added to HF transformers""" + + if model_name.endswith(".md"): + model_name = f"{model_name[:-3]}" + + model_name_src = model_name + if "-" in model_name: + model_name_src = model_name.replace("-", "_") + file_path = os.path.join(MODELS_PATH, model_name_src, "__init__.py") + + # If the init file is not found (only true for legacy models), the doc's first commit date is used + if not os.path.exists(file_path): + file_path = os.path.join(DOCS_PATH, f"{model_name}.md") + + result = subprocess.check_output( + ["git", "log", "--reverse", "--pretty=format:%ad", "--date=iso", file_path], text=True + ) + return result.strip().split("\n")[0][:10] + + +def get_release_date(link: str) -> str: + if link.startswith("https://huggingface.co/papers/"): + link = link.replace("https://huggingface.co/papers/", "") + + try: + info = paper_info(link) + return info.published_at.date().isoformat() + except Exception as e: + print(f"Error fetching release date for the paper https://huggingface.co/papers/{link}: {e}") + + elif link.startswith("https://arxiv.org/abs/"): + print(f"This paper {link} is not yet available in Hugging Face papers, skipping the release date attachment.") + return r"{release_date}" + + +def replace_paper_links(file_path: str) -> bool: + """Replace arxiv links with huggingface links if valid, and replace hf.co with huggingface.co""" + + with open(file_path, "r", encoding="utf-8") as f: + content = f.read() + + model_card = os.path.basename(file_path) + original_content = content + + # Replace hf.co with huggingface.co + content = content.replace("https://hf.co/", "https://huggingface.co/") + + # Find all arxiv links + arxiv_links = re.findall(r"https://arxiv\.org/abs/(\d+\.\d+)", content) + + for paper_id in arxiv_links: + try: + # Check if paper exists on huggingface + paper_info(paper_id) + # If no exception, replace the link + old_link = f"https://arxiv.org/abs/{paper_id}" + new_link = f"https://huggingface.co/papers/{paper_id}" + content = content.replace(old_link, new_link) + print(f"Replaced {old_link} with {new_link}") + + except Exception: + # Paper not available on huggingface, keep arxiv link + print(f"Paper {paper_id} for {model_card} is not available on huggingface, keeping the arxiv link") + continue + + # Write back only if content changed + if content != original_content: + with open(file_path, "w", encoding="utf-8") as f: + f.write(content) + return True + return False + + +def insert_dates(model_card_list: list[str]): + """Insert release and commit dates into model cards""" + + for model_card in model_card_list: + if not model_card.endswith(".md"): + model_card = f"{model_card}.md" + + if model_card == "auto.md" or model_card == "timm_wrapper.md": + continue + + file_path = os.path.join(DOCS_PATH, model_card) + + # First replace arxiv paper links with hf paper link if possible + links_replaced = replace_paper_links(file_path) + if links_replaced: + print(f"Updated paper links in {model_card}") + + pattern = ( + r"\n\*This model was released on (.*) and added to Hugging Face Transformers on (\d{4}-\d{2}-\d{2})\.\*" + ) + + # Check if the copyright disclaimer sections exists, if not, add one with 2025 + with open(file_path, "r", encoding="utf-8") as f: + content = f.read() + markers = list(re.finditer(r"-->", content)) # Dates info is placed right below this marker + if len(markers) == 0: + print(f"No marker found in {model_card}. Adding copyright disclaimer to the top.") + + # Add copyright disclaimer to the very top of the file + content = COPYRIGHT_DISCLAIMER + "\n\n" + content + with open(file_path, "w", encoding="utf-8") as f: + f.write(content) + markers = list(re.finditer(r"-->", content)) + + hf_commit_date = get_first_commit_date(model_name=model_card) + + match = re.search(pattern, content) + + # If the dates info line already exists, only check and update the hf_commit_date, don't modify the existing release date + if match: + release_date = match.group(1) # The release date part + existing_hf_date = match.group(2) # The existing HF date part + if existing_hf_date != hf_commit_date: + old_line = match.group(0) # Full matched line + new_line = f"\n*This model was released on {release_date} and added to Hugging Face Transformers on {hf_commit_date}.*" + + content = content.replace(old_line, new_line) + with open(file_path, "w", encoding="utf-8") as f: + f.write(content) + + # If the dates info line does not exist, add it + else: + paper_link = get_paper_link(path=file_path) + release_date = "" + + if not (paper_link == "No_paper" or paper_link == "blog"): + release_date = get_release_date(paper_link) + else: + release_date = r"{release_date}" + + insert_index = markers[0].end() + + date_info = f"\n*This model was released on {release_date} and added to Hugging Face Transformers on {hf_commit_date}.*" + content = content[:insert_index] + date_info + content[insert_index:] + with open(file_path, "w", encoding="utf-8") as f: + f.write(content) + print(f"Added {model_card} release and commit dates.") + + +def get_all_model_cards(): + """Get all model cards from the docs path""" + + all_files = os.listdir(DOCS_PATH) + model_cards = [] + for file in all_files: + if file.endswith(".md"): + model_name = os.path.splitext(file)[0] + if model_name not in ["auto", "timm_wrapper"]: + model_cards.append(model_name) + return sorted(model_cards) + + +def main(all=False, auto=True, models=None): + if all: + model_cards = get_all_model_cards() + print(f"Processing all {len(model_cards)} model cards from docs directory") + elif auto: + model_cards = get_modified_cards() + if not model_cards: + print("No modified model cards found.") + return + print(f"Processing modified model cards: {model_cards}") + else: + model_cards = models + print(f"Processing specified model cards: {model_cards}") + + insert_dates(model_cards) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Add release and commit dates to model cards") + group = parser.add_mutually_exclusive_group(required=False) + group.add_argument( + "--auto", action="store_true", help="Automatically process modified model cards from git status" + ) + group.add_argument("--models", nargs="+", help="Specify model cards to process (without .md extension)") + group.add_argument("--all", action="store_true", help="Process all model cards in the docs directory") + + parser.set_defaults(auto=True) + args = parser.parse_args() + + main(args.all, args.auto, args.models) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/add_pipeline_model_mapping_to_test.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/add_pipeline_model_mapping_to_test.py new file mode 100644 index 0000000000000000000000000000000000000000..636f018eb5104fb922a4974d41f3fa8062e68758 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/add_pipeline_model_mapping_to_test.py @@ -0,0 +1,336 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +"""A script to add and/or update the attribute `pipeline_model_mapping` in model test files. + +This script will be (mostly) used in the following 2 situations: + + - run within a (scheduled) CI job to: + - check if model test files in the library have updated `pipeline_model_mapping`, + - and/or update test files and (possibly) open a GitHub pull request automatically + - being run by a `transformers` member to quickly check and update some particular test file(s) + +This script is **NOT** intended to be run (manually) by community contributors. +""" + +import argparse +import glob +import inspect +import os +import re +import unittest + +from get_test_info import get_test_classes + +from tests.test_pipeline_mixin import pipeline_test_mapping + + +PIPELINE_TEST_MAPPING = {} +for task in pipeline_test_mapping: + PIPELINE_TEST_MAPPING[task] = {"pt": None, "tf": None} + + +# DO **NOT** add item to this set (unless the reason is approved) +TEST_FILE_TO_IGNORE = { + "tests/models/esm/test_modeling_esmfold.py", # The pipeline test mapping is added to `test_modeling_esm.py` +} + + +def get_framework(test_class): + """Infer the framework from the test class `test_class`.""" + + if "ModelTesterMixin" in [x.__name__ for x in test_class.__bases__]: + return "pt" + elif "TFModelTesterMixin" in [x.__name__ for x in test_class.__bases__]: + return "tf" + elif "FlaxModelTesterMixin" in [x.__name__ for x in test_class.__bases__]: + return "flax" + else: + return None + + +def get_mapping_for_task(task, framework): + """Get mappings defined in `XXXPipelineTests` for the task `task`.""" + # Use the cached results + if PIPELINE_TEST_MAPPING[task].get(framework, None) is not None: + return PIPELINE_TEST_MAPPING[task][framework] + + pipeline_test_class = pipeline_test_mapping[task]["test"] + mapping = None + + if framework == "pt": + mapping = getattr(pipeline_test_class, "model_mapping", None) + elif framework == "tf": + mapping = getattr(pipeline_test_class, "tf_model_mapping", None) + + if mapping is not None: + mapping = dict(mapping.items()) + + # cache the results + PIPELINE_TEST_MAPPING[task][framework] = mapping + return mapping + + +def get_model_for_pipeline_test(test_class, task): + """Get the model architecture(s) related to the test class `test_class` for a pipeline `task`.""" + framework = get_framework(test_class) + if framework is None: + return None + mapping = get_mapping_for_task(task, framework) + if mapping is None: + return None + + config_classes = list({model_class.config_class for model_class in test_class.all_model_classes}) + if len(config_classes) != 1: + raise ValueError("There should be exactly one configuration class from `test_class.all_model_classes`.") + + # This could be a list/tuple of model classes, but it's rare. + model_class = mapping.get(config_classes[0], None) + if isinstance(model_class, (tuple, list)): + model_class = sorted(model_class, key=lambda x: x.__name__) + + return model_class + + +def get_pipeline_model_mapping(test_class): + """Get `pipeline_model_mapping` for `test_class`.""" + mapping = [(task, get_model_for_pipeline_test(test_class, task)) for task in pipeline_test_mapping] + mapping = sorted([(task, model) for task, model in mapping if model is not None], key=lambda x: x[0]) + + return dict(mapping) + + +def get_pipeline_model_mapping_string(test_class): + """Get `pipeline_model_mapping` for `test_class` as a string (to be added to the test file). + + This will be a 1-line string. After this is added to a test file, `make style` will format it beautifully. + """ + framework = get_framework(test_class) + if framework == "pt": + framework = "torch" + default_value = "{}" + + mapping = get_pipeline_model_mapping(test_class) + if len(mapping) == 0: + return "" + + texts = [] + for task, model_classes in mapping.items(): + if isinstance(model_classes, (tuple, list)): + # A list/tuple of model classes + value = "(" + ", ".join([x.__name__ for x in model_classes]) + ")" + else: + # A single model class + value = model_classes.__name__ + texts.append(f'"{task}": {value}') + text = "{" + ", ".join(texts) + "}" + text = f"pipeline_model_mapping = {text} if is_{framework}_available() else {default_value}" + + return text + + +def is_valid_test_class(test_class): + """Restrict to `XXXModelTesterMixin` and should be a subclass of `unittest.TestCase`.""" + base_class_names = {"ModelTesterMixin", "TFModelTesterMixin", "FlaxModelTesterMixin"} + if not issubclass(test_class, unittest.TestCase): + return False + return len(base_class_names.intersection([x.__name__ for x in test_class.__bases__])) > 0 + + +def find_test_class(test_file): + """Find a test class in `test_file` to which we will add `pipeline_model_mapping`.""" + test_classes = [x for x in get_test_classes(test_file) if is_valid_test_class(x)] + + target_test_class = None + for test_class in test_classes: + # If a test class has defined `pipeline_model_mapping`, let's take it + if getattr(test_class, "pipeline_model_mapping", None) is not None: + target_test_class = test_class + break + # Take the test class with the shortest name (just a heuristic) + if target_test_class is None and len(test_classes) > 0: + target_test_class = sorted(test_classes, key=lambda x: (len(x.__name__), x.__name__))[0] + + return target_test_class + + +def find_block_ending(lines, start_idx, indent_level): + end_idx = start_idx + for idx, line in enumerate(lines[start_idx:]): + indent = len(line) - len(line.lstrip()) + if idx == 0 or indent > indent_level or (indent == indent_level and line.strip() == ")"): + end_idx = start_idx + idx + elif idx > 0 and indent <= indent_level: + # Outside the definition block of `pipeline_model_mapping` + break + + return end_idx + + +def add_pipeline_model_mapping(test_class, overwrite=False): + """Add `pipeline_model_mapping` to `test_class`.""" + if getattr(test_class, "pipeline_model_mapping", None) is not None: + if not overwrite: + return "", -1 + + line_to_add = get_pipeline_model_mapping_string(test_class) + if len(line_to_add) == 0: + return "", -1 + line_to_add = line_to_add + "\n" + + # The code defined the class `test_class` + class_lines, class_start_line_no = inspect.getsourcelines(test_class) + # `inspect` gives the code for an object, including decorator(s) if any. + # We (only) need the exact line of the class definition. + for idx, line in enumerate(class_lines): + if line.lstrip().startswith("class "): + class_lines = class_lines[idx:] + class_start_line_no += idx + break + class_end_line_no = class_start_line_no + len(class_lines) - 1 + + # The index in `class_lines` that starts the definition of `all_model_classes`, `all_generative_model_classes` or + # `pipeline_model_mapping`. This assumes they are defined in such order, and we take the start index of the last + # block that appears in a `test_class`. + start_idx = None + # The indent level of the line at `class_lines[start_idx]` (if defined) + indent_level = 0 + # To record if `pipeline_model_mapping` is found in `test_class`. + def_line = None + for idx, line in enumerate(class_lines): + if line.strip().startswith("all_model_classes = "): + indent_level = len(line) - len(line.lstrip()) + start_idx = idx + elif line.strip().startswith("all_generative_model_classes = "): + indent_level = len(line) - len(line.lstrip()) + start_idx = idx + elif line.strip().startswith("pipeline_model_mapping = "): + indent_level = len(line) - len(line.lstrip()) + start_idx = idx + def_line = line + break + + if start_idx is None: + return "", -1 + # Find the ending index (inclusive) of the above found block. + end_idx = find_block_ending(class_lines, start_idx, indent_level) + + # Extract `is_xxx_available()` from existing blocks: some models require specific libraries like `timm` and use + # `is_timm_available()` instead of `is_torch_available()`. + # Keep leading and trailing whitespaces + r = re.compile(r"\s(is_\S+?_available\(\))\s") + for line in class_lines[start_idx : end_idx + 1]: + backend_condition = r.search(line) + if backend_condition is not None: + # replace the leading and trailing whitespaces to the space character " ". + target = " " + backend_condition[0][1:-1] + " " + line_to_add = r.sub(target, line_to_add) + break + + if def_line is None: + # `pipeline_model_mapping` is not defined. The target index is set to the ending index (inclusive) of + # `all_model_classes` or `all_generative_model_classes`. + target_idx = end_idx + else: + # `pipeline_model_mapping` is defined. The target index is set to be one **BEFORE** its start index. + target_idx = start_idx - 1 + # mark the lines of the currently existing `pipeline_model_mapping` to be removed. + for idx in range(start_idx, end_idx + 1): + # These lines are going to be removed before writing to the test file. + class_lines[idx] = None # noqa + + # Make sure the test class is a subclass of `PipelineTesterMixin`. + parent_classes = [x.__name__ for x in test_class.__bases__] + if "PipelineTesterMixin" not in parent_classes: + # Put `PipelineTesterMixin` just before `unittest.TestCase` + _parent_classes = [x for x in parent_classes if x != "TestCase"] + ["PipelineTesterMixin"] + if "TestCase" in parent_classes: + # Here we **assume** the original string is always with `unittest.TestCase`. + _parent_classes.append("unittest.TestCase") + parent_classes = ", ".join(_parent_classes) + for idx, line in enumerate(class_lines): + # Find the ending of the declaration of `test_class` + if line.strip().endswith("):"): + # mark the lines of the declaration of `test_class` to be removed + for _idx in range(idx + 1): + class_lines[_idx] = None # noqa + break + # Add the new, one-line, class declaration for `test_class` + class_lines[0] = f"class {test_class.__name__}({parent_classes}):\n" + + # Add indentation + line_to_add = " " * indent_level + line_to_add + # Insert `pipeline_model_mapping` to `class_lines`. + # (The line at `target_idx` should be kept by definition!) + class_lines = class_lines[: target_idx + 1] + [line_to_add] + class_lines[target_idx + 1 :] + # Remove the lines that are marked to be removed + class_lines = [x for x in class_lines if x is not None] + + # Move from test class to module (in order to write to the test file) + module_lines = inspect.getsourcelines(inspect.getmodule(test_class))[0] + # Be careful with the 1-off between line numbers and array indices + module_lines = module_lines[: class_start_line_no - 1] + class_lines + module_lines[class_end_line_no:] + code = "".join(module_lines) + + moddule_file = inspect.getsourcefile(test_class) + with open(moddule_file, "w", encoding="UTF-8", newline="\n") as fp: + fp.write(code) + + return line_to_add + + +def add_pipeline_model_mapping_to_test_file(test_file, overwrite=False): + """Add `pipeline_model_mapping` to `test_file`.""" + test_class = find_test_class(test_file) + if test_class: + add_pipeline_model_mapping(test_class, overwrite=overwrite) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--test_file", type=str, help="A path to the test file, starting with the repository's `tests` directory." + ) + parser.add_argument( + "--all", + action="store_true", + help="If to check and modify all test files.", + ) + parser.add_argument( + "--overwrite", + action="store_true", + help="If to overwrite a test class if it has already defined `pipeline_model_mapping`.", + ) + args = parser.parse_args() + + if not args.all and not args.test_file: + raise ValueError("Please specify either `test_file` or pass `--all` to check/modify all test files.") + elif args.all and args.test_file: + raise ValueError("Only one of `--test_file` and `--all` could be specified.") + + test_files = [] + if args.test_file: + test_files = [args.test_file] + else: + pattern = os.path.join("tests", "models", "**", "test_modeling_*.py") + for test_file in glob.glob(pattern): + # `Flax` is not concerned at this moment + if not test_file.startswith("test_modeling_flax_"): + test_files.append(test_file) + + for test_file in test_files: + if test_file in TEST_FILE_TO_IGNORE: + print(f"[SKIPPED] {test_file} is skipped as it is in `TEST_FILE_TO_IGNORE` in the file {__file__}.") + continue + add_pipeline_model_mapping_to_test_file(test_file, overwrite=args.overwrite) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_bad_commit.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_bad_commit.py new file mode 100644 index 0000000000000000000000000000000000000000..6750e29668cba7459933c2e810b4d95b79755fd4 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_bad_commit.py @@ -0,0 +1,220 @@ +#!/usr/bin/env python +# coding=utf-8 + +# Copyright 2024 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. +import argparse +import json +import os +import re +import subprocess + +import requests + + +def create_script(target_test): + """Create a python script to be run by `git bisect run` to determine if `target_test` passes or fails. + If a test is not found in a commit, the script with exit code `0` (i.e. `Success`). + + Args: + target_test (`str`): The test to check. + + Returns: + `str`: The script to be run by `git bisect run`. + """ + + script = f""" +import os +import subprocess + +result = subprocess.run( + ["python3", "-m", "pytest", "-v", "-rfEp", f"{target_test}"], + capture_output = True, + text=True, +) +print(result.stdout) + +if f"PASSED {target_test}" in result.stdout: + print("test passed") + exit(0) +elif len(result.stderr) > 0: + if "ERROR: file or directory not found: " in result.stderr: + print("test file or directory not found in this commit") + exit(0) + elif "ERROR: not found: " in result.stderr: + print("test not found in this commit") + exit(0) + else: + print(f"pytest failed to run: {{result.stderr}}") + exit(-1) +elif f"FAILED {target_test}" in result.stdout: + print("test failed") + exit(2) + +exit(0) +""" + + with open("target_script.py", "w") as fp: + fp.write(script.strip()) + + +def find_bad_commit(target_test, start_commit, end_commit): + """Find (backward) the earliest commit between `start_commit` and `end_commit` at which `target_test` fails. + + Args: + target_test (`str`): The test to check. + start_commit (`str`): The latest commit. + end_commit (`str`): The earliest commit. + + Returns: + `str`: The earliest commit at which `target_test` fails. + """ + + if start_commit == end_commit: + return start_commit + + create_script(target_test=target_test) + + bash = f""" +git bisect reset +git bisect start {start_commit} {end_commit} +git bisect run python3 target_script.py +""" + + with open("run_git_bisect.sh", "w") as fp: + fp.write(bash.strip()) + + result = subprocess.run( + ["bash", "run_git_bisect.sh"], + check=False, + capture_output=True, + text=True, + ) + print(result.stdout) + + if "error: bisect run failed" in result.stderr: + index = result.stderr.find("error: bisect run failed") + bash_error = result.stderr[index:] + + error_msg = f"Error when running git bisect:\nbash error: {bash_error}" + + pattern = "pytest failed to run: .+" + pytest_errors = re.findall(pattern, result.stdout) + if len(pytest_errors) > 0: + pytest_error = pytest_errors[0] + index = pytest_error.find("pytest failed to run: ") + index += len("pytest failed to run: ") + pytest_error = pytest_error[index:] + error_msg += f"pytest error: {pytest_error}" + + raise ValueError(error_msg) + + pattern = r"(.+) is the first bad commit" + commits = re.findall(pattern, result.stdout) + + bad_commit = None + if len(commits) > 0: + bad_commit = commits[0] + + print(f"Between `start_commit` {start_commit} and `end_commit` {end_commit}") + print(f"bad_commit: {bad_commit}\n") + + return bad_commit + + +def get_commit_info(commit): + """Get information for a commit via `api.github.com`.""" + pr_number = None + author = None + merged_author = None + + url = f"https://api.github.com/repos/huggingface/transformers/commits/{commit}/pulls" + pr_info_for_commit = requests.get(url).json() + + if len(pr_info_for_commit) > 0: + pr_number = pr_info_for_commit[0]["number"] + + url = f"https://api.github.com/repos/huggingface/transformers/pulls/{pr_number}" + pr_for_commit = requests.get(url).json() + author = pr_for_commit["user"]["login"] + if pr_for_commit["merged_by"] is not None: + merged_author = pr_for_commit["merged_by"]["login"] + + if author is None: + url = f"https://api.github.com/repos/huggingface/transformers/commits/{commit}" + commit_info = requests.get(url).json() + author = commit_info["author"]["login"] + + return {"commit": commit, "pr_number": pr_number, "author": author, "merged_by": merged_author} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--start_commit", type=str, required=True, help="The latest commit hash to check.") + parser.add_argument("--end_commit", type=str, required=True, help="The earliest commit hash to check.") + parser.add_argument("--test", type=str, help="The test to check.") + parser.add_argument("--file", type=str, help="The report file.") + parser.add_argument("--output_file", type=str, required=True, help="The path of the output file.") + args = parser.parse_args() + + print(f"start_commit: {args.start_commit}") + print(f"end_commit: {args.end_commit}") + + # `get_commit_info` uses `requests.get()` to request info. via `api.github.com` without using token. + # If there are many new failed tests in a workflow run, this script may fail at some point with `KeyError` at + # `pr_number = pr_info_for_commit[0]["number"]` due to the rate limit. + # Let's cache the commit info. and reuse them whenever possible. + commit_info_cache = {} + + if len({args.test is None, args.file is None}) != 2: + raise ValueError("Exactly one argument `test` or `file` must be specified.") + + if args.test is not None: + commit = find_bad_commit(target_test=args.test, start_commit=args.start_commit, end_commit=args.end_commit) + with open(args.output_file, "w", encoding="UTF-8") as fp: + fp.write(f"{args.test}\n{commit}") + elif os.path.isfile(args.file): + with open(args.file, "r", encoding="UTF-8") as fp: + reports = json.load(fp) + + for model in reports: + # TODO: make this script able to deal with both `single-gpu` and `multi-gpu` via a new argument. + reports[model].pop("multi-gpu", None) + failed_tests = reports[model]["single-gpu"] + + failed_tests_with_bad_commits = [] + for test in failed_tests: + commit = find_bad_commit(target_test=test, start_commit=args.start_commit, end_commit=args.end_commit) + info = {"test": test, "commit": commit} + + if commit in commit_info_cache: + commit_info = commit_info_cache[commit] + else: + commit_info = get_commit_info(commit) + commit_info_cache[commit] = commit_info + + info.update(commit_info) + failed_tests_with_bad_commits.append(info) + + # If no single-gpu test failures, remove the key + if len(failed_tests_with_bad_commits) > 0: + reports[model]["single-gpu"] = failed_tests_with_bad_commits + else: + reports[model].pop("single-gpu", None) + + # remove the models without any test failure + reports = {k: v for k, v in reports.items() if len(v) > 0} + + with open(args.output_file, "w", encoding="UTF-8") as fp: + json.dump(reports, fp, ensure_ascii=False, indent=4) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_build.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_build.py new file mode 100644 index 0000000000000000000000000000000000000000..929caeb7fa0653bf3e9469ad1b23091707f43012 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_build.py @@ -0,0 +1,49 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +import argparse +import importlib +from pathlib import Path + + +# Test all the extensions added in the setup +FILES_TO_FIND = [ + "kernels/rwkv/wkv_cuda.cu", + "kernels/rwkv/wkv_op.cpp", + "kernels/falcon_mamba/selective_scan_with_ln_interface.py", + "kernels/falcon_mamba/__init__.py", + "kernels/__init__.py", + "models/graphormer/algos_graphormer.pyx", +] + + +def test_custom_files_are_present(transformers_path): + # Test all the extensions added in the setup + for file in FILES_TO_FIND: + if not (transformers_path / file).exists(): + return False + return True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check_lib", action="store_true", help="Whether to check the build or the actual package.") + args = parser.parse_args() + if args.check_lib: + transformers_module = importlib.import_module("transformers") + transformers_path = Path(transformers_module.__file__).parent + else: + transformers_path = Path.cwd() / "build/lib/transformers" + if not test_custom_files_are_present(transformers_path): + raise ValueError("The built release does not contain the custom files. Fix this before going further!") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_config_attributes.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_config_attributes.py new file mode 100644 index 0000000000000000000000000000000000000000..34bf0511a320ddee2da0fbd6a63ac6455f3f9148 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_config_attributes.py @@ -0,0 +1,533 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. + +import inspect +import os +import re + +from transformers.configuration_utils import PretrainedConfig +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_config_docstrings.py +PATH_TO_TRANSFORMERS = "src/transformers" + + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + +CONFIG_MAPPING = transformers.models.auto.configuration_auto.CONFIG_MAPPING + +SPECIAL_CASES_TO_ALLOW = { + "xLSTMConfig": ["add_out_norm", "chunkwise_kernel", "sequence_kernel", "step_kernel"], + "Ernie4_5Config": ["tie_word_embeddings"], + "Ernie4_5_MoeConfig": ["tie_word_embeddings"], + "Lfm2Config": ["full_attn_idxs", "tie_word_embeddings"], + # used internally during generation to provide the custom logit processors with their necessary information + "DiaConfig": [ + "delay_pattern", + ], + # 'max_position_embeddings' is not used in modeling file, but needed for eval frameworks like Huggingface's lighteval (https://github.com/huggingface/lighteval/blob/af24080ea4f16eaf1683e353042a2dfc9099f038/src/lighteval/models/base_model.py#L264). + # periods and offsets are not used in modeling file, but used in the configuration file to define `layers_block_type` and `layers_num_experts`. + "BambaConfig": [ + "attn_layer_indices", + ], + "Dots1Config": ["max_window_layers"], + "JambaConfig": [ + "max_position_embeddings", + "attn_layer_offset", + "attn_layer_period", + "expert_layer_offset", + "expert_layer_period", + ], + "Qwen2Config": ["use_sliding_window", "max_window_layers"], + "Qwen2MoeConfig": ["use_sliding_window"], + "Qwen2VLTextConfig": ["use_sliding_window", "max_window_layers"], + "Qwen2_5_VLTextConfig": ["use_sliding_window", "max_window_layers"], + "Qwen2_5OmniTextConfig": ["use_sliding_window", "max_window_layers"], + "Qwen2_5OmniTalkerConfig": ["use_sliding_window", "max_window_layers"], + "Qwen3Config": ["max_window_layers", "use_sliding_window"], # now use `layer_types` instead + "Qwen3MoeConfig": ["max_window_layers", "use_sliding_window"], + # `cache_implementation` should be in the default generation config, but we don't yet support per-model + # generation configs (TODO joao) + "Gemma2Config": ["tie_word_embeddings", "cache_implementation"], + "Cohere2Config": ["cache_implementation"], + # Dropout with this value was declared but never used + "Phi3Config": ["embd_pdrop"], + # used to compute the property `self.chunk_length` + "EncodecConfig": ["overlap"], + # used to compute `frame_rate` + "XcodecConfig": ["sample_rate", "audio_channels"], + # used to compute the property `self.layers_block_type` + "RecurrentGemmaConfig": ["block_types"], + # used as in the config to define `intermediate_size` + "MambaConfig": ["expand"], + # used as in the config to define `intermediate_size` + "FalconMambaConfig": ["expand"], + # used as `self.bert_model = BertModel(config, ...)` + "DPRConfig": True, + "FuyuConfig": True, + # not used in modeling files, but it's an important information + "FSMTConfig": ["langs"], + # used internally in the configuration class file + "GPTNeoConfig": ["attention_types"], + # used internally in the configuration class file + "EsmConfig": ["is_folding_model"], + # used during training (despite we don't have training script for these models yet) + "Mask2FormerConfig": ["ignore_value"], + # `ignore_value` used during training (despite we don't have training script for these models yet) + # `norm` used in conversion script (despite not using in the modeling file) + "OneFormerConfig": ["ignore_value", "norm"], + # used internally in the configuration class file + "T5Config": ["feed_forward_proj"], + # used internally in the configuration class file + # `tokenizer_class` get default value `T5Tokenizer` intentionally + "MT5Config": ["feed_forward_proj", "tokenizer_class"], + "UMT5Config": ["feed_forward_proj", "tokenizer_class"], + # used internally in the configuration class file + "LongT5Config": ["feed_forward_proj"], + # used internally in the configuration class file + "Pop2PianoConfig": ["feed_forward_proj"], + # used internally in the configuration class file + "SwitchTransformersConfig": ["feed_forward_proj"], + # having default values other than `1e-5` - we can't fix them without breaking + "BioGptConfig": ["layer_norm_eps"], + # having default values other than `1e-5` - we can't fix them without breaking + "GLPNConfig": ["layer_norm_eps"], + # having default values other than `1e-5` - we can't fix them without breaking + "SegformerConfig": ["layer_norm_eps"], + # having default values other than `1e-5` - we can't fix them without breaking + "CvtConfig": ["layer_norm_eps"], + # having default values other than `1e-5` - we can't fix them without breaking + "PerceiverConfig": ["layer_norm_eps"], + # used internally to calculate the feature size + "InformerConfig": ["num_static_real_features", "num_time_features"], + # used internally to calculate the feature size + "TimeSeriesTransformerConfig": ["num_static_real_features", "num_time_features"], + # used internally to calculate the feature size + "AutoformerConfig": ["num_static_real_features", "num_time_features"], + # used internally to calculate `mlp_dim` + "SamVisionConfig": ["mlp_ratio"], + # used internally to calculate `mlp_dim` + "SamHQVisionConfig": ["mlp_ratio"], + # For (head) training, but so far not implemented + "ClapAudioConfig": ["num_classes"], + # Not used, but providing useful information to users + "SpeechT5HifiGanConfig": ["sampling_rate"], + # used internally in the configuration class file + "UdopConfig": ["feed_forward_proj"], + # Actually used in the config or generation config, in that case necessary for the sub-components generation + "SeamlessM4TConfig": [ + "max_new_tokens", + "t2u_max_new_tokens", + "t2u_decoder_attention_heads", + "t2u_decoder_ffn_dim", + "t2u_decoder_layers", + "t2u_encoder_attention_heads", + "t2u_encoder_ffn_dim", + "t2u_encoder_layers", + "t2u_max_position_embeddings", + ], + # Actually used in the config or generation config, in that case necessary for the sub-components generation + "SeamlessM4Tv2Config": [ + "max_new_tokens", + "t2u_decoder_attention_heads", + "t2u_decoder_ffn_dim", + "t2u_decoder_layers", + "t2u_encoder_attention_heads", + "t2u_encoder_ffn_dim", + "t2u_encoder_layers", + "t2u_max_position_embeddings", + "t2u_variance_pred_dropout", + "t2u_variance_predictor_embed_dim", + "t2u_variance_predictor_hidden_dim", + "t2u_variance_predictor_kernel_size", + ], + "ZambaConfig": [ + "tie_word_embeddings", + "attn_layer_offset", + "attn_layer_period", + ], + "MllamaTextConfig": [ + "initializer_range", + ], + "MllamaVisionConfig": [ + "initializer_range", + "supported_aspect_ratios", + ], + "ConditionalDetrConfig": [ + "bbox_cost", + "bbox_loss_coefficient", + "class_cost", + "cls_loss_coefficient", + "dice_loss_coefficient", + "focal_alpha", + "giou_cost", + "giou_loss_coefficient", + "mask_loss_coefficient", + ], + "DabDetrConfig": [ + "dilation", + "bbox_cost", + "bbox_loss_coefficient", + "class_cost", + "cls_loss_coefficient", + "focal_alpha", + "giou_cost", + "giou_loss_coefficient", + ], + "DetrConfig": [ + "bbox_cost", + "bbox_loss_coefficient", + "class_cost", + "dice_loss_coefficient", + "eos_coefficient", + "giou_cost", + "giou_loss_coefficient", + "mask_loss_coefficient", + ], + "DFineConfig": [ + "eos_coefficient", + "focal_loss_alpha", + "focal_loss_gamma", + "matcher_alpha", + "matcher_bbox_cost", + "matcher_class_cost", + "matcher_gamma", + "matcher_giou_cost", + "use_focal_loss", + "weight_loss_bbox", + "weight_loss_giou", + "weight_loss_vfl", + "weight_loss_fgl", + "weight_loss_ddf", + ], + "GroundingDinoConfig": [ + "bbox_cost", + "bbox_loss_coefficient", + "class_cost", + "focal_alpha", + "giou_cost", + "giou_loss_coefficient", + ], + "MMGroundingDinoConfig": [ + "bbox_cost", + "bbox_loss_coefficient", + "class_cost", + "focal_alpha", + "giou_cost", + "giou_loss_coefficient", + ], + "RTDetrConfig": [ + "eos_coefficient", + "focal_loss_alpha", + "focal_loss_gamma", + "matcher_alpha", + "matcher_bbox_cost", + "matcher_class_cost", + "matcher_gamma", + "matcher_giou_cost", + "use_focal_loss", + "weight_loss_bbox", + "weight_loss_giou", + "weight_loss_vfl", + ], + "RTDetrV2Config": [ + "eos_coefficient", + "focal_loss_alpha", + "focal_loss_gamma", + "matcher_alpha", + "matcher_bbox_cost", + "matcher_class_cost", + "matcher_gamma", + "matcher_giou_cost", + "use_focal_loss", + "weight_loss_bbox", + "weight_loss_giou", + "weight_loss_vfl", + ], + "YolosConfig": [ + "bbox_cost", + "bbox_loss_coefficient", + "class_cost", + "eos_coefficient", + "giou_cost", + "giou_loss_coefficient", + ], + "GPTNeoXConfig": ["rotary_emb_base"], + "Gemma3Config": ["boi_token_index", "eoi_token_index"], + "Gemma3TextConfig": ["cache_implementation", "tie_word_embeddings"], + "ShieldGemma2Config": [ + "boi_token_index", + "eoi_token_index", + "initializer_range", + "mm_tokens_per_image", + "text_config", + "vision_config", + ], + "Llama4Config": ["boi_token_index", "eoi_token_index"], + "Llama4TextConfig": [ + "interleave_moe_layer_step", + "no_rope_layer_interval", + "no_rope_layers", + "output_router_logits", + "router_aux_loss_coef", + "router_jitter_noise", + "cache_implementation", + "attention_chunk_size", + ], + "Llama4VisionConfig": ["multi_modal_projector_bias", "norm_eps"], + "ModernBertDecoderConfig": [ + "embedding_dropout", + "hidden_activation", + "initializer_cutoff_factor", + "intermediate_size", + "max_position_embeddings", + "mlp_bias", + "mlp_dropout", + "classifier_activation", + "global_attn_every_n_layers", + "local_attention", + "local_rope_theta", + ], + # position_embedding_type not used and deprecated. Should be deleted in v4.55 + "LayoutLMConfig": ["position_embedding_type"], + "MarkupLMConfig": ["position_embedding_type"], + "SmolLM3Config": ["no_rope_layer_interval"], + "Gemma3nVisionConfig": ["architecture", "do_pooling", "model_args"], # this is for use in `timm` +} + + +# TODO (ydshieh): Check the failing cases, try to fix them or move some cases to the above block once we are sure +SPECIAL_CASES_TO_ALLOW.update( + { + "CLIPSegConfig": True, + "DeformableDetrConfig": True, + "DinatConfig": True, + "DonutSwinConfig": True, + "FastSpeech2ConformerConfig": True, + "FSMTConfig": True, + "LayoutLMv2Config": True, + "MaskFormerSwinConfig": True, + "MT5Config": True, + # For backward compatibility with trust remote code models + "MptConfig": True, + "MptAttentionConfig": True, + "OneFormerConfig": True, + "PerceiverConfig": True, + "RagConfig": True, + "SpeechT5Config": True, + "SwinConfig": True, + "Swin2SRConfig": True, + "Swinv2Config": True, + "SwitchTransformersConfig": True, + "TableTransformerConfig": True, + "TapasConfig": True, + "UniSpeechConfig": True, + "UniSpeechSatConfig": True, + "WavLMConfig": True, + "WhisperConfig": True, + # TODO: @Arthur (for `alignment_head` and `alignment_layer`) + "JukeboxPriorConfig": True, + # TODO: @Younes (for `is_decoder`) + "Pix2StructTextConfig": True, + "IdeficsConfig": True, + "IdeficsVisionConfig": True, + "IdeficsPerceiverConfig": True, + # TODO: @Arthur/Joao (`hidden_act` unused) + "GptOssConfig": True, + } +) + + +def check_attribute_being_used(config_class, attributes, default_value, source_strings): + """Check if any name in `attributes` is used in one of the strings in `source_strings` + + Args: + config_class (`type`): + The configuration class for which the arguments in its `__init__` will be checked. + attributes (`List[str]`): + The name of an argument (or attribute) and its variant names if any. + default_value (`Any`): + A default value for the attribute in `attributes` assigned in the `__init__` of `config_class`. + source_strings (`List[str]`): + The python source code strings in the same modeling directory where `config_class` is defined. The file + containing the definition of `config_class` should be excluded. + """ + attribute_used = False + for attribute in attributes: + for modeling_source in source_strings: + # check if we can find `config.xxx`, `getattr(config, "xxx", ...)` or `getattr(self.config, "xxx", ...)` + if ( + f"config.{attribute}" in modeling_source + or f'getattr(config, "{attribute}"' in modeling_source + or f'getattr(self.config, "{attribute}"' in modeling_source + or ( + "TextConfig" in config_class.__name__ + and f"config.get_text_config().{attribute}" in modeling_source + ) + ): + attribute_used = True + # Deal with multi-line cases + elif ( + re.search( + rf'getattr[ \t\v\n\r\f]*\([ \t\v\n\r\f]*(self\.)?config,[ \t\v\n\r\f]*"{attribute}"', + modeling_source, + ) + is not None + ): + attribute_used = True + if attribute_used: + break + if attribute_used: + break + + # common and important attributes, even if they do not always appear in the modeling files + attributes_to_allow = [ + "initializer_range", + "bos_index", + "eos_index", + "pad_index", + "unk_index", + "mask_index", + "image_token_id", # for VLMs + "video_token_id", + "image_seq_length", + "video_seq_length", + "image_size", + "text_config", # may appear as `get_text_config()` + "use_cache", + "out_features", + "out_indices", + "sampling_rate", + # backbone related arguments passed to load_backbone + "use_pretrained_backbone", + "backbone", + "backbone_config", + "use_timm_backbone", + "backbone_kwargs", + # rope attributes may not appear directly in the modeling but are used + "rope_theta", + "partial_rotary_factor", + "pretraining_tp", + "boi_token_id", + "eoi_token_id", + ] + attributes_used_in_generation = ["encoder_no_repeat_ngram_size"] + + # Special cases to be allowed + case_allowed = True + if not attribute_used: + case_allowed = False + for attribute in attributes: + # Allow if the default value in the configuration class is different from the one in `PretrainedConfig` + if attribute in ["is_encoder_decoder"] and default_value is True: + case_allowed = True + elif attribute in ["tie_word_embeddings"] and default_value is False: + case_allowed = True + + # Allow cases without checking the default value in the configuration class + elif attribute in attributes_to_allow + attributes_used_in_generation: + case_allowed = True + elif attribute.endswith("_token_id"): + case_allowed = True + + # configuration class specific cases + if not case_allowed: + allowed_cases = SPECIAL_CASES_TO_ALLOW.get(config_class.__name__, []) + case_allowed = allowed_cases is True or attribute in allowed_cases + + return attribute_used or case_allowed + + +def check_config_attributes_being_used(config_class): + """Check the arguments in `__init__` of `config_class` are used in the modeling files in the same directory + + Args: + config_class (`type`): + The configuration class for which the arguments in its `__init__` will be checked. + """ + # Get the parameters in `__init__` of the configuration class, and the default values if any + signature = dict(inspect.signature(config_class.__init__).parameters) + parameter_names = [x for x in list(signature.keys()) if x not in ["self", "kwargs"]] + parameter_defaults = [signature[param].default for param in parameter_names] + + # If `attribute_map` exists, an attribute can have different names to be used in the modeling files, and as long + # as one variant is used, the test should pass + reversed_attribute_map = {} + if len(config_class.attribute_map) > 0: + reversed_attribute_map = {v: k for k, v in config_class.attribute_map.items()} + + # Get the path to modeling source files + config_source_file = inspect.getsourcefile(config_class) + model_dir = os.path.dirname(config_source_file) + # Let's check against all frameworks: as long as one framework uses an attribute, we are good. + modeling_paths = [os.path.join(model_dir, fn) for fn in os.listdir(model_dir) if fn.startswith("modeling_")] + + # Get the source code strings + modeling_sources = [] + for path in modeling_paths: + if os.path.isfile(path): + with open(path, encoding="utf8") as fp: + modeling_sources.append(fp.read()) + + unused_attributes = [] + for config_param, default_value in zip(parameter_names, parameter_defaults): + # `attributes` here is all the variant names for `config_param` + attributes = [config_param] + # some configuration classes have non-empty `attribute_map`, and both names could be used in the + # corresponding modeling files. As long as one of them appears, it is fine. + if config_param in reversed_attribute_map: + attributes.append(reversed_attribute_map[config_param]) + + if not check_attribute_being_used(config_class, attributes, default_value, modeling_sources): + unused_attributes.append(attributes[0]) + + return sorted(unused_attributes) + + +def check_config_attributes(): + """Check the arguments in `__init__` of all configuration classes are used in python files""" + configs_with_unused_attributes = {} + for _config_class in list(CONFIG_MAPPING.values()): + # Skip deprecated models + if "models.deprecated" in _config_class.__module__: + continue + # Some config classes are not in `CONFIG_MAPPING` (e.g. `CLIPVisionConfig`, `Blip2VisionConfig`, etc.) + config_classes_in_module = [ + cls + for name, cls in inspect.getmembers( + inspect.getmodule(_config_class), + lambda x: inspect.isclass(x) + and issubclass(x, PretrainedConfig) + and inspect.getmodule(x) == inspect.getmodule(_config_class), + ) + ] + for config_class in config_classes_in_module: + unused_attributes = check_config_attributes_being_used(config_class) + if len(unused_attributes) > 0: + configs_with_unused_attributes[config_class.__name__] = unused_attributes + + if len(configs_with_unused_attributes) > 0: + error = "The following configuration classes contain unused attributes in the corresponding modeling files:\n" + for name, attributes in configs_with_unused_attributes.items(): + error += f"{name}: {attributes}\n" + + raise ValueError(error) + + +if __name__ == "__main__": + check_config_attributes() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_config_docstrings.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_config_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..4a5d0395a20e376514a66357ffc211af7f8f57c5 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_config_docstrings.py @@ -0,0 +1,103 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# 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. + +import inspect +import re + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_config_docstrings.py +PATH_TO_TRANSFORMERS = "src/transformers" + + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + +CONFIG_MAPPING = transformers.models.auto.configuration_auto.CONFIG_MAPPING + +# Regex pattern used to find the checkpoint mentioned in the docstring of `config_class`. +# For example, `[google-bert/bert-base-uncased](https://huggingface.co/google-bert/bert-base-uncased)` +_re_checkpoint = re.compile(r"\[(.+?)\]\((https://huggingface\.co/.+?)\)") + + +CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK = { + "DecisionTransformerConfig", + "EncoderDecoderConfig", + "MusicgenConfig", + "RagConfig", + "SpeechEncoderDecoderConfig", + "TimmBackboneConfig", + "TimmWrapperConfig", + "VisionEncoderDecoderConfig", + "VisionTextDualEncoderConfig", + "LlamaConfig", + "GraniteConfig", + "GraniteMoeConfig", + "GraniteMoeHybridConfig", + "Qwen3MoeConfig", + "GraniteSpeechConfig", +} + + +def get_checkpoint_from_config_class(config_class): + checkpoint = None + + # source code of `config_class` + config_source = inspect.getsource(config_class) + checkpoints = _re_checkpoint.findall(config_source) + + # Each `checkpoint` is a tuple of a checkpoint name and a checkpoint link. + # For example, `('google-bert/bert-base-uncased', 'https://huggingface.co/google-bert/bert-base-uncased')` + for ckpt_name, ckpt_link in checkpoints: + # allow the link to end with `/` + if ckpt_link.endswith("/"): + ckpt_link = ckpt_link[:-1] + + # verify the checkpoint name corresponds to the checkpoint link + ckpt_link_from_name = f"https://huggingface.co/{ckpt_name}" + if ckpt_link == ckpt_link_from_name: + checkpoint = ckpt_name + break + + return checkpoint + + +def check_config_docstrings_have_checkpoints(): + configs_without_checkpoint = [] + + for config_class in list(CONFIG_MAPPING.values()): + # Skip deprecated models + if "models.deprecated" in config_class.__module__: + continue + checkpoint = get_checkpoint_from_config_class(config_class) + + name = config_class.__name__ + if checkpoint is None and name not in CONFIG_CLASSES_TO_IGNORE_FOR_DOCSTRING_CHECKPOINT_CHECK: + configs_without_checkpoint.append(name) + + if len(configs_without_checkpoint) > 0: + message = "\n".join(sorted(configs_without_checkpoint)) + raise ValueError( + f"The following configurations don't contain any valid checkpoint:\n{message}\n\n" + "The requirement is to include a link pointing to one of the models of this architecture in the " + "docstring of the config classes listed above. The link should have be a markdown format like " + "[myorg/mymodel](https://huggingface.co/myorg/mymodel)." + ) + + +if __name__ == "__main__": + check_config_docstrings_have_checkpoints() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_copies.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_copies.py new file mode 100644 index 0000000000000000000000000000000000000000..e48163421ac4f11fd40466af721babd58e840bad --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_copies.py @@ -0,0 +1,1081 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. +""" +Utility that checks whether the copies defined in the library match the original or not. This includes: +- All code commented with `# Copied from` comments, +- The list of models in the main README.md matches the ones in the localized READMEs, +- Files that are registered as full copies of one another in the `FULL_COPIES` constant of this script. + +This also checks the list of models in the README is complete (has all models) and adds a line to complete if there is +a model missing. + +Use from the root of the repo with: + +```bash +python utils/check_copies.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`) or + +```bash +python utils/check_copies.py --fix_and_overwrite +``` + +for a check that will fix all inconsistencies automatically (used by `make fix-copies`). +""" + +import argparse +import glob +import os +import re +import subprocess +from collections import OrderedDict +from typing import Optional, Union + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_copies.py +TRANSFORMERS_PATH = "src/transformers" +MODEL_TEST_PATH = "tests/models" +PATH_TO_DOCS = "docs/source/en" +REPO_PATH = "." + +# Mapping for files that are full copies of others (keys are copies, values the file to keep them up to data with) +FULL_COPIES = { + "examples/tensorflow/question-answering/utils_qa.py": "examples/pytorch/question-answering/utils_qa.py", + "examples/flax/question-answering/utils_qa.py": "examples/pytorch/question-answering/utils_qa.py", +} + + +LOCALIZED_READMES = { + # If the introduction or the conclusion of the list change, the prompts may need to be updated. + "README.md": { + "start_prompt": "🤗 Transformers currently provides the following architectures", + "end_prompt": "1. Want to contribute a new model?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_zh-hans.md": { + "start_prompt": "🤗 Transformers 目前支持如下的架构", + "end_prompt": "1. 想要贡献新的模型?", + "format_model_list": ( + "**[{title}]({model_link})** (来自 {paper_affiliations}) 伴随论文 {paper_title_link} 由 {paper_authors}" + " 发布。{supplements}" + ), + }, + "README_zh-hant.md": { + "start_prompt": "🤗 Transformers 目前支援以下的架構", + "end_prompt": "1. 想要貢獻新的模型?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_ko.md": { + "start_prompt": "🤗 Transformers는 다음 모델들을 제공합니다", + "end_prompt": "1. 새로운 모델을 올리고 싶나요?", + "format_model_list": ( + "**[{title}]({model_link})** ({paper_affiliations} 에서 제공)은 {paper_authors}.{supplements}의" + " {paper_title_link}논문과 함께 발표했습니다." + ), + }, + "README_es.md": { + "start_prompt": "🤗 Transformers actualmente proporciona las siguientes arquitecturas", + "end_prompt": "1. ¿Quieres aportar un nuevo modelo?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_ja.md": { + "start_prompt": "🤗Transformersは現在、以下のアーキテクチャを提供しています", + "end_prompt": "1. 新しいモデルを投稿したいですか?", + "format_model_list": ( + "**[{title}]({model_link})** ({paper_affiliations} から) {paper_authors}.{supplements} から公開された研究論文" + " {paper_title_link}" + ), + }, + "README_hd.md": { + "start_prompt": "🤗 ट्रांसफॉर्मर वर्तमान में निम्नलिखित आर्किटेक्चर का समर्थन करते हैं", + "end_prompt": "1. एक नए मॉडल में योगदान देना चाहते हैं?", + "format_model_list": ( + "**[{title}]({model_link})** ({paper_affiliations} से) {paper_authors}.{supplements} द्वारा" + "अनुसंधान पत्र {paper_title_link} के साथ जारी किया गया" + ), + }, + "README_ru.md": { + "start_prompt": "🤗 В настоящее время Transformers предоставляет следующие архитектуры", + "end_prompt": "1. Хотите внести новую модель?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_pt-br.md": { + "start_prompt": "🤗 Transformers atualmente fornece as seguintes arquiteturas", + "end_prompt": "1. Quer contribuir com um novo modelo?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_te.md": { + "start_prompt": "🤗 ట్రాన్స్‌ఫార్మర్లు ప్రస్తుతం కింది ఆర్కిటెక్చర్‌లను అందజేస్తున్నాయి", + "end_prompt": "1. కొత్త మోడల్‌ను అందించాలనుకుంటున్నారా?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_fr.md": { + "start_prompt": "🤗 Transformers fournit actuellement les architectures suivantes", + "end_prompt": "1. Vous souhaitez contribuer avec un nouveau modèle ?", + "format_model_list": ( + "**[{title}]({model_link})** (de {paper_affiliations}) publié dans l'article {paper_title_link} par" + "{paper_authors}.{supplements}" + ), + }, + "README_de.md": { + "start_prompt": "🤗 Transformers bietet derzeit die folgenden Architekturen an", + "end_prompt": "1. Möchten Sie ein neues Modell beitragen?", + "format_model_list": ( + "**[{title}]({model_link})** (from {paper_affiliations}) released with the paper {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, + "README_vi.md": { + "start_prompt": "🤗 Transformers hiện đang cung cấp các kiến trúc sau đây", + "end_prompt": "1. Muốn đóng góp một mô hình mới?", + "format_model_list": ( + "**[{title}]({model_link})** (từ {paper_affiliations}) được phát hành với bài báo {paper_title_link} by" + " {paper_authors}.{supplements}" + ), + }, +} + +# This is to make sure the transformers module imported is the one in the repo. +transformers_module = direct_transformers_import(TRANSFORMERS_PATH) + + +def _is_definition_header_ending_line(line: str) -> bool: + # Helper function. Returns `True` if `line` is the end parenthesis of a class/function definition + return re.search(r"^\s*\)(\s*->.*:|:)\s*$", line) is not None + + +def _should_continue(line: str, indent: str) -> bool: + # Helper function. Returns `True` if `line` is empty, starts with the `indent` or is the end parenthesis of a + # class/function definition + return line.startswith(indent) or len(line.strip()) == 0 or _is_definition_header_ending_line(line) + + +def _sanity_check_splits(splits_1, splits_2, is_class, filename): + """Check the two (inner) block structures of the corresponding code block given by `split_code_into_blocks` match. + + For the case of `class`, they must be of one of the following 3 cases: + + - a single block without name: + + class foo: + a = 1 + + - a consecutive sequence of (1 or more) blocks with name + + class foo: + + def f(x): + return x + + - a block without name, followed by a consecutive sequence of (1 or more) blocks with name + + class foo: + a = 1 + + def f(x): + return x + + def g(x): + return None + + The 2 code snippets that give `splits_1` and `splits_2` have to be in the same case to pass this check, but the + number of blocks with name in the consecutive sequence is not taken into account. + + For the case of `function or method`, we don't require it to be in one of the above 3 cases. However, the structure + of`splits_1` and `splits_2` have to match exactly. In particular, the number of blocks with name in a consecutive + sequence is taken into account. + """ + block_names_1 = [] + block_names_2 = [] + + for block in splits_1[1:]: + if block[0].startswith("_block_without_name_"): + block_names_1.append("block_without_name") + elif not block[0].startswith("_empty_block_") and ( + not is_class or len(block_names_1) == 0 or block_names_1[-1].startswith("block_without_name") + ): + block_names_1.append("block_with_name") + + for block in splits_2[1:]: + if block[0].startswith("_block_without_name_"): + block_names_2.append("block_without_name") + elif not block[0].startswith("_empty_block_") and ( + not is_class or len(block_names_2) == 0 or block_names_2[-1].startswith("block_without_name") + ): + block_names_2.append("block_with_name") + + if is_class: + if block_names_1 not in [ + ["block_without_name"], + ["block_with_name"], + ["block_without_name", "block_with_name"], + ]: + raise ValueError( + f"""Class defined in {filename} doesn't have the expected structure. + See the docstring of `_sanity_check_splits` in the file `utils/check_copies.py`""", + ) + + if block_names_1 != block_names_2: + raise ValueError(f"In {filename}, two code blocks expected to be copies have different structures.") + + +def find_block_end(lines: list[str], start_index: int, indent: int) -> int: + """ + Find the end of the class/func block starting at `start_index` in a source code (defined by `lines`). + + Args: + lines (`List[str]`): + The source code, represented by a list of lines. + start_index (`int`): + The starting index of the target class/func block. + indent (`int`): + The indent of the class/func body. + + Returns: + `int`: The index of the block's ending line plus by 1 (i.e. exclusive). + """ + indent = " " * indent + # enter the block body + line_index = start_index + 1 + + while line_index < len(lines) and _should_continue(lines[line_index], indent): + line_index += 1 + # Clean up empty lines at the end (if any). + while len(lines[line_index - 1]) <= 1: + line_index -= 1 + + return line_index + + +def split_code_into_blocks( + lines: list[str], start_index: int, end_index: int, indent: int, backtrace: bool = False +) -> list[tuple[str, int, int]]: + """ + Split the class/func block starting at `start_index` in a source code (defined by `lines`) into *inner blocks*. + + The block's header is included as the first element. The contiguous regions (without empty lines) that are not + inside any inner block are included as blocks. The contiguous regions of empty lines that are not inside any inner + block are also included as (dummy) blocks. + + Args: + lines (`List[str]`): + The source code, represented by a list of lines. + start_index (`int`): + The starting index of the target class/func block. + end_index (`int`): + The ending index of the target class/func block. + indent (`int`): + The indent of the class/func body. + backtrace (`bool`, *optional*, defaults to `False`): + Whether or not to include the lines before the inner class/func block's header (e.g. comments, decorators, + etc.) until an empty line is encountered. + + Returns: + `List[Tuple[str, int, int]]`: A list of elements with the form `(block_name, start_index, end_index)`. + """ + splits = [] + # `indent - 4` is the indent level of the target class/func header + try: + target_block_name = re.search( + rf"^{' ' * (indent - 4)}((class|def)\s+\S+)(\(|\:)", lines[start_index] + ).groups()[0] + except Exception: + start_context = min(start_index - 10, 0) + end_context = min(end_index + 10, len(lines)) + raise ValueError( + f"Tried to split a class or function. It did not work. Error comes from line {start_index}: \n```\n" + + "".join(lines[start_context:end_context]) + + "```\n" + ) + + # from now on, the `block` means inner blocks unless explicitly specified + indent_str = " " * indent + block_without_name_idx = 0 + empty_block_idx = 0 + + # Find the lines for the definition header + index = start_index + if "(" in lines[start_index] and "):" not in lines[start_index] in lines[start_index]: + while index < end_index: + if _is_definition_header_ending_line(lines[index]): + break + index += 1 + + # the first line outside the definition header + index += 1 + splits.append((target_block_name, start_index, index)) + + block_start_index, prev_block_end_index = index, index + while index < end_index: + # if found, it will be an inner block + block_found = re.search(rf"^{indent_str}((class|def)\s+\S+)(\(|\:)", lines[index]) + if block_found: + name = block_found.groups()[0] + + block_end_index = find_block_end(lines, index, indent + 4) + + # backtrace to include the lines before the found block's definition header (e.g. comments, decorators, + # etc.) until an empty line is encountered. + block_start_index = index + if index > prev_block_end_index and backtrace: + idx = index - 1 + for idx in range(index - 1, prev_block_end_index - 2, -1): + if not (len(lines[idx].strip()) > 0 and lines[idx].startswith(indent_str)): + break + idx += 1 + if idx < index: + block_start_index = idx + + # between the current found block and the previous found block + if block_start_index > prev_block_end_index: + # give it a dummy name + if len("".join(lines[prev_block_end_index:block_start_index]).strip()) == 0: + prev_block_name = f"_empty_block_{empty_block_idx}" + empty_block_idx += 1 + else: + prev_block_name = f"_block_without_name_{block_without_name_idx}" + block_without_name_idx += 1 + # Add it as a block + splits.append((prev_block_name, prev_block_end_index, block_start_index)) + + # Add the current found block + splits.append((name, block_start_index, block_end_index)) + prev_block_end_index = block_end_index + index = block_end_index - 1 + + index += 1 + + if index > prev_block_end_index: + if len("".join(lines[prev_block_end_index:index]).strip()) == 0: + prev_block_name = f"_empty_block_{empty_block_idx}" + else: + prev_block_name = f"_block_without_name_{block_without_name_idx}" + splits.append((prev_block_name, prev_block_end_index, index)) + + return splits + + +def find_code_in_transformers( + object_name: str, base_path: Optional[str] = None, return_indices: bool = False +) -> Union[str, tuple[list[str], int, int]]: + """ + Find and return the source code of an object. + + Args: + object_name (`str`): + The name of the object we want the source code of. + base_path (`str`, *optional*): + The path to the base folder where files are checked. If not set, it will be set to `TRANSFORMERS_PATH`. + return_indices(`bool`, *optional*, defaults to `False`): + If `False`, will only return the code (as a string), otherwise it will also return the whole lines of the + file where the object specified by `object_name` is defined, together the start/end indices of the block in + the file that defines the object. + + Returns: + `Union[str, Tuple[List[str], int, int]]`: If `return_indices=False`, only the source code of the object will be + returned. Otherwise, it also returns the whole lines of the file where the object specified by `object_name` is + defined, together the start/end indices of the block in the file that defines the object. + """ + parts = object_name.split(".") + i = 0 + + # We can't set this as the default value in the argument, otherwise `CopyCheckTester` will fail, as it uses a + # patched temp directory. + if base_path is None: + base_path = TRANSFORMERS_PATH + + # Detail: the `Copied from` statement is originally designed to work with the last part of `TRANSFORMERS_PATH`, + # (which is `transformers`). The same should be applied for `MODEL_TEST_PATH`. However, its last part is `models` + # (to only check and search in it) which is a bit confusing. So we keep the copied statement starting with + # `tests.models.` and change it to `tests` here. + if base_path == MODEL_TEST_PATH: + base_path = "tests" + + # First let's find the module where our object lives. + module = parts[i] + while i < len(parts) and not os.path.isfile(os.path.join(base_path, f"{module}.py")): + i += 1 + if i < len(parts): + module = os.path.join(module, parts[i]) + if i >= len(parts): + raise ValueError( + f"`object_name` should begin with the name of a module of transformers but got {object_name}." + ) + + with open(os.path.join(base_path, f"{module}.py"), "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Now let's find the class / func in the code! + indent = "" + line_index = 0 + for name in parts[i + 1 :]: + while ( + line_index < len(lines) and re.search(rf"^{indent}(class|def)\s+{name}(\(|\:)", lines[line_index]) is None + ): + line_index += 1 + # find the target specified in the current level in `parts` -> increase `indent` so we can search the next + indent += " " + # the index of the first line in the (currently found) block *body* + line_index += 1 + + if line_index >= len(lines): + raise ValueError(f" {object_name} does not match any function or class in {module}.") + + # `indent` is already one level deeper than the (found) class/func block's definition header + + # We found the beginning of the class / func, now let's find the end (when the indent diminishes). + # `start_index` is the index of the class/func block's definition header + start_index = line_index - 1 + end_index = find_block_end(lines, start_index, len(indent)) + + code = "".join(lines[start_index:end_index]) + return (code, (lines, start_index, end_index)) if return_indices else code + + +def replace_code(code: str, replace_pattern: str) -> str: + """Replace `code` by a pattern of the form `with X1->X2,Y1->Y2,Z1->Z2`. + + Args: + code (`str`): The code to be modified. + replace_pattern (`str`): The pattern used to modify `code`. + + Returns: + `str`: The modified code. + """ + if len(replace_pattern) > 0: + patterns = replace_pattern.replace("with", "").split(",") + patterns = [_re_replace_pattern.search(p) for p in patterns] + for pattern in patterns: + if pattern is None: + continue + obj1, obj2, option = pattern.groups() + code = re.sub(obj1, obj2, code) + if option.strip() == "all-casing": + code = re.sub(obj1.lower(), obj2.lower(), code) + code = re.sub(obj1.upper(), obj2.upper(), code) + + return code + + +def find_code_and_splits(object_name: str, base_path: str, buffer: Optional[dict] = None): + """Find the code of an object (specified by `object_name`) and split it into blocks. + + Args: + object_name (`str`): + The name of the object, e.g. `transformers.models.bert.modeling_bert.BertAttention` or + `tests.models.llama.test_modeling_llama.LlamaModelTest.test_config`. + base_path (`str`): + The path to the base directory within which the search will be performed. It could be either + `TRANSFORMERS_PATH` or `MODEL_TEST_PATH`. + buffer (`dict`, *optional*): + The buffer used to store the previous results in order to speed up the process. + + Returns: + lines (`List[str]`): + The lines of the whole file where the object is defined. + code (`str`): + The object's code. + code_splits (`List[Tuple[str, int, int]]`): + `code` splitted into blocks. See `split_code_into_blocks`. + """ + if buffer is None: + buffer = {} + + if (object_name, base_path) in buffer: + lines, code, code_splits = buffer[(object_name, base_path)] + else: + code, (lines, target_start_index, target_end_index) = find_code_in_transformers( + object_name, base_path=base_path, return_indices=True + ) + indent = get_indent(code) + + # Split the code into blocks + # `indent` is the indent of the class/func definition header, but `code_splits` expects the indent level of the + # block body. + code_splits = split_code_into_blocks( + lines, target_start_index, target_end_index, len(indent) + 4, backtrace=True + ) + buffer[(object_name, base_path)] = lines, code, code_splits + + return lines, code, code_splits + + +_re_copy_warning = re.compile(r"^(\s*)#\s*Copied from\s+transformers\.(\S+\.\S+)\s*($|\S.*$)") +_re_copy_warning_for_test_file = re.compile(r"^(\s*)#\s*Copied from\s+tests\.(\S+\.\S+)\s*($|\S.*$)") +_re_replace_pattern = re.compile(r"^\s*(\S+)->(\S+)(\s+.*|$)") +_re_fill_pattern = re.compile(r"]*>") + + +def get_indent(code: str) -> str: + """ + Find the indent in the first non empty line in a code sample. + + Args: + code (`str`): The code to inspect. + + Returns: + `str`: The indent looked at (as string). + """ + lines = code.split("\n") + idx = 0 + while idx < len(lines) and len(lines[idx]) == 0: + idx += 1 + if idx < len(lines): + return re.search(r"^(\s*)\S", lines[idx]).groups()[0] + return "" + + +def run_ruff(code, check=False): + if check: + command = ["ruff", "check", "-", "--fix", "--exit-zero"] + else: + command = ["ruff", "format", "-", "--config", "pyproject.toml", "--silent"] + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + stdout, _ = process.communicate(input=code.encode()) + return stdout.decode() + + +def stylify(code: str) -> str: + """ + Applies the ruff part of our `make style` command to some code. This formats the code using `ruff format`. + As `ruff` does not provide a python api this cannot be done on the fly. + + Args: + code (`str`): The code to format. + + Returns: + `str`: The formatted code. + """ + has_indent = len(get_indent(code)) > 0 + if has_indent: + code = f"class Bla:\n{code}" + formatted_code = run_ruff(code) + return formatted_code[len("class Bla:\n") :] if has_indent else formatted_code + + +def check_codes_match(observed_code: str, theoretical_code: str) -> Optional[int]: + """ + Checks if two version of a code match with the exception of the class/function name. + + Args: + observed_code (`str`): The code found. + theoretical_code (`str`): The code to match. + + Returns: + `Optional[int]`: The index of the first line where there is a difference (if any) and `None` if the codes + match. + """ + observed_code_header = observed_code.split("\n")[0] + theoretical_code_header = theoretical_code.split("\n")[0] + + # Catch the function/class name: it is expected that those do not match. + _re_class_match = re.compile(r"class\s+([^\(:]+)(?:\(|:)") + _re_func_match = re.compile(r"def\s+([^\(]+)\(") + for re_pattern in [_re_class_match, _re_func_match]: + if re_pattern.match(observed_code_header) is not None: + try: + observed_obj_name = re_pattern.search(observed_code_header).groups()[0] + except Exception: + raise ValueError( + "Tried to split a class or function. It did not work. Error comes from: \n```\n" + + observed_code_header + + "\n```\n" + ) + + try: + theoretical_name = re_pattern.search(theoretical_code_header).groups()[0] + except Exception: + raise ValueError( + "Tried to split a class or function. It did not work. Error comes from: \n```\n" + + theoretical_code_header + + "\n```\n" + ) + theoretical_code_header = theoretical_code_header.replace(theoretical_name, observed_obj_name) + + # Find the first diff. Line 0 is special since we need to compare with the function/class names ignored. + diff_index = 0 + if theoretical_code_header != observed_code_header: + return 0 + + diff_index = 1 + for observed_line, theoretical_line in zip(observed_code.split("\n")[1:], theoretical_code.split("\n")[1:]): + if observed_line != theoretical_line: + return diff_index + diff_index += 1 + + +def is_copy_consistent( + filename: str, overwrite: bool = False, buffer: Optional[dict] = None +) -> Optional[list[tuple[str, int]]]: + """ + Check if the code commented as a copy in a file matches the original. + + Args: + filename (`str`): + The name of the file to check. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the copies when they don't match. + buffer (`dict`, *optional*): + The buffer used to store the previous results in order to speed up the process. + + Returns: + `Optional[List[Tuple[str, int]]]`: If `overwrite=False`, returns the list of differences as tuples `(str, int)` + with the name of the object having a diff and the line number where there is the first diff. + """ + base_path = TRANSFORMERS_PATH if not filename.startswith("tests") else MODEL_TEST_PATH + + with open(filename, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + diffs = [] + line_index = 0 + # Not a for loop cause `lines` is going to change (if `overwrite=True`). + search_re = _re_copy_warning_for_test_file if filename.startswith("tests") else _re_copy_warning + while line_index < len(lines): + search = search_re.search(lines[line_index]) + if search is None: + line_index += 1 + continue + + # There is some copied code here, let's retrieve the original. + indent, object_name, replace_pattern = search.groups() + + # Find the file lines, the object's code, and its blocks + try: + target_lines, theoretical_code, theoretical_code_splits = find_code_and_splits( + object_name, base_path, buffer=buffer + ) + except Exception as exc: + exc.args = (f"Error while trying to find source code for {filename}.\n\n" + str(exc),) + raise + + # code replaced by the patterns + theoretical_code_blocks = OrderedDict() + for name, start, end in theoretical_code_splits: + name = replace_code(name, replace_pattern) + code = "".join(target_lines[start:end]) + code = replace_code(code, replace_pattern) + theoretical_code_blocks[name] = code + + theoretical_indent = get_indent(theoretical_code) + + # `start_index` is the index of the first line (the definition header) after `# Copied from`. + # (`indent != theoretical_indent` doesn't seem to occur so far, not sure what this case is for.) + start_index = line_index + 1 if indent == theoretical_indent else line_index + # enter the block body + line_index = start_index + 1 + + subcode = "\n".join(theoretical_code.split("\n")[1:]) + indent = get_indent(subcode) + # Loop to check the observed code, stop when indentation diminishes or if we see a End copy comment. + # We can't call `find_block_end` directly as there is sth. special `# End copy"` here. + should_continue = True + while line_index < len(lines) and should_continue: + line_index += 1 + if line_index >= len(lines): + break + line = lines[line_index] + # There is a special pattern `# End copy` to stop early. It's not documented cause it shouldn't really be + # used. + should_continue = _should_continue(line, indent) and re.search(f"^{indent}# End copy", line) is None + # `line_index` is outside the block + # Clean up empty lines at the end (if any). + while len(lines[line_index - 1]) <= 1: + line_index -= 1 + + # Split the observed code into blocks + observed_code_splits = split_code_into_blocks(lines, start_index, line_index, len(indent), backtrace=True) + + is_class = lines[start_index].startswith(f"{' ' * (len(indent) - 4)}class ") + # sanity check + _sanity_check_splits(theoretical_code_splits, observed_code_splits, is_class=is_class, filename=filename) + + # observed code in a structured way (a dict mapping block names to blocks' code) + observed_code_blocks = OrderedDict() + for name, start, end in observed_code_splits: + code = "".join(lines[start:end]) + observed_code_blocks[name] = code + + # Below, we change some names in `theoretical_code_blocks` and `observed_code_blocks`. These mappings map the + # original names to the modified names: this is used to restore the original order of the code blocks. + name_mappings_1 = {k: k for k in theoretical_code_blocks} + name_mappings_2 = {k: k for k in observed_code_blocks} + + # Update code blocks' name and content: + # If `"# Ignore copy"` is found in a block of the observed code: + # 1. if it's a block only in the observed code --> add it to the theoretical code. + # 2. if it's also in the theoretical code () --> put its content (body) to the corresponding block under the + # same name in the theoretical code. + # In both cases, we change the name to have a prefix `_ignored_` so we know if we can discard them during the + # comparison. + ignored_existing_block_index = 0 + ignored_new_block_index = 0 + for name in list(observed_code_blocks.keys()): + code = observed_code_blocks[name] + if "# Ignore copy" in code: + if name in theoretical_code_blocks: + # in the target --> just copy the content + del theoretical_code_blocks[name] + theoretical_code_blocks[f"_ignored_existing_block_{ignored_existing_block_index}"] = code + name_mappings_1[name] = f"_ignored_existing_block_{ignored_existing_block_index}" + + del observed_code_blocks[name] + observed_code_blocks[f"_ignored_existing_block_{ignored_existing_block_index}"] = code + name_mappings_2[name] = f"_ignored_existing_block_{ignored_existing_block_index}" + ignored_existing_block_index += 1 + else: + # not in the target --> add it + theoretical_code_blocks[f"_ignored_new_block_{ignored_new_block_index}"] = code + name_mappings_1[f"_ignored_new_block_{ignored_new_block_index}"] = ( + f"_ignored_new_block_{ignored_new_block_index}" + ) + + del observed_code_blocks[name] + observed_code_blocks[f"_ignored_new_block_{ignored_new_block_index}"] = code + name_mappings_2[name] = f"_ignored_new_block_{ignored_new_block_index}" + ignored_new_block_index += 1 + + # Respect the original block order: + # 1. in `theoretical_code_blocks`: the new blocks will follow the existing ones + # 2. in `observed_code_blocks`: the original order are kept with names modified potentially. This is necessary + # to compute the correct `diff_index` if `overwrite=True` and there is a diff. + theoretical_code_blocks = { + name_mappings_1[orig_name]: theoretical_code_blocks[name_mappings_1[orig_name]] + for orig_name in name_mappings_1 + } + observed_code_blocks = { + name_mappings_2[orig_name]: observed_code_blocks[name_mappings_2[orig_name]] + for orig_name in name_mappings_2 + } + + # Ignore the blocks specified to be ignored. This is the version used to check if there is a mismatch + theoretical_code_blocks_clean = { + k: v + for k, v in theoretical_code_blocks.items() + if not (k.startswith(("_ignored_existing_block_", "_ignored_new_block_"))) + } + theoretical_code = "".join(list(theoretical_code_blocks_clean.values())) + + # stylify `theoretical_code` before compare (this is needed only when `replace_pattern` is not empty) + if replace_pattern: + theoretical_code = stylify(theoretical_code) + # Remove `\n\n` in `theoretical_code` before compare (so no empty line) + while "\n\n" in theoretical_code: + theoretical_code = theoretical_code.replace("\n\n", "\n") + + # Compute `observed_code` where we don't include any empty line + keep track the line index between the + # original/processed `observed_code` so we can have the correct `diff_index`. + idx_to_orig_idx_mapping_for_observed_code_lines = {} + idx = -1 + orig_idx = -1 + observed_code = "" + for name, code in observed_code_blocks.items(): + if code.endswith("\n"): + code = code[:-1] + for code_line in code.split("\n"): + orig_idx += 1 + if code_line.strip() and not name.startswith(("_ignored_existing_block_", "_ignored_new_block_")): + idx += 1 + observed_code += code_line + "\n" + idx_to_orig_idx_mapping_for_observed_code_lines[idx] = orig_idx + + # Test for a diff and act accordingly. + diff_index = check_codes_match(observed_code, theoretical_code) + if diff_index is not None: + # switch to the index in the original `observed_code` (i.e. before removing empty lines) + diff_index = idx_to_orig_idx_mapping_for_observed_code_lines[diff_index] + diffs.append([object_name, diff_index + start_index + 1]) + if overwrite: + # `theoretical_code_to_write` is a single string but may have several lines. + theoretical_code_to_write = stylify("".join(list(theoretical_code_blocks.values()))) + lines = lines[:start_index] + [theoretical_code_to_write] + lines[line_index:] + # Here we treat it as a single entry in `lines`. + line_index = start_index + 1 + + if overwrite and len(diffs) > 0: + # Warn the user a file has been modified. + print(f"Detected changes, rewriting {filename}.") + with open(filename, "w", encoding="utf-8", newline="\n") as f: + f.writelines(lines) + return diffs + + +def check_copies(overwrite: bool = False, file: Optional[str] = None): + """ + Check every file is copy-consistent with the original. Also check the model list in the main README and other + READMEs are consistent. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the copies when they don't match. + file (`bool`, *optional*): + The path to a specific file to check and/or fix. + """ + buffer = {} + + if file is None: + all_files = glob.glob(os.path.join(TRANSFORMERS_PATH, "**/*.py"), recursive=True) + all_test_files = glob.glob(os.path.join(MODEL_TEST_PATH, "**/*.py"), recursive=True) + all_files = list(all_files) + list(all_test_files) + else: + all_files = [file] + + diffs = [] + for filename in all_files: + new_diffs = is_copy_consistent(filename, overwrite, buffer) + diffs += [f"- {filename}: copy does not match {d[0]} at line {d[1]}" for d in new_diffs] + if not overwrite and len(diffs) > 0: + diff = "\n".join(diffs) + raise Exception( + "Found the following copy inconsistencies:\n" + + diff + + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." + ) + + +def check_full_copies(overwrite: bool = False): + """ + Check the files that are full copies of others (as indicated in `FULL_COPIES`) are copy-consistent. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to overwrite the copies when they don't match. + """ + diffs = [] + for target, source in FULL_COPIES.items(): + with open(source, "r", encoding="utf-8") as f: + source_code = f.read() + with open(target, "r", encoding="utf-8") as f: + target_code = f.read() + if source_code != target_code: + if overwrite: + with open(target, "w", encoding="utf-8") as f: + print(f"Replacing the content of {target} by the one of {source}.") + f.write(source_code) + else: + diffs.append(f"- {target}: copy does not match {source}.") + + if not overwrite and len(diffs) > 0: + diff = "\n".join(diffs) + raise Exception( + "Found the following copy inconsistencies:\n" + + diff + + "\nRun `make fix-copies` or `python utils/check_copies.py --fix_and_overwrite` to fix them." + ) + + +def get_model_list(filename: str, start_prompt: str, end_prompt: str) -> str: + """ + Extracts the model list from a README. + + Args: + filename (`str`): The name of the README file to check. + start_prompt (`str`): The string to look for that introduces the model list. + end_prompt (`str`): The string to look for that ends the model list. + + Returns: + `str`: The model list. + """ + with open(os.path.join(REPO_PATH, filename), "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + # Find the start of the list. + start_index = 0 + while not lines[start_index].startswith(start_prompt): + start_index += 1 + start_index += 1 + + result = [] + current_line = "" + end_index = start_index + + # Keep going until the end of the list. + while not lines[end_index].startswith(end_prompt): + if lines[end_index].startswith("1."): + if len(current_line) > 1: + result.append(current_line) + current_line = lines[end_index] + elif len(lines[end_index]) > 1: + current_line = f"{current_line[:-1]} {lines[end_index].lstrip()}" + end_index += 1 + if len(current_line) > 1: + result.append(current_line) + + return "".join(result) + + +def convert_to_localized_md(model_list: str, localized_model_list: str, format_str: str) -> tuple[bool, str]: + """ + Compare the model list from the main README to the one in a localized README. + + Args: + model_list (`str`): The model list in the main README. + localized_model_list (`str`): The model list in one of the localized README. + format_str (`str`): + The template for a model entry in the localized README (look at the `format_model_list` in the entries of + `LOCALIZED_READMES` for examples). + + Returns: + `Tuple[bool, str]`: A tuple where the first value indicates if the READMEs match or not, and the second value + is the correct localized README. + """ + + def _rep(match): + title, model_link, paper_affiliations, paper_title_link, paper_authors, supplements = match.groups() + return format_str.format( + title=title, + model_link=model_link, + paper_affiliations=paper_affiliations, + paper_title_link=paper_title_link, + paper_authors=paper_authors, + supplements=" " + supplements.strip() if len(supplements) != 0 else "", + ) + + # This regex captures metadata from an English model description, including model title, model link, + # affiliations of the paper, title of the paper, authors of the paper, and supplemental data (see DistilBERT for + # example). + _re_capture_meta = re.compile( + r"\*\*\[([^\]]*)\]\(([^\)]*)\)\*\* \(from ([^)]*)\)[^\[]*([^\)]*\)).*?by (.*?[A-Za-z\*]{2,}?)\. (.*)$" + ) + # This regex is used to synchronize title link. + _re_capture_title_link = re.compile(r"\*\*\[([^\]]*)\]\(([^\)]*)\)\*\*") + # This regex is used to synchronize paper title and link. + _re_capture_paper_link = re.compile(r" \[([^\]]*)\]\(([^\)]*)\)") + + if len(localized_model_list) == 0: + localized_model_index = {} + else: + try: + localized_model_index = { + re.search(r"\*\*\[([^\]]*)", line).groups()[0]: line + for line in localized_model_list.strip().split("\n") + } + except AttributeError: + raise AttributeError("A model name in localized READMEs cannot be recognized.") + + model_keys = [re.search(r"\*\*\[([^\]]*)", line).groups()[0] for line in model_list.strip().split("\n")] + + # We exclude keys in localized README not in the main one. + readmes_match = not any(k not in model_keys for k in localized_model_index) + localized_model_index = {k: v for k, v in localized_model_index.items() if k in model_keys} + + for model in model_list.strip().split("\n"): + title, model_link = _re_capture_title_link.search(model).groups() + if title not in localized_model_index: + readmes_match = False + # Add an anchor white space behind a model description string for regex. + # If metadata cannot be captured, the English version will be directly copied. + localized_model_index[title] = _re_capture_meta.sub(_rep, model + " ") + elif _re_fill_pattern.search(localized_model_index[title]) is not None: + update = _re_capture_meta.sub(_rep, model + " ") + if update != localized_model_index[title]: + readmes_match = False + localized_model_index[title] = update + else: + # Synchronize title link + converted_model = _re_capture_title_link.sub( + f"**[{title}]({model_link})**", localized_model_index[title], count=1 + ) + + # Synchronize paper title and its link (if found) + paper_title_link = _re_capture_paper_link.search(model) + if paper_title_link is not None: + paper_title, paper_link = paper_title_link.groups() + converted_model = _re_capture_paper_link.sub( + f" [{paper_title}]({paper_link})", converted_model, count=1 + ) + + if converted_model != localized_model_index[title]: + readmes_match = False + localized_model_index[title] = converted_model + + sorted_index = sorted(localized_model_index.items(), key=lambda x: x[0].lower()) + + return readmes_match, "\n".join(x[1] for x in sorted_index) + "\n" + + +# Map a model name with the name it has in the README for the check_readme check +SPECIAL_MODEL_NAMES = { + "Bert Generation": "BERT For Sequence Generation", + "BigBird": "BigBird-RoBERTa", + "Data2VecAudio": "Data2Vec", + "Data2VecText": "Data2Vec", + "Data2VecVision": "Data2Vec", + "DonutSwin": "Swin Transformer", + "Marian": "MarianMT", + "MaskFormerSwin": "Swin Transformer", + "OpenAI GPT-2": "GPT-2", + "OpenAI GPT": "GPT", + "Perceiver": "Perceiver IO", + "SAM": "Segment Anything", + "SAM_HQ": "Segment Anything High Quality", + "ViT": "Vision Transformer (ViT)", +} + +# Update this list with the models that shouldn't be in the README. This only concerns modular models or those who do +# not have an associated paper. +MODELS_NOT_IN_README = [ + "BertJapanese", + "Encoder decoder", + "FairSeq Machine-Translation", + "HerBERT", + "RetriBERT", + "Speech Encoder decoder", + "Speech2Text", + "Speech2Text2", + "TimmBackbone", + "Vision Encoder decoder", + "VisionTextDualEncoder", + "CLIPVisionModel", + "SiglipVisionModel", + "ChineseCLIPVisionModel", + "VitPoseBackbone", +] + +# Template for new entries to add in the main README when we have missing models. +README_TEMPLATE = ( + "1. **[{model_name}](https://huggingface.co/docs/main/transformers/model_doc/{model_type})** (from " + ") released with the paper []() by ." +) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--file", type=str, default=None, help="A specific file to check and/or fix") + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + check_copies(args.fix_and_overwrite, args.file) + check_full_copies(args.fix_and_overwrite) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_doc_toc.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_doc_toc.py new file mode 100644 index 0000000000000000000000000000000000000000..9de67488eec1073a32263cf33c5905d3827d7ead --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_doc_toc.py @@ -0,0 +1,133 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# 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 script is responsible for cleaning the model section of the table of content by removing duplicates and sorting +the entries in alphabetical order. + +Usage (from the root of the repo): + +Check that the table of content is properly sorted (used in `make quality`): + +```bash +python utils/check_doc_toc.py +``` + +Auto-sort the table of content if it is not properly sorted (used in `make style`): + +```bash +python utils/check_doc_toc.py --fix_and_overwrite +``` +""" + +import argparse +from collections import defaultdict + +import yaml + + +PATH_TO_TOC = "docs/source/en/_toctree.yml" + + +def clean_model_doc_toc(model_doc: list[dict]) -> list[dict]: + """ + Cleans a section of the table of content of the model documentation (one specific modality) by removing duplicates + and sorting models alphabetically. + + Args: + model_doc (`List[dict]`): + The list of dictionaries extracted from the `_toctree.yml` file for this specific modality. + + Returns: + `List[dict]`: List of dictionaries like the input, but cleaned up and sorted. + """ + counts = defaultdict(int) + for doc in model_doc: + counts[doc["local"]] += 1 + duplicates = [key for key, value in counts.items() if value > 1] + + new_doc = [] + for duplicate_key in duplicates: + titles = list({doc["title"] for doc in model_doc if doc["local"] == duplicate_key}) + if len(titles) > 1: + raise ValueError( + f"{duplicate_key} is present several times in the documentation table of content at " + "`docs/source/en/_toctree.yml` with different *Title* values. Choose one of those and remove the " + "others." + ) + # Only add this once + new_doc.append({"local": duplicate_key, "title": titles[0]}) + + # Add none duplicate-keys + new_doc.extend([doc for doc in model_doc if counts[doc["local"]] == 1]) + + # Sort + return sorted(new_doc, key=lambda s: s["title"].lower()) + + +def check_model_doc(overwrite: bool = False): + """ + Check that the content of the table of content in `_toctree.yml` is clean (no duplicates and sorted for the model + API doc) and potentially auto-cleans it. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether to just check if the TOC is clean or to auto-clean it (when `overwrite=True`). + """ + with open(PATH_TO_TOC, encoding="utf-8") as f: + content = yaml.safe_load(f.read()) + + # Get to the API doc + api_idx = 0 + while content[api_idx]["title"] != "API": + api_idx += 1 + api_doc = content[api_idx]["sections"] + + # Then to the model doc + model_idx = 0 + while api_doc[model_idx]["title"] != "Models": + model_idx += 1 + + model_doc = api_doc[model_idx]["sections"] + + # Extract the modalities and clean them one by one. + modalities_docs = [(idx, section) for idx, section in enumerate(model_doc) if "sections" in section] + diff = False + for idx, modality_doc in modalities_docs: + old_modality_doc = modality_doc["sections"] + new_modality_doc = clean_model_doc_toc(old_modality_doc) + + if old_modality_doc != new_modality_doc: + diff = True + if overwrite: + model_doc[idx]["sections"] = new_modality_doc + + if diff: + if overwrite: + api_doc[model_idx]["sections"] = model_doc + content[api_idx]["sections"] = api_doc + with open(PATH_TO_TOC, "w", encoding="utf-8") as f: + f.write(yaml.dump(content, allow_unicode=True)) + else: + raise ValueError( + "The model doc part of the table of content is not properly sorted, run `make style` to fix this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + check_model_doc(args.fix_and_overwrite) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_docstrings.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..3904b850b6008d6187bb7fd18a1311762373a8d1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_docstrings.py @@ -0,0 +1,1614 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +""" +Utility that checks all docstrings of public objects have an argument section matching their signature. + +Use from the root of the repo with: + +```bash +python utils/check_docstrings.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`). + +To auto-fix issues run: + +```bash +python utils/check_docstrings.py --fix_and_overwrite +``` + +which is used by `make fix-copies` (note that this fills what it cans, you might have to manually fill information +like argument descriptions). +""" + +import argparse +import ast +import enum +import glob +import inspect +import operator as op +import os +import re +from collections import OrderedDict +from pathlib import Path +from typing import Any, Optional, Union + +from check_repo import ignore_undocumented +from git import Repo + +from transformers.utils import direct_transformers_import +from transformers.utils.auto_docstring import ( + ImageProcessorArgs, + ModelArgs, + ModelOutputArgs, + get_args_doc_from_source, + parse_docstring, + set_min_indent, +) + + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() +PATH_TO_TRANSFORMERS = Path("src").resolve() / "transformers" + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + +OPTIONAL_KEYWORD = "*optional*" +# Re pattern that catches args blocks in docstrings (with all variation around the name supported). +_re_args = re.compile(r"^\s*(Args?|Arguments?|Attributes?|Params?|Parameters?):\s*$") +# Re pattern that parses the start of an arg block: catches () in those lines. +_re_parse_arg = re.compile(r"^(\s*)(\S+)\s+\((.+)\)(?:\:|$)") +# Re pattern that parses the end of a description of an arg (catches the default in *optional*, defaults to xxx). +_re_parse_description = re.compile(r"\*optional\*, defaults to (.*)$") +# Args that are always overridden in the docstring, for clarity we don't want to remove them from the docstring +ALWAYS_OVERRIDE = ["labels"] + +# This is a temporary list of objects to ignore while we progressively fix them. Do not add anything here, fix the +# docstrings instead. If formatting should be ignored for the docstring, you can put a comment # no-format on the +# line before the docstring. +OBJECTS_TO_IGNORE = [ + "Mxfp4Config", + "Exaone4Config", + "SmolLM3Config", + "Gemma3nVisionConfig", + "Llama4Processor", + # Deprecated + "InputExample", + "InputFeatures", + # Signature is *args/**kwargs + "TFSequenceSummary", + "TFBertTokenizer", + "TFGPT2Tokenizer", + # Missing arguments in the docstring + "ASTFeatureExtractor", + "AlbertModel", + "AlbertTokenizerFast", + "AlignTextModel", + "AlignVisionConfig", + "AudioClassificationPipeline", + "AutoformerConfig", + "AutomaticSpeechRecognitionPipeline", + "BarkCoarseConfig", + "BarkConfig", + "BarkFineConfig", + "BarkSemanticConfig", + "BartConfig", + "BartTokenizerFast", + "BarthezTokenizerFast", + "BeitModel", + "BertConfig", + "BertJapaneseTokenizer", + "BertModel", + "BertTokenizerFast", + "BigBirdConfig", + "BigBirdForQuestionAnswering", + "BigBirdModel", + "BigBirdPegasusConfig", + "BigBirdTokenizerFast", + "BitImageProcessor", + "BlenderbotConfig", + "BlenderbotSmallConfig", + "BlenderbotSmallTokenizerFast", + "BlenderbotTokenizerFast", + "Blip2VisionConfig", + "BlipTextConfig", + "BlipVisionConfig", + "BloomConfig", + "BloomTokenizerFast", + "BridgeTowerTextConfig", + "BridgeTowerVisionConfig", + "BrosModel", + "CamembertConfig", + "CamembertModel", + "CamembertTokenizerFast", + "CanineModel", + "CanineTokenizer", + "ChineseCLIPTextModel", + "ClapTextConfig", + "ConditionalDetrConfig", + "ConditionalDetrImageProcessor", + "ConvBertConfig", + "ConvBertTokenizerFast", + "ConvNextConfig", + "ConvNextV2Config", + "CpmAntTokenizer", + "CvtConfig", + "CvtModel", + "DeiTImageProcessor", + "DPRReaderTokenizer", + "DPRReaderTokenizerFast", + "DPTModel", + "Data2VecAudioConfig", + "Data2VecTextConfig", + "Data2VecTextModel", + "Data2VecVisionModel", + "DataCollatorForLanguageModeling", + "DebertaConfig", + "DebertaV2Config", + "DebertaV2Tokenizer", + "DebertaV2TokenizerFast", + "DecisionTransformerConfig", + "DeformableDetrConfig", + "DeformableDetrImageProcessor", + "DeiTModel", + "DepthEstimationPipeline", + "DetaConfig", + "DetaImageProcessor", + "DetrConfig", + "DetrImageProcessor", + "DinatModel", + "DINOv3ConvNextConfig", + "DINOv3ViTConfig", + "DistilBertConfig", + "DistilBertTokenizerFast", + "DocumentQuestionAnsweringPipeline", + "DonutSwinModel", + "EarlyStoppingCallback", + "EfficientFormerConfig", + "EfficientFormerImageProcessor", + "EfficientNetConfig", + "ElectraConfig", + "ElectraTokenizerFast", + "EncoderDecoderModel", + "ErnieMModel", + "ErnieModel", + "ErnieMTokenizer", + "EsmConfig", + "EsmModel", + "FlaxAlbertForMaskedLM", + "FlaxAlbertForMultipleChoice", + "FlaxAlbertForPreTraining", + "FlaxAlbertForQuestionAnswering", + "FlaxAlbertForSequenceClassification", + "FlaxAlbertForTokenClassification", + "FlaxAlbertModel", + "FlaxBartForCausalLM", + "FlaxBartForConditionalGeneration", + "FlaxBartForQuestionAnswering", + "FlaxBartForSequenceClassification", + "FlaxBartModel", + "FlaxBeitForImageClassification", + "FlaxBeitForMaskedImageModeling", + "FlaxBeitModel", + "FlaxBertForCausalLM", + "FlaxBertForMaskedLM", + "FlaxBertForMultipleChoice", + "FlaxBertForNextSentencePrediction", + "FlaxBertForPreTraining", + "FlaxBertForQuestionAnswering", + "FlaxBertForSequenceClassification", + "FlaxBertForTokenClassification", + "FlaxBertModel", + "FlaxBigBirdForCausalLM", + "FlaxBigBirdForMaskedLM", + "FlaxBigBirdForMultipleChoice", + "FlaxBigBirdForPreTraining", + "FlaxBigBirdForQuestionAnswering", + "FlaxBigBirdForSequenceClassification", + "FlaxBigBirdForTokenClassification", + "FlaxBigBirdModel", + "FlaxBlenderbotForConditionalGeneration", + "FlaxBlenderbotModel", + "FlaxBlenderbotSmallForConditionalGeneration", + "FlaxBlenderbotSmallModel", + "FlaxBloomForCausalLM", + "FlaxBloomModel", + "FlaxCLIPModel", + "FlaxDinov2ForImageClassification", + "FlaxDinov2Model", + "FlaxDistilBertForMaskedLM", + "FlaxDistilBertForMultipleChoice", + "FlaxDistilBertForQuestionAnswering", + "FlaxDistilBertForSequenceClassification", + "FlaxDistilBertForTokenClassification", + "FlaxDistilBertModel", + "FlaxElectraForCausalLM", + "FlaxElectraForMaskedLM", + "FlaxElectraForMultipleChoice", + "FlaxElectraForPreTraining", + "FlaxElectraForQuestionAnswering", + "FlaxElectraForSequenceClassification", + "FlaxElectraForTokenClassification", + "FlaxElectraModel", + "FlaxEncoderDecoderModel", + "FlaxGPT2LMHeadModel", + "FlaxGPT2Model", + "FlaxGPTJForCausalLM", + "FlaxGPTJModel", + "FlaxGPTNeoForCausalLM", + "FlaxGPTNeoModel", + "FlaxLlamaForCausalLM", + "FlaxLlamaModel", + "FlaxGemmaForCausalLM", + "FlaxGemmaModel", + "FlaxMBartForConditionalGeneration", + "FlaxMBartForQuestionAnswering", + "FlaxMBartForSequenceClassification", + "FlaxMBartModel", + "FlaxMarianMTModel", + "FlaxMarianModel", + "FlaxMistralForCausalLM", + "FlaxMistralModel", + "FlaxOPTForCausalLM", + "FlaxPegasusForConditionalGeneration", + "FlaxPegasusModel", + "FlaxRegNetForImageClassification", + "FlaxRegNetModel", + "FlaxResNetForImageClassification", + "FlaxResNetModel", + "FlaxRoFormerForMaskedLM", + "FlaxRoFormerForMultipleChoice", + "FlaxRoFormerForQuestionAnswering", + "FlaxRoFormerForSequenceClassification", + "FlaxRoFormerForTokenClassification", + "FlaxRoFormerModel", + "FlaxRobertaForCausalLM", + "FlaxRobertaForMaskedLM", + "FlaxRobertaForMultipleChoice", + "FlaxRobertaForQuestionAnswering", + "FlaxRobertaForSequenceClassification", + "FlaxRobertaForTokenClassification", + "FlaxRobertaModel", + "FlaxRobertaPreLayerNormForCausalLM", + "FlaxRobertaPreLayerNormForMaskedLM", + "FlaxRobertaPreLayerNormForMultipleChoice", + "FlaxRobertaPreLayerNormForQuestionAnswering", + "FlaxRobertaPreLayerNormForSequenceClassification", + "FlaxRobertaPreLayerNormForTokenClassification", + "FlaxRobertaPreLayerNormModel", + "FlaxSpeechEncoderDecoderModel", + "FlaxViTForImageClassification", + "FlaxViTModel", + "FlaxVisionEncoderDecoderModel", + "FlaxVisionTextDualEncoderModel", + "FlaxWav2Vec2ForCTC", + "FlaxWav2Vec2ForPreTraining", + "FlaxWav2Vec2Model", + "FlaxWhisperForAudioClassification", + "FlaxWhisperForConditionalGeneration", + "FlaxWhisperModel", + "FlaxWhisperTimeStampLogitsProcessor", + "FlaxXGLMForCausalLM", + "FlaxXGLMModel", + "FlaxXLMRobertaForCausalLM", + "FlaxXLMRobertaForMaskedLM", + "FlaxXLMRobertaForMultipleChoice", + "FlaxXLMRobertaForQuestionAnswering", + "FlaxXLMRobertaForSequenceClassification", + "FlaxXLMRobertaForTokenClassification", + "FlaxXLMRobertaModel", + "FNetConfig", + "FNetModel", + "FNetTokenizerFast", + "FSMTConfig", + "FeatureExtractionPipeline", + "FillMaskPipeline", + "FlaubertConfig", + "FlavaConfig", + "FlavaForPreTraining", + "FlavaImageModel", + "FlavaImageProcessor", + "FlavaMultimodalModel", + "FlavaTextConfig", + "FlavaTextModel", + "FocalNetModel", + "FunnelTokenizerFast", + "GPTBigCodeConfig", + "GPTJConfig", + "GPTNeoXConfig", + "GPTNeoXJapaneseConfig", + "GPTNeoXTokenizerFast", + "GPTSanJapaneseConfig", + "GitConfig", + "GitVisionConfig", + "GraphormerConfig", + "GroupViTTextConfig", + "GroupViTVisionConfig", + "HerbertTokenizerFast", + "HubertConfig", + "HubertForCTC", + "IBertConfig", + "IBertModel", + "IdeficsConfig", + "IdeficsProcessor", + "IJepaModel", + "ImageClassificationPipeline", + "ImageFeatureExtractionPipeline", + "ImageGPTConfig", + "ImageSegmentationPipeline", + "ImageTextToTextPipeline", + "ImageToImagePipeline", + "ImageToTextPipeline", + "InformerConfig", + "JukeboxPriorConfig", + "JukeboxTokenizer", + "LEDConfig", + "LEDTokenizerFast", + "LayoutLMForQuestionAnswering", + "LayoutLMTokenizerFast", + "LayoutLMv2Config", + "LayoutLMv2ForQuestionAnswering", + "LayoutLMv2TokenizerFast", + "LayoutLMv3Config", + "LayoutLMv3ImageProcessor", + "LayoutLMv3TokenizerFast", + "LayoutXLMTokenizerFast", + "LevitConfig", + "LiltConfig", + "LiltModel", + "LongT5Config", + "LongformerConfig", + "LongformerModel", + "LongformerTokenizerFast", + "LukeModel", + "LukeTokenizer", + "LxmertTokenizerFast", + "M2M100Config", + "M2M100Tokenizer", + "MarkupLMProcessor", + "MaskGenerationPipeline", + "MBart50TokenizerFast", + "MBartConfig", + "MCTCTFeatureExtractor", + "MPNetConfig", + "MPNetModel", + "MPNetTokenizerFast", + "MT5Config", + "MT5TokenizerFast", + "MarianConfig", + "MarianTokenizer", + "MarkupLMConfig", + "MarkupLMModel", + "MarkupLMTokenizer", + "MarkupLMTokenizerFast", + "Mask2FormerConfig", + "MaskFormerConfig", + "MaxTimeCriteria", + "MegaConfig", + "MegaModel", + "MegatronBertConfig", + "MegatronBertForPreTraining", + "MegatronBertModel", + "MLCDVisionConfig", + "MobileBertConfig", + "MobileBertModel", + "MobileBertTokenizerFast", + "MobileNetV1ImageProcessor", + "MobileNetV1Model", + "MobileNetV2ImageProcessor", + "MobileNetV2Model", + "MobileViTModel", + "MobileViTV2Model", + "MLukeTokenizer", + "MraConfig", + "MusicgenDecoderConfig", + "MusicgenForConditionalGeneration", + "MusicgenMelodyForConditionalGeneration", + "MvpConfig", + "MvpTokenizerFast", + "MT5Tokenizer", + "NatModel", + "NerPipeline", + "NezhaConfig", + "NezhaModel", + "NllbMoeConfig", + "NllbTokenizer", + "NllbTokenizerFast", + "NystromformerConfig", + "OPTConfig", + "ObjectDetectionPipeline", + "OneFormerProcessor", + "OpenAIGPTTokenizerFast", + "OpenLlamaConfig", + "PLBartConfig", + "PegasusConfig", + "PegasusTokenizer", + "PegasusTokenizerFast", + "PegasusXConfig", + "PerceiverImageProcessor", + "PerceiverModel", + "PerceiverTokenizer", + "PersimmonConfig", + "Pipeline", + "Pix2StructConfig", + "Pix2StructTextConfig", + "PLBartTokenizer", + "Pop2PianoConfig", + "PreTrainedTokenizer", + "PreTrainedTokenizerBase", + "PreTrainedTokenizerFast", + "PrefixConstrainedLogitsProcessor", + "ProphetNetConfig", + "QDQBertConfig", + "QDQBertModel", + "QuestionAnsweringPipeline", + "RagConfig", + "RagModel", + "RagRetriever", + "RagSequenceForGeneration", + "RagTokenForGeneration", + "RealmConfig", + "RealmForOpenQA", + "RealmScorer", + "RealmTokenizerFast", + "ReformerConfig", + "ReformerTokenizerFast", + "RegNetConfig", + "RemBertConfig", + "RemBertModel", + "RemBertTokenizer", + "RemBertTokenizerFast", + "RetriBertConfig", + "RetriBertTokenizerFast", + "RoCBertConfig", + "RoCBertModel", + "RoCBertTokenizer", + "RoFormerConfig", + "RobertaConfig", + "RobertaModel", + "RobertaPreLayerNormConfig", + "RobertaPreLayerNormModel", + "RobertaTokenizerFast", + "SEWConfig", + "SEWDConfig", + "SEWDForCTC", + "SEWForCTC", + "SamConfig", + "SamPromptEncoderConfig", + "SamHQConfig", + "SamHQPromptEncoderConfig", + "SeamlessM4TConfig", # use of unconventional markdown + "SeamlessM4Tv2Config", # use of unconventional markdown + "Seq2SeqTrainingArguments", + "SpecialTokensMixin", + "Speech2Text2Config", + "Speech2Text2Tokenizer", + "Speech2TextTokenizer", + "SpeechEncoderDecoderModel", + "SpeechT5Config", + "SpeechT5Model", + "SplinterConfig", + "SplinterTokenizerFast", + "SqueezeBertTokenizerFast", + "SummarizationPipeline", + "Swin2SRImageProcessor", + "Swinv2Model", + "SwitchTransformersConfig", + "T5Config", + "T5Tokenizer", + "T5TokenizerFast", + "TableQuestionAnsweringPipeline", + "TableTransformerConfig", + "TapasConfig", + "TapasModel", + "TapasTokenizer", + "Text2TextGenerationPipeline", + "TextClassificationPipeline", + "TextGenerationPipeline", + "TFBartForConditionalGeneration", + "TFBartForSequenceClassification", + "TFBartModel", + "TFBertModel", + "TFConvNextModel", + "TFData2VecVisionModel", + "TFDeiTModel", + "TFEncoderDecoderModel", + "TFEsmModel", + "TFMobileViTModel", + "TFRagModel", + "TFRagSequenceForGeneration", + "TFRagTokenForGeneration", + "TFRepetitionPenaltyLogitsProcessor", + "TFSwinModel", + "TFViTModel", + "TFVisionEncoderDecoderModel", + "TFVisionTextDualEncoderModel", + "TFXGLMForCausalLM", + "TFXGLMModel", + "TimeSeriesTransformerConfig", + "TokenClassificationPipeline", + "TrOCRConfig", + "Phi4MultimodalProcessor", + "TrainerState", + "TrainingArguments", + "TrajectoryTransformerConfig", + "TranslationPipeline", + "TvltImageProcessor", + "UMT5Config", + "UperNetConfig", + "UperNetForSemanticSegmentation", + "ViTHybridImageProcessor", + "ViTHybridModel", + "ViTMSNModel", + "ViTModel", + "VideoClassificationPipeline", + "ViltConfig", + "ViltForImagesAndTextClassification", + "ViltModel", + "VisionEncoderDecoderModel", + "VisionTextDualEncoderModel", + "VisualBertConfig", + "VisualBertModel", + "VisualQuestionAnsweringPipeline", + "VitMatteForImageMatting", + "VitsTokenizer", + "VivitModel", + "Wav2Vec2BertForCTC", + "Wav2Vec2CTCTokenizer", + "Wav2Vec2Config", + "Wav2Vec2ConformerConfig", + "Wav2Vec2ConformerForCTC", + "Wav2Vec2FeatureExtractor", + "Wav2Vec2PhonemeCTCTokenizer", + "WavLMConfig", + "WavLMForCTC", + "WhisperConfig", + "WhisperFeatureExtractor", + "WhisperForAudioClassification", + "XCLIPTextConfig", + "XCLIPVisionConfig", + "XGLMConfig", + "XGLMModel", + "XGLMTokenizerFast", + "XLMConfig", + "XLMProphetNetConfig", + "XLMRobertaConfig", + "XLMRobertaModel", + "XLMRobertaTokenizerFast", + "XLMRobertaXLConfig", + "XLMRobertaXLModel", + "XLNetConfig", + "XLNetTokenizerFast", + "XmodConfig", + "XmodModel", + "YolosImageProcessor", + "YolosModel", + "YosoConfig", + "ZeroShotAudioClassificationPipeline", + "ZeroShotClassificationPipeline", + "ZeroShotImageClassificationPipeline", + "ZeroShotObjectDetectionPipeline", + "Llama4TextConfig", +] + +# Supported math operations when interpreting the value of defaults. +MATH_OPERATORS = { + ast.Add: op.add, + ast.Sub: op.sub, + ast.Mult: op.mul, + ast.Div: op.truediv, + ast.Pow: op.pow, + ast.BitXor: op.xor, + ast.USub: op.neg, +} + + +def find_indent(line: str) -> int: + """ + Returns the number of spaces that start a line indent. + """ + search = re.search(r"^(\s*)(?:\S|$)", line) + if search is None: + return 0 + return len(search.groups()[0]) + + +def stringify_default(default: Any) -> str: + """ + Returns the string representation of a default value, as used in docstring: numbers are left as is, all other + objects are in backtiks. + + Args: + default (`Any`): The default value to process + + Returns: + `str`: The string representation of that default. + """ + if isinstance(default, bool): + # We need to test for bool first as a bool passes isinstance(xxx, (int, float)) + return f"`{default}`" + elif isinstance(default, enum.Enum): + # We need to test for enum first as an enum with int values will pass isinstance(xxx, (int, float)) + return f"`{str(default)}`" + elif isinstance(default, int): + return str(default) + elif isinstance(default, float): + result = str(default) + return str(round(default, 2)) if len(result) > 6 else result + elif isinstance(default, str): + return str(default) if default.isnumeric() else f'`"{default}"`' + elif isinstance(default, type): + return f"`{default.__name__}`" + else: + return f"`{default}`" + + +def eval_math_expression(expression: str) -> Optional[Union[float, int]]: + # Mainly taken from the excellent https://stackoverflow.com/a/9558001 + """ + Evaluate (safely) a mathematial expression and returns its value. + + Args: + expression (`str`): The expression to evaluate. + + Returns: + `Optional[Union[float, int]]`: Returns `None` if the evaluation fails in any way and the value computed + otherwise. + + Example: + + ```py + >>> eval_expr('2^6') + 4 + >>> eval_expr('2**6') + 64 + >>> eval_expr('1 + 2*3**(4^5) / (6 + -7)') + -5.0 + ``` + """ + try: + return eval_node(ast.parse(expression, mode="eval").body) + except TypeError: + return + + +def eval_node(node): + if isinstance(node, ast.Constant) and type(node.value) in (int, float, complex): + return node.value + elif isinstance(node, ast.BinOp): # + return MATH_OPERATORS[type(node.op)](eval_node(node.left), eval_node(node.right)) + elif isinstance(node, ast.UnaryOp): # e.g., -1 + return MATH_OPERATORS[type(node.op)](eval_node(node.operand)) + else: + raise TypeError(node) + + +def replace_default_in_arg_description(description: str, default: Any) -> str: + """ + Catches the default value in the description of an argument inside a docstring and replaces it by the value passed. + + Args: + description (`str`): The description of an argument in a docstring to process. + default (`Any`): The default value that would be in the docstring of that argument. + + Returns: + `str`: The description updated with the new default value. + """ + # Lots of docstrings have `optional` or **opational** instead of *optional* so we do this fix here. + description = description.replace("`optional`", OPTIONAL_KEYWORD) + description = description.replace("**optional**", OPTIONAL_KEYWORD) + if default is inspect._empty: + # No default, make sure the description doesn't have any either + idx = description.find(OPTIONAL_KEYWORD) + if idx != -1: + description = description[:idx].rstrip() + if description.endswith(","): + description = description[:-1].rstrip() + elif default is None: + # Default None are not written, we just set `*optional*`. If there is default that is not None specified in the + # description, we do not erase it (as sometimes we set the default to `None` because the default is a mutable + # object). + idx = description.find(OPTIONAL_KEYWORD) + if idx == -1: + description = f"{description}, {OPTIONAL_KEYWORD}" + elif re.search(r"defaults to `?None`?", description) is not None: + len_optional = len(OPTIONAL_KEYWORD) + description = description[: idx + len_optional] + else: + str_default = None + # For numbers we may have a default that is given by a math operation (1/255 is really popular). We don't + # want to replace those by their actual values. + if isinstance(default, (int, float)) and re.search("defaults to `?(.*?)(?:`|$)", description) is not None: + # Grab the default and evaluate it. + current_default = re.search("defaults to `?(.*?)(?:`|$)", description).groups()[0] + if default == eval_math_expression(current_default): + try: + # If it can be directly converted to the type of the default, it's a simple value + str_default = str(type(default)(current_default)) + except Exception: + # Otherwise there is a math operator so we add a code block. + str_default = f"`{current_default}`" + elif isinstance(default, enum.Enum) and default.name == current_default.split(".")[-1]: + # When the default is an Enum (this is often the case for PIL.Image.Resampling), and the docstring + # matches the enum name, keep the existing docstring rather than clobbering it with the enum value. + str_default = f"`{current_default}`" + + if str_default is None: + str_default = stringify_default(default) + # Make sure default match + if OPTIONAL_KEYWORD not in description: + description = f"{description}, {OPTIONAL_KEYWORD}, defaults to {str_default}" + elif _re_parse_description.search(description) is None: + idx = description.find(OPTIONAL_KEYWORD) + len_optional = len(OPTIONAL_KEYWORD) + description = f"{description[: idx + len_optional]}, defaults to {str_default}" + else: + description = _re_parse_description.sub(rf"*optional*, defaults to {str_default}", description) + + return description + + +def get_default_description(arg: inspect.Parameter) -> str: + """ + Builds a default description for a parameter that was not documented. + + Args: + arg (`inspect.Parameter`): The argument in the signature to generate a description for. + + Returns: + `str`: The description. + """ + if arg.annotation is inspect._empty: + arg_type = "" + elif hasattr(arg.annotation, "__name__"): + arg_type = arg.annotation.__name__ + else: + arg_type = str(arg.annotation) + + if arg.default is inspect._empty: + return f"`{arg_type}`" + elif arg.default is None: + return f"`{arg_type}`, {OPTIONAL_KEYWORD}" + else: + str_default = stringify_default(arg.default) + return f"`{arg_type}`, {OPTIONAL_KEYWORD}, defaults to {str_default}" + + +def find_source_file(obj: Any) -> Path: + """ + Finds the source file of an object. + + Args: + obj (`Any`): The object whose source file we are looking for. + + Returns: + `Path`: The source file. + """ + module = obj.__module__ + obj_file = PATH_TO_TRANSFORMERS + for part in module.split(".")[1:]: + obj_file = obj_file / part + return obj_file.with_suffix(".py") + + +def match_docstring_with_signature(obj: Any) -> Optional[tuple[str, str]]: + """ + Matches the docstring of an object with its signature. + + Args: + obj (`Any`): The object to process. + + Returns: + `Optional[Tuple[str, str]]`: Returns `None` if there is no docstring or no parameters documented in the + docstring, otherwise returns a tuple of two strings: the current documentation of the arguments in the + docstring and the one matched with the signature. + """ + if len(getattr(obj, "__doc__", "")) == 0: + # Nothing to do, there is no docstring. + return + + # Read the docstring in the source code to see if there is a special command to ignore this object. + try: + source, _ = inspect.getsourcelines(obj) + except OSError: + source = [] + + # Find the line where the docstring starts + idx = 0 + while idx < len(source) and '"""' not in source[idx]: + idx += 1 + + ignore_order = False + if idx < len(source): + line_before_docstring = source[idx - 1] + # Match '# no-format' (allowing surrounding whitespaces) + if re.search(r"^\s*#\s*no-format\s*$", line_before_docstring): + # This object is ignored by the auto-docstring tool + return + # Match '# ignore-order' (allowing surrounding whitespaces) + elif re.search(r"^\s*#\s*ignore-order\s*$", line_before_docstring): + ignore_order = True + + # Read the signature + signature = inspect.signature(obj).parameters + + obj_doc_lines = obj.__doc__.split("\n") + # Get to the line where we start documenting arguments + idx = 0 + while idx < len(obj_doc_lines) and _re_args.search(obj_doc_lines[idx]) is None: + idx += 1 + + if idx == len(obj_doc_lines): + # Nothing to do, no parameters are documented. + return + + if "kwargs" in signature and signature["kwargs"].annotation != inspect._empty: + # Inspecting signature with typed kwargs is not supported yet. + return + + indent = find_indent(obj_doc_lines[idx]) + arguments = {} + current_arg = None + idx += 1 + start_idx = idx + # Keep going until the arg section is finished (nonempty line at the same indent level) or the end of the docstring. + while idx < len(obj_doc_lines) and ( + len(obj_doc_lines[idx].strip()) == 0 or find_indent(obj_doc_lines[idx]) > indent + ): + if find_indent(obj_doc_lines[idx]) == indent + 4: + # New argument -> let's generate the proper doc for it + re_search_arg = _re_parse_arg.search(obj_doc_lines[idx]) + if re_search_arg is not None: + _, name, description = re_search_arg.groups() + current_arg = name + if name in signature: + default = signature[name].default + if signature[name].kind is inspect._ParameterKind.VAR_KEYWORD: + default = None + new_description = replace_default_in_arg_description(description, default) + else: + new_description = description + init_doc = _re_parse_arg.sub(rf"\1\2 ({new_description}):", obj_doc_lines[idx]) + arguments[current_arg] = [init_doc] + elif current_arg is not None: + arguments[current_arg].append(obj_doc_lines[idx]) + + idx += 1 + + # We went too far by one (perhaps more if there are a lot of new lines) + idx -= 1 + if current_arg: + while len(obj_doc_lines[idx].strip()) == 0: + arguments[current_arg] = arguments[current_arg][:-1] + idx -= 1 + # And we went too far by one again. + idx += 1 + + old_doc_arg = "\n".join(obj_doc_lines[start_idx:idx]) + + old_arguments = list(arguments.keys()) + arguments = {name: "\n".join(doc) for name, doc in arguments.items()} + # Add missing arguments with a template + for name in set(signature.keys()) - set(arguments.keys()): + arg = signature[name] + # We ignore private arguments or *args/**kwargs (unless they are documented by the user) + if name.startswith("_") or arg.kind in [ + inspect._ParameterKind.VAR_KEYWORD, + inspect._ParameterKind.VAR_POSITIONAL, + ]: + arguments[name] = "" + else: + arg_desc = get_default_description(arg) + arguments[name] = " " * (indent + 4) + f"{name} ({arg_desc}): " + + # Arguments are sorted by the order in the signature unless a special comment is put. + if ignore_order: + new_param_docs = [arguments[name] for name in old_arguments if name in signature] + missing = set(signature.keys()) - set(old_arguments) + new_param_docs.extend([arguments[name] for name in missing if len(arguments[name]) > 0]) + else: + new_param_docs = [arguments[name] for name in signature if len(arguments[name]) > 0] + new_doc_arg = "\n".join(new_param_docs) + + return old_doc_arg, new_doc_arg + + +def fix_docstring(obj: Any, old_doc_args: str, new_doc_args: str): + """ + Fixes the docstring of an object by replacing its arguments documentation by the one matched with the signature. + + Args: + obj (`Any`): + The object whose dostring we are fixing. + old_doc_args (`str`): + The current documentation of the parameters of `obj` in the docstring (as returned by + `match_docstring_with_signature`). + new_doc_args (`str`): + The documentation of the parameters of `obj` matched with its signature (as returned by + `match_docstring_with_signature`). + """ + # Read the docstring in the source code and make sure we have the right part of the docstring + source, line_number = inspect.getsourcelines(obj) + + # Get to the line where we start documenting arguments + idx = 0 + while idx < len(source) and _re_args.search(source[idx]) is None: + idx += 1 + + if idx == len(source): + # Args are not defined in the docstring of this object. This can happen when the docstring is inherited. + # In this case, we are not trying to fix it on the child object. + return + + # Get to the line where we stop documenting arguments + indent = find_indent(source[idx]) + idx += 1 + start_idx = idx + while idx < len(source) and (len(source[idx].strip()) == 0 or find_indent(source[idx]) > indent): + idx += 1 + + idx -= 1 + while len(source[idx].strip()) == 0: + idx -= 1 + idx += 1 + + # `old_doc_args` is built from `obj.__doc__`, which may have + # different indentation than the raw source from `inspect.getsourcelines`. + # We use `inspect.cleandoc` to remove indentation uniformly from both + # strings before comparing them. + source_args_as_str = "".join(source[start_idx:idx]) + if inspect.cleandoc(source_args_as_str) != inspect.cleandoc(old_doc_args): + # Args are not fully defined in the docstring of this object + obj_file = find_source_file(obj) + actual_args_section = source_args_as_str.rstrip() + raise ValueError( + f"Cannot fix docstring of {obj.__name__} in {obj_file} because the argument section in the source code " + f"does not match the expected format. This usually happens when:\n" + f"1. The argument section is not properly indented\n" + f"2. The argument section contains unexpected formatting\n" + f"3. The docstring parsing failed to correctly identify the argument boundaries\n\n" + f"Expected argument section:\n{repr(old_doc_args)}\n\n" + f"Actual argument section found:\n{repr(actual_args_section)}\n\n" + ) + + obj_file = find_source_file(obj) + with open(obj_file, "r", encoding="utf-8") as f: + content = f.read() + + # Replace content + lines = content.split("\n") + prev_line_indentation = find_indent(lines[line_number + start_idx - 2]) + # Now increase the indentation of every line in new_doc_args by prev_line_indentation + new_doc_args = "\n".join([f"{' ' * prev_line_indentation}{line}" for line in new_doc_args.split("\n")]) + + lines = lines[: line_number + start_idx - 1] + [new_doc_args] + lines[line_number + idx - 1 :] + + print(f"Fixing the docstring of {obj.__name__} in {obj_file}.") + with open(obj_file, "w", encoding="utf-8") as f: + f.write("\n".join(lines)) + + +def _find_sig_line(lines, line_end): + parenthesis_count = 0 + sig_line_end = line_end + found_sig = False + while not found_sig: + for char in lines[sig_line_end]: + if char == "(": + parenthesis_count += 1 + elif char == ")": + parenthesis_count -= 1 + if parenthesis_count == 0: + found_sig = True + break + sig_line_end += 1 + return sig_line_end + + +def _find_docstring_end_line(lines, docstring_start_line): + if '"""' not in lines[docstring_start_line]: + return None + docstring_end = docstring_start_line + if docstring_start_line is not None: + docstring_end = docstring_start_line + if not lines[docstring_start_line].count('"""') >= 2: + docstring_end += 1 + while '"""' not in lines[docstring_end]: + docstring_end += 1 + return docstring_end + + +def find_matching_model_files(check_all: bool = False): + """ + Find all model files in the transformers repo that should be checked for @auto_docstring, + excluding files with certain substrings. + Returns: + List of file paths. + """ + module_diff_files = None + if not check_all: + module_diff_files = set() + repo = Repo(PATH_TO_REPO) + # Diff from index to unstaged files + for modified_file_diff in repo.index.diff(None): + if modified_file_diff.a_path.startswith("src/transformers"): + module_diff_files.add(os.path.join(PATH_TO_REPO, modified_file_diff.a_path)) + # Diff from index to `main` + for modified_file_diff in repo.index.diff(repo.refs.main.commit): + if modified_file_diff.a_path.startswith("src/transformers"): + module_diff_files.add(os.path.join(PATH_TO_REPO, modified_file_diff.a_path)) + # quick escape route: if there are no module files in the diff, skip this check + if len(module_diff_files) == 0: + return None + + modeling_glob_pattern = os.path.join(PATH_TO_TRANSFORMERS, "models/**/modeling_**") + potential_files = glob.glob(modeling_glob_pattern) + image_processing_glob_pattern = os.path.join(PATH_TO_TRANSFORMERS, "models/**/image_processing_*_fast.py") + potential_files += glob.glob(image_processing_glob_pattern) + exclude_substrings = ["modeling_tf_", "modeling_flax_"] + matching_files = [] + for file_path in potential_files: + if os.path.isfile(file_path): + filename = os.path.basename(file_path) + is_excluded = any(exclude in filename for exclude in exclude_substrings) + if not is_excluded: + matching_files.append(file_path) + if not check_all: + # intersect with module_diff_files + matching_files = sorted([file for file in matching_files if file in module_diff_files]) + + print(" Checking auto_docstrings in the following files:" + "\n - " + "\n - ".join(matching_files)) + + return matching_files + + +def find_files_with_auto_docstring(matching_files, decorator="@auto_docstring"): + """ + From a list of files, return those that contain the @auto_docstring decorator. + """ + auto_docstrings_files = [] + for file_path in matching_files: + with open(file_path, "r", encoding="utf-8") as f: + content_base_file = f.read() + if decorator in content_base_file: + lines = content_base_file.split("\n") + line_numbers = [i for i, line in enumerate(lines) if decorator in line] + for line_number in line_numbers: + line_end = line_number + end_patterns = ["class ", " def"] + stop_condition = False + while line_end < len(lines) and not stop_condition: + line_end += 1 + stop_condition = any(lines[line_end].startswith(end_pattern) for end_pattern in end_patterns) + candidate_patterns = ["class ", " def"] + candidate = any( + lines[line_end].startswith(candidate_pattern) for candidate_pattern in candidate_patterns + ) + if stop_condition and candidate: + auto_docstrings_files.append(file_path) + break + return auto_docstrings_files + + +def get_auto_docstring_candidate_lines(lines): + """ + For a file's lines, find the start and end line indices of all @auto_docstring candidates. + Returns two lists: starts and ends. + """ + line_numbers = [i for i, line in enumerate(lines) if "@auto_docstring" in line] + line_starts_candidates = [] + line_ends_candidates = [] + for line_number in line_numbers: + line_end = line_number + end_patterns = ["class ", " def"] + stop_condition = False + while line_end < len(lines) and not stop_condition: + line_end += 1 + stop_condition = any(lines[line_end].startswith(end_pattern) for end_pattern in end_patterns) + candidate_patterns = ["class ", " def"] + candidate = any(lines[line_end].startswith(candidate_pattern) for candidate_pattern in candidate_patterns) + if stop_condition and candidate: + line_ends_candidates.append(line_end) + line_starts_candidates.append(line_number) + return line_starts_candidates, line_ends_candidates + + +def get_args_in_signature(lines, signature_content): + signature_content = [line.split("#")[0] for line in signature_content] + signature_content = "".join(signature_content) + signature_content = "".join(signature_content.split(")")[:-1]) + args_in_signature = re.findall(r"[,(]\s*(\w+)\s*(?=:|=|,|\))", signature_content) + if "self" in args_in_signature: + args_in_signature.remove("self") + return args_in_signature + + +def get_args_in_dataclass(lines, dataclass_content): + dataclass_content = [line.split("#")[0] for line in dataclass_content] + dataclass_content = "\n".join(dataclass_content) + args_in_dataclass = re.findall(r"^ (\w+)(?:\s*:|\s*=|\s*$)", dataclass_content, re.MULTILINE) + if "self" in args_in_dataclass: + args_in_dataclass.remove("self") + return args_in_dataclass + + +def generate_new_docstring_for_signature( + lines, + args_in_signature, + sig_end_line, + docstring_start_line, + arg_indent=" ", + output_docstring_indent=8, + custom_args_dict={}, + source_args_doc=[ModelArgs, ImageProcessorArgs], +): + """ + Generalized docstring generator for a function or class signature. + Args: + lines: List of lines from the file. + sig_start_line: Line index where the signature starts. + sig_end_line: Line index where the signature ends. + docstring_line: Line index where the docstring starts (or None if not present). + arg_indent: Indentation for missing argument doc entries. + Returns: + new_docstring, sig_end_line, docstring_end (last docstring line index) + """ + # Extract and clean signature + missing_docstring_args = [] + docstring_args_ro_remove = [] + fill_docstring_args = [] + + # Parse docstring if present + args_docstring_dict = {} + remaining_docstring = "" + if docstring_start_line is not None: + docstring_end_line = _find_docstring_end_line(lines, docstring_start_line) + docstring_content = lines[docstring_start_line : docstring_end_line + 1] + parsed_docstring, remaining_docstring = parse_docstring("\n".join(docstring_content)) + args_docstring_dict.update(parsed_docstring) + else: + docstring_end_line = None + + # Remove args that are the same as the ones in the source args doc + for arg in args_docstring_dict: + if arg in get_args_doc_from_source(source_args_doc) and arg not in ALWAYS_OVERRIDE: + source_arg_doc = get_args_doc_from_source(source_args_doc)[arg] + if source_arg_doc["description"].strip("\n ") == args_docstring_dict[arg]["description"].strip("\n "): + if source_arg_doc.get("shape") is not None and args_docstring_dict[arg].get("shape") is not None: + if source_arg_doc.get("shape").strip("\n ") == args_docstring_dict[arg].get("shape").strip("\n "): + docstring_args_ro_remove.append(arg) + elif ( + source_arg_doc.get("additional_info") is not None + and args_docstring_dict[arg].get("additional_info") is not None + ): + if source_arg_doc.get("additional_info").strip("\n ") == args_docstring_dict[arg].get( + "additional_info" + ).strip("\n "): + docstring_args_ro_remove.append(arg) + else: + docstring_args_ro_remove.append(arg) + args_docstring_dict = { + arg: args_docstring_dict[arg] for arg in args_docstring_dict if arg not in docstring_args_ro_remove + } + + # Fill missing args + for arg in args_in_signature: + if ( + arg not in args_docstring_dict + and arg not in get_args_doc_from_source(source_args_doc) + and arg not in custom_args_dict + ): + missing_docstring_args.append(arg) + args_docstring_dict[arg] = { + "type": "", + "optional": False, + "shape": None, + "description": "\n ", + "default": None, + "additional_info": None, + } + + # Handle docstring of inherited args (for dataclasses) + ordered_args_docstring_dict = OrderedDict( + (arg, args_docstring_dict[arg]) for arg in args_docstring_dict if arg not in args_in_signature + ) + # Add args in the order of the signature + ordered_args_docstring_dict.update( + (arg, args_docstring_dict[arg]) for arg in args_in_signature if arg in args_docstring_dict + ) + # Build new docstring + new_docstring = "" + if len(ordered_args_docstring_dict) > 0 or remaining_docstring: + new_docstring += 'r"""\n' + for arg in ordered_args_docstring_dict: + additional_info = ordered_args_docstring_dict[arg]["additional_info"] or "" + custom_arg_description = ordered_args_docstring_dict[arg]["description"] + if "" in custom_arg_description and arg not in missing_docstring_args: + fill_docstring_args.append(arg) + if custom_arg_description.endswith('"""'): + custom_arg_description = "\n".join(custom_arg_description.split("\n")[:-1]) + new_docstring += ( + f"{arg} ({ordered_args_docstring_dict[arg]['type']}{additional_info}):{custom_arg_description}\n" + ) + close_docstring = True + if remaining_docstring: + if remaining_docstring.endswith('"""'): + close_docstring = False + end_docstring = "\n" if close_docstring else "" + new_docstring += f"{set_min_indent(remaining_docstring, 0)}{end_docstring}" + if close_docstring: + new_docstring += '"""' + new_docstring = set_min_indent(new_docstring, output_docstring_indent) + + return ( + new_docstring, + sig_end_line, + docstring_end_line if docstring_end_line is not None else sig_end_line - 1, + missing_docstring_args, + fill_docstring_args, + docstring_args_ro_remove, + ) + + +def generate_new_docstring_for_function(lines, current_line_end, custom_args_dict): + """ + Wrapper for function docstring generation using the generalized helper. + """ + sig_end_line = _find_sig_line(lines, current_line_end) + signature_content = lines[current_line_end:sig_end_line] + args_in_signature = get_args_in_signature(lines, signature_content) + docstring_start_line = sig_end_line if '"""' in lines[sig_end_line] else None + return generate_new_docstring_for_signature( + lines, + args_in_signature, + sig_end_line, + docstring_start_line, + arg_indent=" ", + custom_args_dict=custom_args_dict, + ) + + +def generate_new_docstring_for_class(lines, current_line_end, custom_args_dict): + """ + Wrapper for class docstring generation (via __init__) using the generalized helper. + Returns the new docstring and relevant signature/docstring indices. + """ + sig_start_line = current_line_end + found_init_method = False + found_model_output = False + while sig_start_line < len(lines) - 1 and not found_init_method: + sig_start_line += 1 + if " def __init__" in lines[sig_start_line]: + found_init_method = True + elif lines[sig_start_line].startswith("class ") or lines[sig_start_line].startswith("def "): + break + if not found_init_method: + if "ModelOutput" in lines[current_line_end]: + found_model_output = True + sig_start_line = current_line_end + else: + return "", None, None, [], [], [] + + if found_init_method: + sig_end_line = _find_sig_line(lines, sig_start_line) + signature_content = lines[sig_start_line:sig_end_line] + args_in_signature = get_args_in_signature(lines, signature_content) + else: + # we have a ModelOutput class, the class attributes are the args + sig_end_line = sig_start_line + 1 + docstring_end = _find_docstring_end_line(lines, sig_end_line) + model_output_class_start = docstring_end + 1 if docstring_end is not None else sig_end_line - 1 + model_output_class_end = model_output_class_start + while model_output_class_end < len(lines) and ( + lines[model_output_class_end].startswith(" ") or lines[model_output_class_end] == "" + ): + model_output_class_end += 1 + dataclass_content = lines[model_output_class_start : model_output_class_end - 1] + args_in_signature = get_args_in_dataclass(lines, dataclass_content) + + docstring_start_line = sig_end_line if '"""' in lines[sig_end_line] else None + + return generate_new_docstring_for_signature( + lines, + args_in_signature, + sig_end_line, + docstring_start_line, + arg_indent="", + custom_args_dict=custom_args_dict, + output_docstring_indent=4 if found_model_output else 8, + source_args_doc=[ModelArgs, ImageProcessorArgs] if not found_model_output else [ModelOutputArgs], + ) + + +def find_custom_args_with_details(file_content: str, custom_args_var_name: str) -> list[dict]: + """ + Find the given custom args variable in the file content and return its content. + + Args: + file_content: The string content of the Python file. + custom_args_var_name: The name of the custom args variable. + """ + # Escape the variable_name to handle any special regex characters it might contain + escaped_variable_name = re.escape(custom_args_var_name) + + # Construct the regex pattern dynamically with the specific variable name + # This regex looks for: + # ^\s* : Start of a line with optional leading whitespace. + # ({escaped_variable_name}) : Capture the exact variable name. + # \s*=\s* : An equals sign, surrounded by optional whitespace. + # (r?\"\"\") : Capture the opening triple quotes (raw or normal string). + # (.*?) : Capture the content (non-greedy). + # (\"\"\") : Match the closing triple quotes. + regex_pattern = rf"^\s*({escaped_variable_name})\s*=\s*(r?\"\"\")(.*?)(\"\"\")" + + flags = re.MULTILINE | re.DOTALL + + # Use re.search to find the first match + match = re.search(regex_pattern, file_content, flags) + + if match: + # match.group(1) will be the variable_name itself + # match.group(3) will be the content inside the triple quotes + content = match.group(3).strip() + return content + return None + + +def update_file_with_new_docstrings( + candidate_file, lines, line_starts_candidates, line_ends_candidates, overwrite=False +): + """ + For a given file, update the docstrings for all @auto_docstring candidates and write the new content. + """ + content_base_file_new_lines = lines[: line_ends_candidates[0]] + current_line_start = line_starts_candidates[0] + current_line_end = line_ends_candidates[0] + index = 1 + missing_docstring_args_warnings = [] + fill_docstring_args_warnings = [] + docstring_args_ro_remove_warnings = [] + + while index <= len(line_starts_candidates): + custom_args_dict = {} + auto_docstring_signature_content = "".join(lines[current_line_start:current_line_end]) + match = re.findall(r"custom_args=(\w+)", auto_docstring_signature_content) + if match: + custom_args_var_name = match[0] + custom_args_var_content = find_custom_args_with_details("\n".join(lines), custom_args_var_name) + if custom_args_var_content: + custom_args_dict, _ = parse_docstring(custom_args_var_content) + new_docstring = "" + modify_class_docstring = False + # Function + if " def" in lines[current_line_end]: + ( + new_docstring, + sig_line_end, + docstring_end, + missing_docstring_args, + fill_docstring_args, + docstring_args_ro_remove, + ) = generate_new_docstring_for_function(lines, current_line_end, custom_args_dict) + # Class + elif "class " in lines[current_line_end]: + ( + new_docstring, + class_sig_line_end, + class_docstring_end_line, + missing_docstring_args, + fill_docstring_args, + docstring_args_ro_remove, + ) = generate_new_docstring_for_class(lines, current_line_end, custom_args_dict) + modify_class_docstring = class_sig_line_end is not None + # Add warnings if needed + if missing_docstring_args: + for arg in missing_docstring_args: + missing_docstring_args_warnings.append(f" - {arg} line {current_line_end}") + if fill_docstring_args: + for arg in fill_docstring_args: + fill_docstring_args_warnings.append(f" - {arg} line {current_line_end}") + if docstring_args_ro_remove: + for arg in docstring_args_ro_remove: + docstring_args_ro_remove_warnings.append(f" - {arg} line {current_line_end}") + # Write new lines + if index >= len(line_ends_candidates) or line_ends_candidates[index] > current_line_end: + if " def" in lines[current_line_end]: + content_base_file_new_lines += lines[current_line_end:sig_line_end] + if new_docstring != "": + content_base_file_new_lines += new_docstring.split("\n") + if index < len(line_ends_candidates): + content_base_file_new_lines += lines[docstring_end + 1 : line_ends_candidates[index]] + else: + content_base_file_new_lines += lines[docstring_end + 1 :] + elif modify_class_docstring: + content_base_file_new_lines += lines[current_line_end:class_sig_line_end] + if new_docstring != "": + content_base_file_new_lines += new_docstring.split("\n") + if index < len(line_ends_candidates): + content_base_file_new_lines += lines[class_docstring_end_line + 1 : line_ends_candidates[index]] + else: + content_base_file_new_lines += lines[class_docstring_end_line + 1 :] + elif index < len(line_ends_candidates): + content_base_file_new_lines += lines[current_line_end : line_ends_candidates[index]] + else: + content_base_file_new_lines += lines[current_line_end:] + if index < len(line_ends_candidates): + current_line_end = line_ends_candidates[index] + current_line_start = line_starts_candidates[index] + index += 1 + content_base_file_new = "\n".join(content_base_file_new_lines) + if overwrite: + with open(candidate_file, "w", encoding="utf-8") as f: + f.write(content_base_file_new) + + return ( + missing_docstring_args_warnings, + fill_docstring_args_warnings, + docstring_args_ro_remove_warnings, + ) + + +# TODO (Yoni): The functions in check_auto_docstrings rely on direct code parsing, which is prone to +# failure on edge cases and not robust to code changes. While this approach is significantly faster +# than using inspect (like in check_docstrings) and allows parsing any object including non-public +# ones, it may need to be refactored in the future to use a more robust parsing method. Note that +# we still need auto_docstring for some non-public objects since their docstrings are included in the +# docs of public objects (e.g. ModelOutput classes). +def check_auto_docstrings(overwrite: bool = False, check_all: bool = False): + """ + Check docstrings of all public objects that are decorated with `@auto_docstrings`. + This function orchestrates the process by finding relevant files, scanning for decorators, + generating new docstrings, and updating files as needed. + """ + # 1. Find all model files to check + matching_files = find_matching_model_files(check_all) + if matching_files is None: + return + # 2. Find files that contain the @auto_docstring decorator + auto_docstrings_files = find_files_with_auto_docstring(matching_files) + # 3. For each file, update docstrings for all candidates + for candidate_file in auto_docstrings_files: + with open(candidate_file, "r", encoding="utf-8") as f: + lines = f.read().split("\n") + line_starts_candidates, line_ends_candidates = get_auto_docstring_candidate_lines(lines) + missing_docstring_args_warnings, fill_docstring_args_warnings, docstring_args_ro_remove_warnings = ( + update_file_with_new_docstrings( + candidate_file, lines, line_starts_candidates, line_ends_candidates, overwrite=overwrite + ) + ) + if missing_docstring_args_warnings: + if not overwrite: + print( + "Some docstrings are missing. Run `make fix-copies` or `python utils/check_docstrings.py --fix_and_overwrite` to generate the docstring templates where needed." + ) + print(f"🚨 Missing docstring for the following arguments in {candidate_file}:") + for warning in missing_docstring_args_warnings: + print(warning) + if docstring_args_ro_remove_warnings: + if not overwrite: + print( + "Some docstrings are redundant with the ones in `auto_docstring.py` and will be removed. Run `make fix-copies` or `python utils/check_docstrings.py --fix_and_overwrite` to remove the redundant docstrings." + ) + print(f"🚨 Redundant docstring for the following arguments in {candidate_file}:") + for warning in docstring_args_ro_remove_warnings: + print(warning) + if fill_docstring_args_warnings: + print(f"🚨 Docstring needs to be filled for the following arguments in {candidate_file}:") + for warning in fill_docstring_args_warnings: + print(warning) + + +def check_docstrings(overwrite: bool = False, check_all: bool = False): + """ + Check docstrings of all public objects that are callables and are documented. By default, only checks the diff. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): + Whether to fix inconsistencies or not. + check_all (`bool`, *optional*, defaults to `False`): + Whether to check all files. + """ + module_diff_files = None + if not check_all: + module_diff_files = set() + repo = Repo(PATH_TO_REPO) + # Diff from index to unstaged files + for modified_file_diff in repo.index.diff(None): + if modified_file_diff.a_path.startswith("src/transformers"): + module_diff_files.add(modified_file_diff.a_path) + # Diff from index to `main` + for modified_file_diff in repo.index.diff(repo.refs.main.commit): + if modified_file_diff.a_path.startswith("src/transformers"): + module_diff_files.add(modified_file_diff.a_path) + # quick escape route: if there are no module files in the diff, skip this check + if len(module_diff_files) == 0: + return + print(" Checking docstrings in the following files:" + "\n - " + "\n - ".join(module_diff_files)) + + failures = [] + hard_failures = [] + to_clean = [] + for name in dir(transformers): + # Skip objects that are private or not documented. + if name.startswith("_") or ignore_undocumented(name) or name in OBJECTS_TO_IGNORE: + continue + + obj = getattr(transformers, name) + if not callable(obj) or not isinstance(obj, type) or getattr(obj, "__doc__", None) is None: + continue + + # If we are checking against the diff, we skip objects that are not part of the diff. + if module_diff_files is not None: + object_file = find_source_file(getattr(transformers, name)) + object_file_relative_path = "src/" + str(object_file).split("/src/")[1] + if object_file_relative_path not in module_diff_files: + continue + + # Check docstring + try: + result = match_docstring_with_signature(obj) + if result is not None: + old_doc, new_doc = result + else: + old_doc, new_doc = None, None + except Exception as e: + print(e) + hard_failures.append(name) + continue + if old_doc != new_doc: + if overwrite: + fix_docstring(obj, old_doc, new_doc) + else: + failures.append(name) + elif not overwrite and new_doc is not None and ("" in new_doc or "" in new_doc): + to_clean.append(name) + + # Deal with errors + error_message = "" + if len(hard_failures) > 0: + error_message += ( + "The argument part of the docstrings of the following objects could not be processed, check they are " + "properly formatted." + ) + error_message += "\n" + "\n".join([f"- {name}" for name in hard_failures]) + if len(failures) > 0: + error_message += ( + "The following objects docstrings do not match their signature. Run `make fix-copies` to fix this. " + "In some cases, this error may be raised incorrectly by the docstring checker. If you think this is the " + "case, you can manually check the docstrings and then add the object name to `OBJECTS_TO_IGNORE` in " + "`utils/check_docstrings.py`." + ) + error_message += "\n" + "\n".join([f"- {name}" for name in failures]) + if len(to_clean) > 0: + error_message += ( + "The following objects docstrings contain templates you need to fix: search for `` or " + "``." + ) + error_message += "\n" + "\n".join([f"- {name}" for name in to_clean]) + + if len(error_message) > 0: + error_message = "There was at least one problem when checking docstrings of public objects.\n" + error_message + raise ValueError(error_message) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + parser.add_argument( + "--check_all", action="store_true", help="Whether to check all files. By default, only checks the diff" + ) + args = parser.parse_args() + check_auto_docstrings(overwrite=args.fix_and_overwrite, check_all=args.check_all) + check_docstrings(overwrite=args.fix_and_overwrite, check_all=args.check_all) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_doctest_list.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_doctest_list.py new file mode 100644 index 0000000000000000000000000000000000000000..1d763475cb63dc8662395e94d6c1ec58598a40d8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_doctest_list.py @@ -0,0 +1,86 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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 script is responsible for cleaning the list of doctests by making sure the entries all exist and are in +alphabetical order. + +Usage (from the root of the repo): + +Check that the doctest list is properly sorted and all files exist (used in `make repo-consistency`): + +```bash +python utils/check_doctest_list.py +``` + +Auto-sort the doctest list if it is not properly sorted (used in `make fix-copies`): + +```bash +python utils/check_doctest_list.py --fix_and_overwrite +``` +""" + +import argparse +import os + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_doctest_list.py +REPO_PATH = "." +DOCTEST_FILE_PATHS = ["not_doctested.txt", "slow_documentation_tests.txt"] + + +def clean_doctest_list(doctest_file: str, overwrite: bool = False): + """ + Cleans the doctest in a given file. + + Args: + doctest_file (`str`): + The path to the doctest file to check or clean. + overwrite (`bool`, *optional*, defaults to `False`): + Whether or not to fix problems. If `False`, will error when the file is not clean. + """ + non_existent_paths = [] + all_paths = [] + with open(doctest_file, "r", encoding="utf-8") as f: + for line in f: + line = line.strip().split(" ")[0] + path = os.path.join(REPO_PATH, line) + if not (os.path.isfile(path) or os.path.isdir(path)): + non_existent_paths.append(line) + all_paths.append(line) + + if len(non_existent_paths) > 0: + non_existent_paths = "\n".join([f"- {f}" for f in non_existent_paths]) + raise ValueError(f"`{doctest_file}` contains non-existent paths:\n{non_existent_paths}") + + sorted_paths = sorted(all_paths) + if all_paths != sorted_paths: + if not overwrite: + raise ValueError( + f"Files in `{doctest_file}` are not in alphabetical order, run `make fix-copies` to fix " + "this automatically." + ) + with open(doctest_file, "w", encoding="utf-8") as f: + f.write("\n".join(sorted_paths) + "\n") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + for doctest_file in DOCTEST_FILE_PATHS: + doctest_file = os.path.join(REPO_PATH, "utils", doctest_file) + clean_doctest_list(doctest_file, args.fix_and_overwrite) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_dummies.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_dummies.py new file mode 100644 index 0000000000000000000000000000000000000000..b9757bdb0250bfbd523c94379a98434fafde893c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_dummies.py @@ -0,0 +1,256 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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 script is responsible for making sure the dummies in utils/dummies_xxx.py are up to date with the main init. + +Why dummies? This is to make sure that a user can always import all objects from `transformers`, even if they don't +have the necessary extra libs installed. Those objects will then raise helpful error message whenever the user tries +to access one of their methods. + +Usage (from the root of the repo): + +Check that the dummy files are up to date (used in `make repo-consistency`): + +```bash +python utils/check_dummies.py +``` + +Update the dummy files if needed (used in `make fix-copies`): + +```bash +python utils/check_dummies.py --fix_and_overwrite +``` +""" + +import argparse +import os +import re +from typing import Optional + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_dummies.py +PATH_TO_TRANSFORMERS = "src/transformers" + +# Matches is_xxx_available() +_re_backend = re.compile(r"is\_([a-z_]*)_available()") +# Matches from xxx import bla +_re_single_line_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") +# Matches if not is_xxx_available() +_re_test_backend = re.compile(r"^\s+if\s+not\s+\(?is\_[a-z_]*\_available\(\)") + + +# Template for the dummy objects. +DUMMY_CONSTANT = """ +{0} = None +""" + + +DUMMY_CLASS = """ +class {0}(metaclass=DummyObject): + _backends = {1} + + def __init__(self, *args, **kwargs): + requires_backends(self, {1}) +""" + + +DUMMY_FUNCTION = """ +def {0}(*args, **kwargs): + requires_backends({0}, {1}) +""" + + +def find_backend(line: str) -> Optional[str]: + """ + Find one (or multiple) backend in a code line of the init. + + Args: + line (`str`): A code line in an init file. + + Returns: + Optional[`str`]: If one (or several) backend is found, returns it. In the case of multiple backends (the line + contains `if is_xxx_available() and `is_yyy_available()`) returns all backends joined on `_and_` (so + `xxx_and_yyy` for instance). + """ + if _re_test_backend.search(line) is None: + return None + backends = [b[0] for b in _re_backend.findall(line)] + backends.sort() + return "_and_".join(backends) + + +def read_init() -> dict[str, list[str]]: + """ + Read the init and extract backend-specific objects. + + Returns: + Dict[str, List[str]]: A dictionary mapping backend name to the list of object names requiring that backend. + """ + with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Get to the point we do the actual imports for type checking + line_index = 0 + while not lines[line_index].startswith("if TYPE_CHECKING"): + line_index += 1 + + backend_specific_objects = {} + # Go through the end of the file + while line_index < len(lines): + # If the line is an if is_backend_available, we grab all objects associated. + backend = find_backend(lines[line_index]) + if backend is not None: + while not lines[line_index].startswith(" else:"): + line_index += 1 + line_index += 1 + + objects = [] + # Until we unindent, add backend objects to the list + while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8): + line = lines[line_index] + single_line_import_search = _re_single_line_import.search(line) + if single_line_import_search is not None: + # Single-line imports + objects.extend(single_line_import_search.groups()[0].split(", ")) + elif line.startswith(" " * 12): + # Multiple-line imports (with 3 indent level) + objects.append(line[12:-2]) + line_index += 1 + + backend_specific_objects[backend] = objects + else: + line_index += 1 + + return backend_specific_objects + + +def create_dummy_object(name: str, backend_name: str) -> str: + """ + Create the code for a dummy object. + + Args: + name (`str`): The name of the object. + backend_name (`str`): The name of the backend required for that object. + + Returns: + `str`: The code of the dummy object. + """ + if name.isupper(): + return DUMMY_CONSTANT.format(name) + elif name.islower(): + return DUMMY_FUNCTION.format(name, backend_name) + else: + return DUMMY_CLASS.format(name, backend_name) + + +def create_dummy_files(backend_specific_objects: Optional[dict[str, list[str]]] = None) -> dict[str, str]: + """ + Create the content of the dummy files. + + Args: + backend_specific_objects (`Dict[str, List[str]]`, *optional*): + The mapping backend name to list of backend-specific objects. If not passed, will be obtained by calling + `read_init()`. + + Returns: + `Dict[str, str]`: A dictionary mapping backend name to code of the corresponding backend file. + """ + if backend_specific_objects is None: + backend_specific_objects = read_init() + + dummy_files = {} + + for backend, objects in backend_specific_objects.items(): + backend_name = "[" + ", ".join(f'"{b}"' for b in backend.split("_and_")) + "]" + dummy_file = "# This file is autogenerated by the command `make fix-copies`, do not edit.\n" + dummy_file += "from ..utils import DummyObject, requires_backends\n\n" + dummy_file += "\n".join([create_dummy_object(o, backend_name) for o in objects]) + dummy_files[backend] = dummy_file + + return dummy_files + + +def check_dummies(overwrite: bool = False): + """ + Check if the dummy files are up to date and maybe `overwrite` with the right content. + + Args: + overwrite (`bool`, *optional*, default to `False`): + Whether or not to overwrite the content of the dummy files. Will raise an error if they are not up to date + when `overwrite=False`. + """ + dummy_files = create_dummy_files() + # For special correspondence backend name to shortcut as used in utils/dummy_xxx_objects.py + short_names = {"torch": "pt"} + + # Locate actual dummy modules and read their content. + path = os.path.join(PATH_TO_TRANSFORMERS, "utils") + dummy_file_paths = { + backend: os.path.join(path, f"dummy_{short_names.get(backend, backend)}_objects.py") for backend in dummy_files + } + + actual_dummies = {} + for backend, file_path in dummy_file_paths.items(): + if os.path.isfile(file_path): + with open(file_path, "r", encoding="utf-8", newline="\n") as f: + actual_dummies[backend] = f.read() + else: + actual_dummies[backend] = "" + + # Compare actual with what they should be. + for backend in dummy_files: + if dummy_files[backend] != actual_dummies[backend]: + if overwrite: + print( + f"Updating transformers.utils.dummy_{short_names.get(backend, backend)}_objects.py as the main " + "__init__ has new objects." + ) + with open(dummy_file_paths[backend], "w", encoding="utf-8", newline="\n") as f: + f.write(dummy_files[backend]) + else: + # Temporary fix to help people identify which objects introduced are not correctly protected. + found = False + for _actual, _dummy in zip( + actual_dummies["torch"].split("class"), dummy_files["torch"].split("class") + ): + if _actual != _dummy: + actual_broken = _actual + dummy_broken = _dummy + found = True + break + + if not found: + print("A transient error was found with the dummies, please investigate.") + continue + + raise ValueError( + "The main __init__ has objects that are not present in " + f"transformers.utils.dummy_{short_names.get(backend, backend)}_objects.py.\n" + f" It is likely the following objects are responsible, see these excerpts: \n" + f"---------------------------------- Actual -------------------------------------\n" + f" \n {actual_broken} \n" + f"---------------------------------- Dummy -------------------------------------\n" + f" \n {dummy_broken} \n" + "Run `make fix-copies` to fix this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + args = parser.parse_args() + + check_dummies(args.fix_and_overwrite) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_inits.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_inits.py new file mode 100644 index 0000000000000000000000000000000000000000..bc211baa9edc0c21e4d389e6c130e85b3f44456d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_inits.py @@ -0,0 +1,355 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. +""" +Utility that checks the custom inits of Transformers are well-defined: Transformers uses init files that delay the +import of an object to when it's actually needed. This is to avoid the main init importing all models, which would +make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with +delayed imports have two halves: one defining a dictionary `_import_structure` which maps modules to the name of the +objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. The goal of this +script is to check the objects defined in both halves are the same. + +This also checks the main init properly references all submodules, even if it doesn't import anything from them: every +submodule should be defined as a key of `_import_structure`, with an empty list as value potentially, or the submodule +won't be importable. + +Use from the root of the repo with: + +```bash +python utils/check_inits.py +``` + +for a check that will error in case of inconsistencies (used by `make repo-consistency`). + +There is no auto-fix possible here sadly :-( +""" + +import collections +import os +import re +from pathlib import Path +from typing import Optional + + +# Path is set with the intent you should run this script from the root of the repo. +PATH_TO_TRANSFORMERS = "src/transformers" + + +# Matches is_xxx_available() +_re_backend = re.compile(r"is\_([a-z_]*)_available()") +# Catches a one-line _import_struct = {xxx} +_re_one_line_import_struct = re.compile(r"^_import_structure\s+=\s+\{([^\}]+)\}") +# Catches a line with a key-values pattern: "bla": ["foo", "bar"] +_re_import_struct_key_value = re.compile(r'\s+"\S*":\s+\[([^\]]*)\]') +# Catches a line if not is_foo_available +_re_test_backend = re.compile(r"^\s*if\s+not\s+is\_[a-z_]*\_available\(\)") +# Catches a line _import_struct["bla"].append("foo") +_re_import_struct_add_one = re.compile(r'^\s*_import_structure\["\S*"\]\.append\("(\S*)"\)') +# Catches a line _import_struct["bla"].extend(["foo", "bar"]) or _import_struct["bla"] = ["foo", "bar"] +_re_import_struct_add_many = re.compile(r"^\s*_import_structure\[\S*\](?:\.extend\(|\s*=\s+)\[([^\]]*)\]") +# Catches a line with an object between quotes and a comma: "MyModel", +_re_quote_object = re.compile(r'^\s+"([^"]+)",') +# Catches a line with objects between brackets only: ["foo", "bar"], +_re_between_brackets = re.compile(r"^\s+\[([^\]]+)\]") +# Catches a line with from foo import bar, bla, boo +_re_import = re.compile(r"\s+from\s+\S*\s+import\s+([^\(\s].*)\n") +# Catches a line with try: +_re_try = re.compile(r"^\s*try:") +# Catches a line with else: +_re_else = re.compile(r"^\s*else:") + + +def find_backend(line: str) -> Optional[str]: + """ + Find one (or multiple) backend in a code line of the init. + + Args: + line (`str`): A code line of the main init. + + Returns: + Optional[`str`]: If one (or several) backend is found, returns it. In the case of multiple backends (the line + contains `if is_xxx_available() and `is_yyy_available()`) returns all backends joined on `_and_` (so + `xxx_and_yyy` for instance). + """ + if _re_test_backend.search(line) is None: + return None + backends = [b[0] for b in _re_backend.findall(line)] + backends.sort() + return "_and_".join(backends) + + +def parse_init(init_file) -> Optional[tuple[dict[str, list[str]], dict[str, list[str]]]]: + """ + Read an init_file and parse (per backend) the `_import_structure` objects defined and the `TYPE_CHECKING` objects + defined. + + Args: + init_file (`str`): Path to the init file to inspect. + + Returns: + `Optional[Tuple[Dict[str, List[str]], Dict[str, List[str]]]]`: A tuple of two dictionaries mapping backends to list of + imported objects, one for the `_import_structure` part of the init and one for the `TYPE_CHECKING` part of the + init. Returns `None` if the init is not a custom init. + """ + with open(init_file, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + + # Get the to `_import_structure` definition. + line_index = 0 + while line_index < len(lines) and not lines[line_index].startswith("_import_structure = {"): + line_index += 1 + + # If this is a traditional init, just return. + if line_index >= len(lines): + return None + + # First grab the objects without a specific backend in _import_structure + objects = [] + while not lines[line_index].startswith("if TYPE_CHECKING") and find_backend(lines[line_index]) is None: + line = lines[line_index] + # If we have everything on a single line, let's deal with it. + if _re_one_line_import_struct.search(line): + content = _re_one_line_import_struct.search(line).groups()[0] + imports = re.findall(r"\[([^\]]+)\]", content) + for imp in imports: + objects.extend([obj[1:-1] for obj in imp.split(", ")]) + line_index += 1 + continue + single_line_import_search = _re_import_struct_key_value.search(line) + if single_line_import_search is not None: + imports = [obj[1:-1] for obj in single_line_import_search.groups()[0].split(", ") if len(obj) > 0] + objects.extend(imports) + elif line.startswith(" " * 8 + '"'): + objects.append(line[9:-3]) + line_index += 1 + + # Those are stored with the key "none". + import_dict_objects = {"none": objects} + + # Let's continue with backend-specific objects in _import_structure + while not lines[line_index].startswith("if TYPE_CHECKING"): + # If the line is an if not is_backend_available, we grab all objects associated. + backend = find_backend(lines[line_index]) + # Check if the backend declaration is inside a try block: + if _re_try.search(lines[line_index - 1]) is None: + backend = None + + if backend is not None: + line_index += 1 + + # Scroll until we hit the else block of try-except-else + while _re_else.search(lines[line_index]) is None: + line_index += 1 + + line_index += 1 + + objects = [] + # Until we unindent, add backend objects to the list + while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 4): + line = lines[line_index] + if _re_import_struct_add_one.search(line) is not None: + objects.append(_re_import_struct_add_one.search(line).groups()[0]) + elif _re_import_struct_add_many.search(line) is not None: + imports = _re_import_struct_add_many.search(line).groups()[0].split(", ") + imports = [obj[1:-1] for obj in imports if len(obj) > 0] + objects.extend(imports) + elif _re_between_brackets.search(line) is not None: + imports = _re_between_brackets.search(line).groups()[0].split(", ") + imports = [obj[1:-1] for obj in imports if len(obj) > 0] + objects.extend(imports) + elif _re_quote_object.search(line) is not None: + objects.append(_re_quote_object.search(line).groups()[0]) + elif line.startswith(" " * 8 + '"'): + objects.append(line[9:-3]) + elif line.startswith(" " * 12 + '"'): + objects.append(line[13:-3]) + line_index += 1 + + import_dict_objects[backend] = objects + else: + line_index += 1 + + # At this stage we are in the TYPE_CHECKING part, first grab the objects without a specific backend + objects = [] + while ( + line_index < len(lines) + and find_backend(lines[line_index]) is None + and not lines[line_index].startswith("else") + ): + line = lines[line_index] + single_line_import_search = _re_import.search(line) + if single_line_import_search is not None: + objects.extend(single_line_import_search.groups()[0].split(", ")) + elif line.startswith(" " * 8): + objects.append(line[8:-2]) + line_index += 1 + + type_hint_objects = {"none": objects} + + # Let's continue with backend-specific objects + while line_index < len(lines): + # If the line is an if is_backend_available, we grab all objects associated. + backend = find_backend(lines[line_index]) + # Check if the backend declaration is inside a try block: + if _re_try.search(lines[line_index - 1]) is None: + backend = None + + if backend is not None: + line_index += 1 + + # Scroll until we hit the else block of try-except-else + while _re_else.search(lines[line_index]) is None: + line_index += 1 + + line_index += 1 + + objects = [] + # Until we unindent, add backend objects to the list + while len(lines[line_index]) <= 1 or lines[line_index].startswith(" " * 8): + line = lines[line_index] + single_line_import_search = _re_import.search(line) + if single_line_import_search is not None: + objects.extend(single_line_import_search.groups()[0].split(", ")) + elif line.startswith(" " * 12): + objects.append(line[12:-2]) + line_index += 1 + + type_hint_objects[backend] = objects + else: + line_index += 1 + + return import_dict_objects, type_hint_objects + + +def analyze_results(import_dict_objects: dict[str, list[str]], type_hint_objects: dict[str, list[str]]) -> list[str]: + """ + Analyze the differences between _import_structure objects and TYPE_CHECKING objects found in an init. + + Args: + import_dict_objects (`Dict[str, List[str]]`): + A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to + list of imported objects. + type_hint_objects (`Dict[str, List[str]]`): + A dictionary mapping backend names (`"none"` for the objects independent of any specific backend) to + list of imported objects. + + Returns: + `List[str]`: The list of errors corresponding to mismatches. + """ + + def find_duplicates(seq): + return [k for k, v in collections.Counter(seq).items() if v > 1] + + # If one backend is missing from the other part of the init, error early. + if list(import_dict_objects.keys()) != list(type_hint_objects.keys()): + return ["Both sides of the init do not have the same backends!"] + + errors = [] + # Find all errors. + for key in import_dict_objects: + # Duplicate imports in any half. + duplicate_imports = find_duplicates(import_dict_objects[key]) + if duplicate_imports: + errors.append(f"Duplicate _import_structure definitions for: {duplicate_imports}") + duplicate_type_hints = find_duplicates(type_hint_objects[key]) + if duplicate_type_hints: + errors.append(f"Duplicate TYPE_CHECKING objects for: {duplicate_type_hints}") + + # Missing imports in either part of the init. + if sorted(set(import_dict_objects[key])) != sorted(set(type_hint_objects[key])): + name = "base imports" if key == "none" else f"{key} backend" + errors.append(f"Differences for {name}:") + for a in type_hint_objects[key]: + if a not in import_dict_objects[key]: + errors.append(f" {a} in TYPE_HINT but not in _import_structure.") + for a in import_dict_objects[key]: + if a not in type_hint_objects[key]: + errors.append(f" {a} in _import_structure but not in TYPE_HINT.") + return errors + + +def get_transformers_submodules() -> list[str]: + """ + Returns the list of Transformers submodules. + """ + submodules = [] + for path, directories, files in os.walk(PATH_TO_TRANSFORMERS): + for folder in directories: + # Ignore private modules + if folder.startswith("_"): + directories.remove(folder) + continue + # Ignore leftovers from branches (empty folders apart from pycache) + if len(list((Path(path) / folder).glob("*.py"))) == 0: + continue + short_path = str((Path(path) / folder).relative_to(PATH_TO_TRANSFORMERS)) + submodule = short_path.replace(os.path.sep, ".") + submodules.append(submodule) + for fname in files: + if fname == "__init__.py": + continue + short_path = str((Path(path) / fname).relative_to(PATH_TO_TRANSFORMERS)) + submodule = short_path.replace(".py", "").replace(os.path.sep, ".") + if len(submodule.split(".")) == 1: + submodules.append(submodule) + return submodules + + +IGNORE_SUBMODULES = [ + "convert_pytorch_checkpoint_to_tf2", + "modeling_flax_pytorch_utils", + "models.esm.openfold_utils", + "modeling_attn_mask_utils", + "safetensors_conversion", + "modeling_gguf_pytorch_utils", + "kernels.falcon_mamba", + "kernels", +] + + +def check_submodules(): + """ + Check all submodules of Transformers are properly registered in the main init. Error otherwise. + """ + # This is to make sure the transformers module imported is the one in the repo. + from transformers.utils import direct_transformers_import + + transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + + import_structure_keys = set(transformers._import_structure.keys()) + # This contains all the base keys of the _import_structure object defined in the init, but if the user is missing + # some optional dependencies, they may not have all of them. Thus we read the init to read all additions and + # (potentiall re-) add them. + with open(os.path.join(PATH_TO_TRANSFORMERS, "__init__.py"), "r") as f: + init_content = f.read() + import_structure_keys.update(set(re.findall(r"import_structure\[\"([^\"]*)\"\]", init_content))) + + module_not_registered = [ + module + for module in get_transformers_submodules() + if module not in IGNORE_SUBMODULES and module not in import_structure_keys + ] + + if len(module_not_registered) > 0: + list_of_modules = "\n".join(f"- {module}" for module in module_not_registered) + raise ValueError( + "The following submodules are not properly registered in the main init of Transformers:\n" + f"{list_of_modules}\n" + "Make sure they appear somewhere in the keys of `_import_structure` with an empty list as value." + ) + + +if __name__ == "__main__": + # This entire files needs an overhaul + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_model_tester.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_model_tester.py new file mode 100644 index 0000000000000000000000000000000000000000..8ace411b1a4e7db68fcc1a0ed874dfc3005721a1 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_model_tester.py @@ -0,0 +1,63 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. + + +import glob +import os + +from get_test_info import get_tester_classes + + +if __name__ == "__main__": + failures = [] + + pattern = os.path.join("tests", "models", "**", "test_modeling_*.py") + test_files = glob.glob(pattern) + # TODO: deal with TF/Flax too + test_files = [ + x for x in test_files if not (x.startswith("test_modeling_tf_") or x.startswith("test_modeling_flax_")) + ] + + for test_file in test_files: + tester_classes = get_tester_classes(test_file) + for tester_class in tester_classes: + # A few tester classes don't have `parent` parameter in `__init__`. + # TODO: deal this better + try: + tester = tester_class(parent=None) + except Exception: + continue + if hasattr(tester, "get_config"): + config = tester.get_config() + for k, v in config.to_dict().items(): + if isinstance(v, int): + target = None + if k in ["vocab_size"]: + target = 100 + elif k in ["max_position_embeddings"]: + target = 128 + elif k in ["hidden_size", "d_model"]: + target = 40 + elif k == ["num_layers", "num_hidden_layers", "num_encoder_layers", "num_decoder_layers"]: + target = 5 + if target is not None and v > target: + failures.append( + f"{tester_class.__name__} will produce a `config` of type `{config.__class__.__name__}`" + f' with config["{k}"] = {v} which is too large for testing! Set its value to be smaller' + f" than {target}." + ) + + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_modular_conversion.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_modular_conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..dad6b1f0a22c694cb0425fb0038378086cebc951 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_modular_conversion.py @@ -0,0 +1,232 @@ +import argparse +import difflib +import glob +import logging +import multiprocessing +import os +import shutil +import subprocess +from functools import partial +from io import StringIO + +from create_dependency_mapping import find_priority_list + +# Console for rich printing +from modular_model_converter import convert_modular_file +from rich.console import Console +from rich.syntax import Syntax + + +logging.basicConfig() +logging.getLogger().setLevel(logging.ERROR) +console = Console() + +BACKUP_EXT = ".modular_backup" + + +def process_file( + modular_file_path, + generated_modeling_content, + file_type="modeling_", + show_diff=True, +): + file_name_prefix = file_type.split("*")[0] + file_name_suffix = file_type.split("*")[-1] if "*" in file_type else "" + file_path = modular_file_path.replace("modular_", f"{file_name_prefix}_").replace(".py", f"{file_name_suffix}.py") + # Read the actual modeling file + with open(file_path, "r", encoding="utf-8") as modeling_file: + content = modeling_file.read() + output_buffer = StringIO(generated_modeling_content[file_type][0]) + output_buffer.seek(0) + output_content = output_buffer.read() + diff = difflib.unified_diff( + output_content.splitlines(), + content.splitlines(), + fromfile=f"{file_path}_generated", + tofile=f"{file_path}", + lineterm="", + ) + diff_list = list(diff) + # Check for differences + if diff_list: + # first save the copy of the original file, to be able to restore it later + if os.path.exists(file_path): + shutil.copy(file_path, file_path + BACKUP_EXT) + # we always save the generated content, to be able to update dependant files + with open(file_path, "w", encoding="utf-8", newline="\n") as modeling_file: + modeling_file.write(generated_modeling_content[file_type][0]) + console.print(f"[bold blue]Overwritten {file_path} with the generated content.[/bold blue]") + if show_diff: + console.print(f"\n[bold red]Differences found between the generated code and {file_path}:[/bold red]\n") + diff_text = "\n".join(diff_list) + syntax = Syntax(diff_text, "diff", theme="ansi_dark", line_numbers=True) + console.print(syntax) + return 1 + else: + console.print(f"[bold green]No differences found for {file_path}.[/bold green]") + return 0 + + +def compare_files(modular_file_path, show_diff=True): + # Generate the expected modeling content + generated_modeling_content = convert_modular_file(modular_file_path) + diff = 0 + for file_type in generated_modeling_content: + diff += process_file(modular_file_path, generated_modeling_content, file_type, show_diff) + return diff + + +def get_models_in_diff(): + """ + Finds all models that have been modified in the diff. + + Returns: + A set containing the names of the models that have been modified (e.g. {'llama', 'whisper'}). + """ + fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") + modified_files = ( + subprocess.check_output(f"git diff --diff-filter=d --name-only {fork_point_sha}".split()) + .decode("utf-8") + .split() + ) + + # Matches both modelling files and tests + relevant_modified_files = [x for x in modified_files if "/models/" in x and x.endswith(".py")] + model_names = set() + for file_path in relevant_modified_files: + model_name = file_path.split("/")[-2] + model_names.add(model_name) + return model_names + + +def guaranteed_no_diff(modular_file_path, dependencies, models_in_diff): + """ + Returns whether it is guaranteed to have no differences between the modular file and the modeling file. + + Model is in the diff -> not guaranteed to have no differences + Dependency is in the diff -> not guaranteed to have no differences + Otherwise -> guaranteed to have no differences + + Args: + modular_file_path: The path to the modular file. + dependencies: A dictionary containing the dependencies of each modular file. + models_in_diff: A set containing the names of the models that have been modified. + + Returns: + A boolean indicating whether the model (code and tests) is guaranteed to have no differences. + """ + model_name = modular_file_path.rsplit("modular_", 1)[1].replace(".py", "") + if model_name in models_in_diff: + return False + for dep in dependencies[modular_file_path]: + # two possible patterns: `transformers.models.model_name.(...)` or `model_name.(...)` + dependency_model_name = dep.split(".")[-2] + if dependency_model_name in models_in_diff: + return False + return True + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Compare modular_xxx.py files with modeling_xxx.py files.") + parser.add_argument( + "--files", default=["all"], type=str, nargs="+", help="List of modular_xxx.py files to compare." + ) + parser.add_argument( + "--fix_and_overwrite", action="store_true", help="Overwrite the modeling_xxx.py file if differences are found." + ) + parser.add_argument("--check_all", action="store_true", help="Check all files, not just the ones in the diff.") + parser.add_argument( + "--num_workers", + default=-1, + type=int, + help="The number of workers to run. Default is -1, which means the number of CPU cores.", + ) + args = parser.parse_args() + if args.files == ["all"]: + args.files = glob.glob("src/transformers/models/**/modular_*.py", recursive=True) + + if args.num_workers == -1: + args.num_workers = multiprocessing.cpu_count() + + # Assuming there is a topological sort on the dependency mapping: if the file being checked and its dependencies + # are not in the diff, then there it is guaranteed to have no differences. If no models are in the diff, then this + # script will do nothing. + current_branch = subprocess.check_output(["git", "branch", "--show-current"], text=True).strip() + if current_branch == "main": + console.print( + "[bold red]You are developing on the main branch. We cannot identify the list of changed files and will have to check all files. This may take a while.[/bold red]" + ) + models_in_diff = {file_path.split("/")[-2] for file_path in args.files} + else: + models_in_diff = get_models_in_diff() + if not models_in_diff and not args.check_all: + console.print( + "[bold green]No models files or model tests in the diff, skipping modular checks[/bold green]" + ) + exit(0) + + skipped_models = set() + non_matching_files = [] + ordered_files, dependencies = find_priority_list(args.files) + flat_ordered_files = [item for sublist in ordered_files for item in sublist] + + # ordered_files is a *sorted* list of lists of filepaths + # - files from the first list do NOT depend on other files + # - files in the second list depend on files from the first list + # - files in the third list depend on files from the second and (optionally) the first list + # - ... and so on + # files (models) within the same list are *independent* of each other; + # we start applying modular conversion to each list in parallel, starting from the first list + + console.print(f"[bold yellow]Number of dependency levels: {len(ordered_files)}[/bold yellow]") + console.print(f"[bold yellow]Files per level: {tuple([len(x) for x in ordered_files])}[/bold yellow]") + + try: + for dependency_level_files in ordered_files: + # Filter files guaranteed no diff + files_to_check = [] + for file_path in dependency_level_files: + if not args.check_all and guaranteed_no_diff(file_path, dependencies, models_in_diff): + skipped_models.add(file_path.split("/")[-2]) # save model folder name + else: + files_to_check.append(file_path) + + if not files_to_check: + continue + + # Process files with diff + num_workers = min(args.num_workers, len(files_to_check)) + with multiprocessing.Pool(num_workers) as p: + is_changed_flags = p.map( + partial(compare_files, show_diff=not args.fix_and_overwrite), + files_to_check, + ) + + # Collect changed files and their original paths + for is_changed, file_path in zip(is_changed_flags, files_to_check): + if is_changed: + non_matching_files.append(file_path) + + # Update changed models, after each round of conversions + # (save model folder name) + models_in_diff.add(file_path.split("/")[-2]) + + finally: + # Restore overwritten files by modular (if needed) + backup_files = glob.glob("**/*" + BACKUP_EXT, recursive=True) + for backup_file_path in backup_files: + overwritten_path = backup_file_path.replace(BACKUP_EXT, "") + if not args.fix_and_overwrite and os.path.exists(overwritten_path): + shutil.copy(backup_file_path, overwritten_path) + os.remove(backup_file_path) + + if non_matching_files and not args.fix_and_overwrite: + diff_models = set(file_path.split("/")[-2] for file_path in non_matching_files) # noqa + models_str = "\n - " + "\n - ".join(sorted(diff_models)) + raise ValueError(f"Some diff and their modeling code did not match. Models in diff:{models_str}") + + if skipped_models: + console.print( + f"[bold green]Skipped {len(skipped_models)} models and their dependencies that are not in the diff: " + f"{', '.join(sorted(skipped_models))}[/bold green]" + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_pipeline_typing.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_pipeline_typing.py new file mode 100644 index 0000000000000000000000000000000000000000..16dcf197a52e2256a25ee6c38a5372c6651d0011 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_pipeline_typing.py @@ -0,0 +1,93 @@ +import re + +from transformers.pipelines import SUPPORTED_TASKS, Pipeline + + +HEADER = """ +# fmt: off +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# The part of the file below was automatically generated from the code. +# Do NOT edit this part of the file manually as any edits will be overwritten by the generation +# of the file. If any change should be done, please apply the changes to the `pipeline` function +# below and run `python utils/check_pipeline_typing.py --fix_and_overwrite` to update the file. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 + +from typing import Literal, overload + + +""" + +FOOTER = """ +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# The part of the file above was automatically generated from the code. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# fmt: on +""" + +TASK_PATTERN = "task: Optional[str] = None" + + +def main(pipeline_file_path: str, fix_and_overwrite: bool = False): + with open(pipeline_file_path, "r") as file: + content = file.read() + + # extract generated code in between and + current_generated_code = re.search(r"# (.*)# ", content, re.DOTALL).group(1) + content_without_generated_code = content.replace(current_generated_code, "") + + # extract pipeline signature in between `def pipeline` and `-> Pipeline` + pipeline_signature = re.search(r"def pipeline(.*) -> Pipeline:", content_without_generated_code, re.DOTALL).group( + 1 + ) + pipeline_signature = pipeline_signature.replace("(\n ", "(") # start of the signature + pipeline_signature = pipeline_signature.replace(",\n ", ", ") # intermediate arguments + pipeline_signature = pipeline_signature.replace(",\n)", ")") # end of the signature + + # collect and sort available pipelines + pipelines = [(f'"{task}"', task_info["impl"]) for task, task_info in SUPPORTED_TASKS.items()] + pipelines = sorted(pipelines, key=lambda x: x[0]) + pipelines.insert(0, (None, Pipeline)) + + # generate new `pipeline` signatures + new_generated_code = "" + for task, pipeline_class in pipelines: + if TASK_PATTERN not in pipeline_signature: + raise ValueError(f"Can't find `{TASK_PATTERN}` in pipeline signature: {pipeline_signature}") + pipeline_type = pipeline_class if isinstance(pipeline_class, str) else pipeline_class.__name__ + new_pipeline_signature = pipeline_signature.replace(TASK_PATTERN, f"task: Literal[{task}]") + new_generated_code += f"@overload\ndef pipeline{new_pipeline_signature} -> {pipeline_type}: ...\n" + + new_generated_code = HEADER + new_generated_code + FOOTER + new_generated_code = new_generated_code.rstrip("\n") + "\n" + + if new_generated_code != current_generated_code and fix_and_overwrite: + print(f"Updating {pipeline_file_path}...") + wrapped_current_generated_code = "# " + current_generated_code + "# " + wrapped_new_generated_code = "# " + new_generated_code + "# " + content = content.replace(wrapped_current_generated_code, wrapped_new_generated_code) + + # write content to file + with open(pipeline_file_path, "w") as file: + file.write(content) + + elif new_generated_code != current_generated_code and not fix_and_overwrite: + message = ( + f"Found inconsistencies in {pipeline_file_path}. " + "Run `python utils/check_pipeline_typing.py --fix_and_overwrite` to fix them." + ) + raise ValueError(message) + + +if __name__ == "__main__": + import argparse + + parser = argparse.ArgumentParser() + parser.add_argument("--fix_and_overwrite", action="store_true", help="Whether to fix inconsistencies.") + parser.add_argument( + "--pipeline_file_path", + type=str, + default="src/transformers/pipelines/__init__.py", + help="Path to the pipeline file.", + ) + args = parser.parse_args() + main(args.pipeline_file_path, args.fix_and_overwrite) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_repo.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_repo.py new file mode 100644 index 0000000000000000000000000000000000000000..3d15c6aa23a1a97d89f63ae0ca9f25243d630c61 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_repo.py @@ -0,0 +1,1287 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. +""" +Utility that performs several consistency checks on the repo. This includes: +- checking all models are properly defined in the __init__ of models/ +- checking all models are in the main __init__ +- checking all models are properly tested +- checking all object in the main __init__ are documented +- checking all models are in at least one auto class +- checking all the auto mapping are properly defined (no typos, importable) +- checking the list of deprecated models is up to date + +Use from the root of the repo with (as used in `make repo-consistency`): + +```bash +python utils/check_repo.py +``` + +It has no auto-fix mode. +""" + +import os +import re +import sys +import types +import warnings +from collections import OrderedDict +from difflib import get_close_matches +from importlib.machinery import ModuleSpec +from pathlib import Path + +from transformers import is_flax_available, is_tf_available, is_torch_available +from transformers.models.auto.auto_factory import get_values +from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES +from transformers.models.auto.feature_extraction_auto import FEATURE_EXTRACTOR_MAPPING_NAMES +from transformers.models.auto.image_processing_auto import IMAGE_PROCESSOR_MAPPING_NAMES +from transformers.models.auto.processing_auto import PROCESSOR_MAPPING_NAMES +from transformers.models.auto.tokenization_auto import TOKENIZER_MAPPING_NAMES +from transformers.utils import ENV_VARS_TRUE_VALUES, direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_repo.py +PATH_TO_TRANSFORMERS = "src/transformers" +PATH_TO_TESTS = "tests" +PATH_TO_DOC = "docs/source/en" + +# Update this list with models that are supposed to be private. +PRIVATE_MODELS = [ + "AltRobertaModel", + "DPRSpanPredictor", + "UdopStack", + "LongT5Stack", + "RealmBertModel", + "T5Stack", + "MT5Stack", + "UMT5Stack", + "Pop2PianoStack", + "Qwen2AudioEncoder", + "Qwen2VisionTransformerPretrainedModel", + "Qwen2_5_VisionTransformerPretrainedModel", + "SwitchTransformersStack", + "TFDPRSpanPredictor", + "MaskFormerSwinModel", + "MaskFormerSwinPreTrainedModel", + "BridgeTowerTextModel", + "BridgeTowerVisionModel", + "Kosmos2TextModel", + "Kosmos2TextForCausalLM", + "Kosmos2VisionModel", + "SeamlessM4Tv2TextToUnitModel", + "SeamlessM4Tv2CodeHifiGan", + "SeamlessM4Tv2TextToUnitForConditionalGeneration", + "Idefics2PerceiverResampler", + "Idefics2VisionTransformer", + "Idefics3VisionTransformer", + "Kosmos2_5TextModel", + "Kosmos2_5TextForCausalLM", + "Kosmos2_5VisionModel", + "SmolVLMVisionTransformer", + "AriaTextForCausalLM", + "AriaTextModel", + "Phi4MultimodalAudioModel", + "Phi4MultimodalVisionModel", + "Glm4vVisionModel", + "Glm4vMoeVisionModel", + "EvollaSaProtPreTrainedModel", + "Ovis2VisionModel", +] + +# Update this list for models that are not tested with a comment explaining the reason it should not be. +# Being in this list is an exception and should **not** be the rule. +IGNORE_NON_TESTED = ( + PRIVATE_MODELS.copy() + + [ + # models to ignore for not tested + "RecurrentGemmaModel", # Building part of bigger (tested) model. + "FuyuForCausalLM", # Not tested fort now + "InstructBlipQFormerModel", # Building part of bigger (tested) model. + "InstructBlipVideoQFormerModel", # Building part of bigger (tested) model. + "UMT5EncoderModel", # Building part of bigger (tested) model. + "Blip2QFormerModel", # Building part of bigger (tested) model. + "ErnieMForInformationExtraction", + "FastSpeech2ConformerHifiGan", # Already tested by SpeechT5HifiGan (# Copied from) + "FastSpeech2ConformerWithHifiGan", # Built with two smaller (tested) models. + "GraphormerDecoderHead", # Building part of bigger (tested) model. + "JukeboxVQVAE", # Building part of bigger (tested) model. + "JukeboxPrior", # Building part of bigger (tested) model. + "DecisionTransformerGPT2Model", # Building part of bigger (tested) model. + "SegformerDecodeHead", # Building part of bigger (tested) model. + "MgpstrModel", # Building part of bigger (tested) model. + "BertLMHeadModel", # Needs to be setup as decoder. + "MegatronBertLMHeadModel", # Building part of bigger (tested) model. + "RealmBertModel", # Building part of bigger (tested) model. + "RealmReader", # Not regular model. + "RealmScorer", # Not regular model. + "RealmForOpenQA", # Not regular model. + "ReformerForMaskedLM", # Needs to be setup as decoder. + "TFElectraMainLayer", # Building part of bigger (tested) model (should it be a TFPreTrainedModel ?) + "TFRobertaForMultipleChoice", # TODO: fix + "TFRobertaPreLayerNormForMultipleChoice", # TODO: fix + "SeparableConv1D", # Building part of bigger (tested) model. + "FlaxBartForCausalLM", # Building part of bigger (tested) model. + "FlaxBertForCausalLM", # Building part of bigger (tested) model. Tested implicitly through FlaxRobertaForCausalLM. + "OPTDecoderWrapper", + "TFSegformerDecodeHead", # Not a regular model. + "AltRobertaModel", # Building part of bigger (tested) model. + "BlipTextLMHeadModel", # No need to test it as it is tested by BlipTextVision models + "TFBlipTextLMHeadModel", # No need to test it as it is tested by BlipTextVision models + "BridgeTowerTextModel", # No need to test it as it is tested by BridgeTowerModel model. + "BridgeTowerVisionModel", # No need to test it as it is tested by BridgeTowerModel model. + "BarkCausalModel", # Building part of bigger (tested) model. + "BarkModel", # Does not have a forward signature - generation tested with integration tests. + "Sam2HieraDetModel", # Building part of bigger (tested) model. + "Sam2VideoModel", # inherit from Sam2Model (tested). + "SeamlessM4TTextToUnitModel", # Building part of bigger (tested) model. + "SeamlessM4TCodeHifiGan", # Building part of bigger (tested) model. + "SeamlessM4TTextToUnitForConditionalGeneration", # Building part of bigger (tested) model. + "ChameleonVQVAE", # VQVAE here is used only for encoding (discretizing) and is tested as part of bigger model + "Qwen2VLModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2VLForConditionalGeneration. + "Qwen2_5_VLModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5_VLForConditionalGeneration. + "Qwen2_5OmniForConditionalGeneration", # Not a regular model. Testted in Qwen2_5OmniModelIntergrationTest + "Qwen2_5OmniTalkerForConditionalGeneration", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5OmniModelIntergrationTest. + "Qwen2_5OmniTalkerModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5OmniModelIntergrationTest. + "Qwen2_5OmniThinkerTextModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5OmniModelIntergrationTest. + "Qwen2_5OmniToken2WavModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5OmniModelIntergrationTest. + "Qwen2_5OmniToken2WavDiTModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5OmniModelIntergrationTest. + "Qwen2_5OmniToken2WavBigVGANModel", # Building part of bigger (tested) model. Tested implicitly through Qwen2_5OmniModelIntergrationTest. + "MllamaTextModel", # Building part of bigger (tested) model. # TODO: add tests + "MllamaVisionModel", # Building part of bigger (tested) model. # TODO: add tests + "Llama4TextModel", # Building part of bigger (tested) model. # TODO: add tests + "Llama4VisionModel", # Building part of bigger (tested) model. # TODO: add tests + "Emu3VQVAE", # Building part of bigger (tested) model + "Emu3TextModel", # Building part of bigger (tested) model + "Glm4vTextModel", # Building part of bigger (tested) model + "Glm4vMoeTextModel", # Building part of bigger (tested) model + "Qwen2VLTextModel", # Building part of bigger (tested) model + "Qwen2_5_VLTextModel", # Building part of bigger (tested) model + "InternVLVisionModel", # Building part of bigger (tested) model + "JanusVisionModel", # Building part of bigger (tested) model + "TimesFmModel", # Building part of bigger (tested) model + "CsmDepthDecoderForCausalLM", # Building part of bigger (tested) model. Tested implicitly through CsmForConditionalGenerationIntegrationTest. + "CsmDepthDecoderModel", # Building part of bigger (tested) model. Tested implicitly through CsmForConditionalGenerationIntegrationTest. + "CsmBackboneModel", # Building part of bigger (tested) model. Tested implicitly through CsmForConditionalGenerationIntegrationTest. + ] +) + +# Update this list with test files that don't have a tester with a `all_model_classes` variable and which don't +# trigger the common tests. +TEST_FILES_WITH_NO_COMMON_TESTS = [ + "models/decision_transformer/test_modeling_decision_transformer.py", + "models/camembert/test_modeling_camembert.py", + "models/mt5/test_modeling_flax_mt5.py", + "models/mbart/test_modeling_mbart.py", + "models/mt5/test_modeling_mt5.py", + "models/pegasus/test_modeling_pegasus.py", + "models/camembert/test_modeling_tf_camembert.py", + "models/mt5/test_modeling_tf_mt5.py", + "models/xlm_roberta/test_modeling_tf_xlm_roberta.py", + "models/xlm_roberta/test_modeling_flax_xlm_roberta.py", + "models/xlm_prophetnet/test_modeling_xlm_prophetnet.py", + "models/xlm_roberta/test_modeling_xlm_roberta.py", + "models/vision_text_dual_encoder/test_modeling_vision_text_dual_encoder.py", + "models/vision_text_dual_encoder/test_modeling_tf_vision_text_dual_encoder.py", + "models/vision_text_dual_encoder/test_modeling_flax_vision_text_dual_encoder.py", + "models/decision_transformer/test_modeling_decision_transformer.py", + "models/bark/test_modeling_bark.py", + "models/shieldgemma2/test_modeling_shieldgemma2.py", + "models/llama4/test_modeling_llama4.py", + "models/sam2_video/test_modeling_sam2_video.py", +] + +# Update this list for models that are not in any of the auto MODEL_XXX_MAPPING. Being in this list is an exception and +# should **not** be the rule. +IGNORE_NON_AUTO_CONFIGURED = PRIVATE_MODELS.copy() + [ + # models to ignore for model xxx mapping + "Aimv2TextModel", + "AlignTextModel", + "AlignVisionModel", + "ClapTextModel", + "ClapTextModelWithProjection", + "ClapAudioModel", + "ClapAudioModelWithProjection", + "Blip2TextModelWithProjection", + "Blip2VisionModelWithProjection", + "Blip2VisionModel", + "ErnieMForInformationExtraction", + "FastSpeech2ConformerHifiGan", + "FastSpeech2ConformerWithHifiGan", + "GitVisionModel", + "GraphormerModel", + "GraphormerForGraphClassification", + "BlipForImageTextRetrieval", + "BlipForQuestionAnswering", + "BlipVisionModel", + "BlipTextLMHeadModel", + "BlipTextModel", + "BrosSpadeEEForTokenClassification", + "BrosSpadeELForTokenClassification", + "TFBlipForConditionalGeneration", + "TFBlipForImageTextRetrieval", + "TFBlipForQuestionAnswering", + "TFBlipVisionModel", + "TFBlipTextLMHeadModel", + "TFBlipTextModel", + "Swin2SRForImageSuperResolution", + "BridgeTowerForImageAndTextRetrieval", + "BridgeTowerForMaskedLM", + "BridgeTowerForContrastiveLearning", + "CLIPSegForImageSegmentation", + "CLIPSegVisionModel", + "CLIPSegTextModel", + "EsmForProteinFolding", + "GPTSanJapaneseModel", + "TimeSeriesTransformerForPrediction", + "InformerForPrediction", + "AutoformerForPrediction", + "PatchTSTForPretraining", + "PatchTSTForPrediction", + "JukeboxVQVAE", + "JukeboxPrior", + "SamModel", + "Sam2Model", + "Sam2VideoModel", + "SamHQModel", + "DPTForDepthEstimation", + "DecisionTransformerGPT2Model", + "GLPNForDepthEstimation", + "ViltForImagesAndTextClassification", + "ViltForImageAndTextRetrieval", + "ViltForTokenClassification", + "ViltForMaskedLM", + "PerceiverForMultimodalAutoencoding", + "PerceiverForOpticalFlow", + "SegformerDecodeHead", + "TFSegformerDecodeHead", + "FlaxBeitForMaskedImageModeling", + "BeitForMaskedImageModeling", + "ChineseCLIPTextModel", + "ChineseCLIPVisionModel", + "CLIPTextModelWithProjection", + "CLIPVisionModelWithProjection", + "ClvpForCausalLM", + "ClvpModel", + "GroupViTTextModel", + "GroupViTVisionModel", + "TFCLIPTextModel", + "TFCLIPVisionModel", + "TFGroupViTTextModel", + "TFGroupViTVisionModel", + "FlaxCLIPTextModel", + "FlaxCLIPTextModelWithProjection", + "FlaxCLIPVisionModel", + "FlaxWav2Vec2ForCTC", + "DetrForSegmentation", + "Pix2StructVisionModel", + "Pix2StructTextModel", + "ConditionalDetrForSegmentation", + "DPRReader", + "FlaubertForQuestionAnswering", + "FlavaImageCodebook", + "FlavaTextModel", + "FlavaImageModel", + "FlavaMultimodalModel", + "GPT2DoubleHeadsModel", + "GPTSw3DoubleHeadsModel", + "InstructBlipVisionModel", + "InstructBlipQFormerModel", + "InstructBlipVideoVisionModel", + "InstructBlipVideoQFormerModel", + "LayoutLMForQuestionAnswering", + "LukeForMaskedLM", + "LukeForEntityClassification", + "LukeForEntityPairClassification", + "LukeForEntitySpanClassification", + "MgpstrModel", + "OpenAIGPTDoubleHeadsModel", + "OwlViTTextModel", + "OwlViTVisionModel", + "Owlv2TextModel", + "Owlv2VisionModel", + "OwlViTForObjectDetection", + "PatchTSMixerForPrediction", + "PatchTSMixerForPretraining", + "RagModel", + "RagSequenceForGeneration", + "RagTokenForGeneration", + "RealmEmbedder", + "RealmForOpenQA", + "RealmScorer", + "RealmReader", + "TFDPRReader", + "TFGPT2DoubleHeadsModel", + "TFLayoutLMForQuestionAnswering", + "TFOpenAIGPTDoubleHeadsModel", + "TFRagModel", + "TFRagSequenceForGeneration", + "TFRagTokenForGeneration", + "Wav2Vec2ForCTC", + "HubertForCTC", + "SEWForCTC", + "SEWDForCTC", + "XLMForQuestionAnswering", + "XLNetForQuestionAnswering", + "SeparableConv1D", + "VisualBertForRegionToPhraseAlignment", + "VisualBertForVisualReasoning", + "VisualBertForQuestionAnswering", + "VisualBertForMultipleChoice", + "TFWav2Vec2ForCTC", + "TFHubertForCTC", + "XCLIPVisionModel", + "XCLIPTextModel", + "AltCLIPTextModel", + "AltCLIPVisionModel", + "AltRobertaModel", + "TvltForAudioVisualClassification", + "BarkCausalModel", + "BarkCoarseModel", + "BarkFineModel", + "BarkSemanticModel", + "MusicgenMelodyModel", + "MusicgenModel", + "MusicgenForConditionalGeneration", + "SpeechT5ForSpeechToSpeech", + "SpeechT5ForTextToSpeech", + "SpeechT5HifiGan", + "VitMatteForImageMatting", + "SeamlessM4TTextToUnitModel", + "SeamlessM4TTextToUnitForConditionalGeneration", + "SeamlessM4TCodeHifiGan", + "SeamlessM4TForSpeechToSpeech", # no auto class for speech-to-speech + "TvpForVideoGrounding", + "SeamlessM4Tv2NARTextToUnitModel", + "SeamlessM4Tv2NARTextToUnitForConditionalGeneration", + "SeamlessM4Tv2CodeHifiGan", + "SeamlessM4Tv2ForSpeechToSpeech", # no auto class for speech-to-speech + "SegGptForImageSegmentation", + "SiglipVisionModel", + "SiglipTextModel", + "Siglip2VisionModel", + "Siglip2TextModel", + "ChameleonVQVAE", # no autoclass for VQ-VAE models + "VitPoseForPoseEstimation", + "CLIPTextModel", + "MoshiForConditionalGeneration", # no auto class for speech-to-speech + "Emu3VQVAE", # no autoclass for VQ-VAE models + "Emu3TextModel", # Building part of bigger (tested) model + "JanusVQVAE", # no autoclass for VQ-VAE models + "JanusVisionModel", # Building part of bigger (tested) model + "Qwen2_5OmniTalkerForConditionalGeneration", # Building part of a bigger model + "Qwen2_5OmniTalkerModel", # Building part of a bigger model + "Qwen2_5OmniThinkerForConditionalGeneration", # Building part of a bigger model + "Qwen2_5OmniThinkerTextModel", # Building part of a bigger model + "Qwen2_5OmniToken2WavModel", # Building part of a bigger model + "Qwen2_5OmniToken2WavBigVGANModel", # Building part of a bigger model + "Qwen2_5OmniToken2WavDiTModel", # Building part of a bigger model + "CsmBackboneModel", # Building part of a bigger model + "CsmDepthDecoderModel", # Building part of a bigger model + "CsmDepthDecoderForCausalLM", # Building part of a bigger model + "CsmForConditionalGeneration", # Building part of a bigger model +] + +# DO NOT edit this list! +# (The corresponding pytorch objects should never have been in the main `__init__`, but it's too late to remove) +OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK = [ + "FlaxBertLayer", + "FlaxBigBirdLayer", + "FlaxRoFormerLayer", + "TFBertLayer", + "TFLxmertEncoder", + "TFLxmertXLayer", + "TFMPNetLayer", + "TFMobileBertLayer", + "TFSegformerLayer", + "TFViTMAELayer", +] + +# Update this list for models that have multiple model types for the same model doc. +MODEL_TYPE_TO_DOC_MAPPING = OrderedDict( + [ + ("data2vec-text", "data2vec"), + ("data2vec-audio", "data2vec"), + ("data2vec-vision", "data2vec"), + ("donut-swin", "donut"), + ("kosmos-2.5", "kosmos2_5"), + ("dinov3_convnext", "dinov3"), + ("dinov3_vit", "dinov3"), + ] +) + + +# This is to make sure the transformers module imported is the one in the repo. +transformers = direct_transformers_import(PATH_TO_TRANSFORMERS) + + +def check_missing_backends(): + """ + Checks if all backends are installed (otherwise the check of this script is incomplete). Will error in the CI if + that's not the case but only throw a warning for users running this. + """ + missing_backends = [] + if not is_torch_available(): + missing_backends.append("PyTorch") + if not is_tf_available(): + missing_backends.append("TensorFlow") + if not is_flax_available(): + missing_backends.append("Flax") + if len(missing_backends) > 0: + missing = ", ".join(missing_backends) + if os.getenv("TRANSFORMERS_IS_CI", "").upper() in ENV_VARS_TRUE_VALUES: + raise Exception( + "Full repo consistency checks require all backends to be installed (with `pip install -e '.[dev]'` in the " + f"Transformers repo, the following are missing: {missing}." + ) + else: + warnings.warn( + "Full repo consistency checks require all backends to be installed (with `pip install -e '.[dev]'` in the " + f"Transformers repo, the following are missing: {missing}. While it's probably fine as long as you " + "didn't make any change in one of those backends modeling files, you should probably execute the " + "command above to be on the safe side." + ) + + +def check_model_list(): + """ + Checks the model listed as subfolders of `models` match the models available in `transformers.models`. + """ + # Get the models from the directory structure of `src/transformers/models/` + import transformers as tfrs + + models_dir = os.path.join(PATH_TO_TRANSFORMERS, "models") + _models = [] + for model in os.listdir(models_dir): + if model == "deprecated": + continue + model_dir = os.path.join(models_dir, model) + if os.path.isdir(model_dir) and "__init__.py" in os.listdir(model_dir): + # If the init is empty, and there are only two files, it's likely that there's just a conversion + # script. Those should not be in the init. + if (Path(model_dir) / "__init__.py").read_text().strip() == "": + continue + + _models.append(model) + + # Get the models in the submodule `transformers.models` + models = [model for model in dir(tfrs.models) if not model.startswith("__")] + + missing_models = sorted(set(_models).difference(models)) + if missing_models: + raise Exception( + f"The following models should be included in {models_dir}/__init__.py: {','.join(missing_models)}." + ) + + +# If some modeling modules should be ignored for all checks, they should be added in the nested list +# _ignore_modules of this function. +def get_model_modules() -> list[str]: + """Get all the model modules inside the transformers library (except deprecated models).""" + _ignore_modules = [ + "modeling_auto", + "modeling_encoder_decoder", + "modeling_marian", + "modeling_retribert", + "modeling_flax_auto", + "modeling_flax_encoder_decoder", + "modeling_speech_encoder_decoder", + "modeling_flax_speech_encoder_decoder", + "modeling_flax_vision_encoder_decoder", + "modeling_timm_backbone", + "modeling_tf_auto", + "modeling_tf_encoder_decoder", + "modeling_tf_vision_encoder_decoder", + "modeling_vision_encoder_decoder", + ] + modules = [] + for model in dir(transformers.models): + # There are some magic dunder attributes in the dir, we ignore them + if "deprecated" in model or model.startswith("__"): + continue + + model_module = getattr(transformers.models, model) + for submodule in dir(model_module): + if submodule.startswith("modeling") and submodule not in _ignore_modules: + modeling_module = getattr(model_module, submodule) + modules.append(modeling_module) + return modules + + +def get_models(module: types.ModuleType, include_pretrained: bool = False) -> list[tuple[str, type]]: + """ + Get the objects in a module that are models. + + Args: + module (`types.ModuleType`): + The module from which we are extracting models. + include_pretrained (`bool`, *optional*, defaults to `False`): + Whether or not to include the `PreTrainedModel` subclass (like `BertPreTrainedModel`) or not. + + Returns: + List[Tuple[str, type]]: List of models as tuples (class name, actual class). + """ + models = [] + model_classes = (transformers.PreTrainedModel, transformers.TFPreTrainedModel, transformers.FlaxPreTrainedModel) + for attr_name in dir(module): + if not include_pretrained and ("Pretrained" in attr_name or "PreTrained" in attr_name): + continue + attr = getattr(module, attr_name) + if isinstance(attr, type) and issubclass(attr, model_classes) and attr.__module__ == module.__name__: + models.append((attr_name, attr)) + return models + + +def is_building_block(model: str) -> bool: + """ + Returns `True` if a model is a building block part of a bigger model. + """ + if model.endswith("Wrapper"): + return True + if model.endswith("Encoder"): + return True + if model.endswith("Decoder"): + return True + if model.endswith("Prenet"): + return True + + +def is_a_private_model(model: str) -> bool: + """Returns `True` if the model should not be in the main init.""" + if model in PRIVATE_MODELS: + return True + return is_building_block(model) + + +def check_models_are_in_init(): + """Checks all models defined in the library are in the main init.""" + models_not_in_init = [] + dir_transformers = dir(transformers) + for module in get_model_modules(): + models_not_in_init += [ + model[0] for model in get_models(module, include_pretrained=True) if model[0] not in dir_transformers + ] + + # Remove private models + models_not_in_init = [model for model in models_not_in_init if not is_a_private_model(model)] + if len(models_not_in_init) > 0: + raise Exception(f"The following models should be in the main init: {','.join(models_not_in_init)}.") + + +# If some test_modeling files should be ignored when checking models are all tested, they should be added in the +# nested list _ignore_files of this function. +def get_model_test_files() -> list[str]: + """ + Get the model test files. + + Returns: + `List[str]`: The list of test files. The returned files will NOT contain the `tests` (i.e. `PATH_TO_TESTS` + defined in this script). They will be considered as paths relative to `tests`. A caller has to use + `os.path.join(PATH_TO_TESTS, ...)` to access the files. + """ + + _ignore_files = [ + "test_modeling_common", + "test_modeling_encoder_decoder", + "test_modeling_flax_encoder_decoder", + "test_modeling_flax_speech_encoder_decoder", + "test_modeling_marian", + "test_modeling_tf_common", + "test_modeling_tf_encoder_decoder", + ] + test_files = [] + model_test_root = os.path.join(PATH_TO_TESTS, "models") + model_test_dirs = [] + for x in os.listdir(model_test_root): + x = os.path.join(model_test_root, x) + if os.path.isdir(x): + model_test_dirs.append(x) + + for target_dir in [PATH_TO_TESTS] + model_test_dirs: + for file_or_dir in os.listdir(target_dir): + path = os.path.join(target_dir, file_or_dir) + if os.path.isfile(path): + filename = os.path.split(path)[-1] + if "test_modeling" in filename and os.path.splitext(filename)[0] not in _ignore_files: + file = os.path.join(*path.split(os.sep)[1:]) + test_files.append(file) + + return test_files + + +# This is a bit hacky but I didn't find a way to import the test_file as a module and read inside the tester class +# for the all_model_classes variable. +def find_tested_models(test_file: str) -> list[str]: + """ + Parse the content of test_file to detect what's in `all_model_classes`. This detects the models that inherit from + the common test class. + + Args: + test_file (`str`): The path to the test file to check + + Returns: + `List[str]`: The list of models tested in that file. + """ + with open(os.path.join(PATH_TO_TESTS, test_file), "r", encoding="utf-8", newline="\n") as f: + content = f.read() + all_models = re.findall(r"all_model_classes\s+=\s+\(\s*\(([^\)]*)\)", content) + # Check with one less parenthesis as well + all_models += re.findall(r"all_model_classes\s+=\s+\(([^\)]*)\)", content) + if len(all_models) > 0: + model_tested = [] + for entry in all_models: + for line in entry.split(","): + name = line.strip() + if len(name) > 0: + model_tested.append(name) + return model_tested + + +def should_be_tested(model_name: str) -> bool: + """ + Whether or not a model should be tested. + """ + if model_name in IGNORE_NON_TESTED: + return False + return not is_building_block(model_name) + + +def check_models_are_tested(module: types.ModuleType, test_file: str) -> list[str]: + """Check models defined in a module are all tested in a given file. + + Args: + module (`types.ModuleType`): The module in which we get the models. + test_file (`str`): The path to the file where the module is tested. + + Returns: + `List[str]`: The list of error messages corresponding to models not tested. + """ + # XxxPreTrainedModel are not tested + defined_models = get_models(module) + tested_models = find_tested_models(test_file) + if tested_models is None: + if test_file.replace(os.path.sep, "/") in TEST_FILES_WITH_NO_COMMON_TESTS: + return + return [ + f"{test_file} should define `all_model_classes` to apply common tests to the models it tests. " + + "If this intentional, add the test filename to `TEST_FILES_WITH_NO_COMMON_TESTS` in the file " + + "`utils/check_repo.py`." + ] + failures = [] + for model_name, _ in defined_models: + if model_name not in tested_models and should_be_tested(model_name): + failures.append( + f"{model_name} is defined in {module.__name__} but is not tested in " + + f"{os.path.join(PATH_TO_TESTS, test_file)}. Add it to the all_model_classes in that file." + + "If common tests should not applied to that model, add its name to `IGNORE_NON_TESTED`" + + "in the file `utils/check_repo.py`." + ) + return failures + + +def check_all_models_are_tested(): + """Check all models are properly tested.""" + modules = get_model_modules() + test_files = get_model_test_files() + failures = [] + for module in modules: + # Matches a module to its test file. + test_file = [file for file in test_files if f"test_{module.__name__.split('.')[-1]}.py" in file] + if len(test_file) == 0: + # We do not test TF or Flax models anymore because they're deprecated. + if not ("modeling_tf" in module.__name__ or "modeling_flax" in module.__name__): + failures.append(f"{module.__name__} does not have its corresponding test file {test_file}.") + elif len(test_file) > 1: + failures.append(f"{module.__name__} has several test files: {test_file}.") + else: + test_file = test_file[0] + new_failures = check_models_are_tested(module, test_file) + if new_failures is not None: + failures += new_failures + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def get_all_auto_configured_models() -> list[str]: + """Return the list of all models in at least one auto class.""" + result = set() # To avoid duplicates we concatenate all model classes in a set. + if is_torch_available(): + for attr_name in dir(transformers.models.auto.modeling_auto): + if attr_name.startswith("MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_auto, attr_name))) + if is_tf_available(): + for attr_name in dir(transformers.models.auto.modeling_tf_auto): + if attr_name.startswith("TF_MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_tf_auto, attr_name))) + if is_flax_available(): + for attr_name in dir(transformers.models.auto.modeling_flax_auto): + if attr_name.startswith("FLAX_MODEL_") and attr_name.endswith("MAPPING_NAMES"): + result = result | set(get_values(getattr(transformers.models.auto.modeling_flax_auto, attr_name))) + return list(result) + + +def ignore_unautoclassed(model_name: str) -> bool: + """Rules to determine if a model should be in an auto class.""" + # Special white list + if model_name in IGNORE_NON_AUTO_CONFIGURED: + return True + # Encoder and Decoder should be ignored + if "Encoder" in model_name or "Decoder" in model_name: + return True + return False + + +def check_models_are_auto_configured(module: types.ModuleType, all_auto_models: list[str]) -> list[str]: + """ + Check models defined in module are each in an auto class. + + Args: + module (`types.ModuleType`): + The module in which we get the models. + all_auto_models (`List[str]`): + The list of all models in an auto class (as obtained with `get_all_auto_configured_models()`). + + Returns: + `List[str]`: The list of error messages corresponding to models not tested. + """ + defined_models = get_models(module) + failures = [] + for model_name, _ in defined_models: + if model_name not in all_auto_models and not ignore_unautoclassed(model_name): + failures.append( + f"{model_name} is defined in {module.__name__} but is not present in any of the auto mapping. " + "If that is intended behavior, add its name to `IGNORE_NON_AUTO_CONFIGURED` in the file " + "`utils/check_repo.py`." + ) + return failures + + +def check_all_models_are_auto_configured(): + """Check all models are each in an auto class.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + modules = get_model_modules() + all_auto_models = get_all_auto_configured_models() + failures = [] + for module in modules: + new_failures = check_models_are_auto_configured(module, all_auto_models) + if new_failures is not None: + failures += new_failures + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_object_names_being_defined(): + """Check all names defined in auto (name) mappings exist in the library.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + mappings_to_check = { + "TOKENIZER_MAPPING_NAMES": TOKENIZER_MAPPING_NAMES, + "IMAGE_PROCESSOR_MAPPING_NAMES": IMAGE_PROCESSOR_MAPPING_NAMES, + "FEATURE_EXTRACTOR_MAPPING_NAMES": FEATURE_EXTRACTOR_MAPPING_NAMES, + "PROCESSOR_MAPPING_NAMES": PROCESSOR_MAPPING_NAMES, + } + + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name, mapping in mappings_to_check.items(): + for class_names in mapping.values(): + if not isinstance(class_names, tuple): + class_names = (class_names,) + for class_name in class_names: + if class_name is None: + continue + # dummy object is accepted + if not hasattr(transformers, class_name): + # If the class name is in a model name mapping, let's not check if there is a definition in any modeling + # module, if it's a private model defined in this file. + if name.endswith("MODEL_MAPPING_NAMES") and is_a_private_model(class_name): + continue + if name.endswith("MODEL_FOR_IMAGE_MAPPING_NAMES") and is_a_private_model(class_name): + continue + failures.append( + f"`{class_name}` appears in the mapping `{name}` but it is not defined in the library." + ) + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_mapping_names_in_config_mapping_names(): + """Check all keys defined in auto mappings (mappings of names) appear in `CONFIG_MAPPING_NAMES`.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + # `TOKENIZER_PROCESSOR_MAPPING_NAMES` and `AutoTokenizer` is special, and don't need to follow the rule. + mappings_to_check = { + "IMAGE_PROCESSOR_MAPPING_NAMES": IMAGE_PROCESSOR_MAPPING_NAMES, + "FEATURE_EXTRACTOR_MAPPING_NAMES": FEATURE_EXTRACTOR_MAPPING_NAMES, + "PROCESSOR_MAPPING_NAMES": PROCESSOR_MAPPING_NAMES, + } + + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name, mapping in mappings_to_check.items(): + for model_type in mapping: + if model_type not in CONFIG_MAPPING_NAMES: + failures.append( + f"`{model_type}` appears in the mapping `{name}` but it is not defined in the keys of " + "`CONFIG_MAPPING_NAMES`." + ) + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_all_auto_mappings_importable(): + """Check all auto mappings can be imported.""" + # This is where we need to check we have all backends or the check is incomplete. + check_missing_backends() + + failures = [] + mappings_to_check = {} + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [x for x in dir(module) if x.endswith("_MAPPING_NAMES")] + mappings_to_check.update({name: getattr(module, name) for name in mapping_names}) + + for name in mappings_to_check: + name = name.replace("_MAPPING_NAMES", "_MAPPING") + if not hasattr(transformers, name): + failures.append(f"`{name}`") + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +def check_objects_being_equally_in_main_init(): + """ + Check if a (TensorFlow or Flax) object is in the main __init__ iif its counterpart in PyTorch is. + """ + attrs = dir(transformers) + + failures = [] + for attr in attrs: + obj = getattr(transformers, attr) + if hasattr(obj, "__module__") and isinstance(obj.__module__, ModuleSpec): + continue + if not hasattr(obj, "__module__") or "models.deprecated" in obj.__module__: + continue + + module_path = obj.__module__ + module_name = module_path.split(".")[-1] + module_dir = ".".join(module_path.split(".")[:-1]) + if ( + module_name.startswith("modeling_") + and not module_name.startswith("modeling_tf_") + and not module_name.startswith("modeling_flax_") + ): + parent_module = sys.modules[module_dir] + + frameworks = [] + if is_tf_available(): + frameworks.append("TF") + if is_flax_available(): + frameworks.append("Flax") + + for framework in frameworks: + other_module_path = module_path.replace("modeling_", f"modeling_{framework.lower()}_") + if os.path.isfile("src/" + other_module_path.replace(".", "/") + ".py"): + other_module_name = module_name.replace("modeling_", f"modeling_{framework.lower()}_") + other_module = getattr(parent_module, other_module_name) + if hasattr(other_module, f"{framework}{attr}"): + if not hasattr(transformers, f"{framework}{attr}"): + if f"{framework}{attr}" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK: + failures.append(f"{framework}{attr}") + if hasattr(other_module, f"{framework}_{attr}"): + if not hasattr(transformers, f"{framework}_{attr}"): + if f"{framework}_{attr}" not in OBJECT_TO_SKIP_IN_MAIN_INIT_CHECK: + failures.append(f"{framework}_{attr}") + if len(failures) > 0: + raise Exception(f"There were {len(failures)} failures:\n" + "\n".join(failures)) + + +_re_decorator = re.compile(r"^\s*@(\S+)\s+$") + + +def check_decorator_order(filename: str) -> list[int]: + """ + Check that in a given test file, the slow decorator is always last. + + Args: + filename (`str`): The path to a test file to check. + + Returns: + `List[int]`: The list of failures as a list of indices where there are problems. + """ + with open(filename, "r", encoding="utf-8", newline="\n") as f: + lines = f.readlines() + decorator_before = None + errors = [] + for i, line in enumerate(lines): + search = _re_decorator.search(line) + if search is not None: + decorator_name = search.groups()[0] + if decorator_before is not None and decorator_name.startswith("parameterized"): + errors.append(i) + decorator_before = decorator_name + elif decorator_before is not None: + decorator_before = None + return errors + + +def check_all_decorator_order(): + """Check that in all test files, the slow decorator is always last.""" + errors = [] + for fname in os.listdir(PATH_TO_TESTS): + if fname.endswith(".py"): + filename = os.path.join(PATH_TO_TESTS, fname) + new_errors = check_decorator_order(filename) + errors += [f"- {filename}, line {i}" for i in new_errors] + if len(errors) > 0: + msg = "\n".join(errors) + raise ValueError( + "The parameterized decorator (and its variants) should always be first, but this is not the case in the" + f" following files:\n{msg}" + ) + + +def find_all_documented_objects() -> list[str]: + """ + Parse the content of all doc files to detect which classes and functions it documents. + + Returns: + `List[str]`: The list of all object names being documented. + `Dict[str, List[str]]`: A dictionary mapping the object name (full import path, e.g. + `integrations.PeftAdapterMixin`) to its documented methods + """ + documented_obj = [] + documented_methods_map = {} + for doc_file in Path(PATH_TO_DOC).glob("**/*.md"): + with open(doc_file, "r", encoding="utf-8", newline="\n") as f: + content = f.read() + raw_doc_objs = re.findall(r"\[\[autodoc\]\]\s+(\S+)\s+", content) + documented_obj += [obj.split(".")[-1] for obj in raw_doc_objs] + + for obj in raw_doc_objs: + obj_public_methods = re.findall(rf"\[\[autodoc\]\] {obj}((\n\s+-.*)+)", content) + # Some objects have no methods documented + if len(obj_public_methods) == 0: + continue + else: + documented_methods_map[obj] = re.findall(r"(?<=-\s).*", obj_public_methods[0][0]) + + return documented_obj, documented_methods_map + + +# One good reason for not being documented is to be deprecated. Put in this list deprecated objects. +DEPRECATED_OBJECTS = [ + "AutoModelWithLMHead", + "BartPretrainedModel", + "DataCollator", + "DataCollatorForSOP", + "GlueDataset", + "GlueDataTrainingArguments", + "LineByLineTextDataset", + "LineByLineWithRefDataset", + "LineByLineWithSOPTextDataset", + "NerPipeline", + "PretrainedBartModel", + "PretrainedFSMTModel", + "SingleSentenceClassificationProcessor", + "SquadDataTrainingArguments", + "SquadDataset", + "SquadExample", + "SquadFeatures", + "SquadV1Processor", + "SquadV2Processor", + "TFAutoModelWithLMHead", + "TFBartPretrainedModel", + "TextDataset", + "TextDatasetForNextSentencePrediction", + "Wav2Vec2ForMaskedLM", + "Wav2Vec2Tokenizer", + "glue_compute_metrics", + "glue_convert_examples_to_features", + "glue_output_modes", + "glue_processors", + "glue_tasks_num_labels", + "squad_convert_examples_to_features", + "xnli_compute_metrics", + "xnli_output_modes", + "xnli_processors", + "xnli_tasks_num_labels", + "TFTrainingArguments", + "OwlViTFeatureExtractor", +] + +# Exceptionally, some objects should not be documented after all rules passed. +# ONLY PUT SOMETHING IN THIS LIST AS A LAST RESORT! +UNDOCUMENTED_OBJECTS = [ + "AddedToken", # This is a tokenizers class. + "BasicTokenizer", # Internal, should never have been in the main init. + "CharacterTokenizer", # Internal, should never have been in the main init. + "DPRPretrainedReader", # Like an Encoder. + "DummyObject", # Just picked by mistake sometimes. + "MecabTokenizer", # Internal, should never have been in the main init. + "ModelCard", # Internal type. + "SqueezeBertModule", # Internal building block (should have been called SqueezeBertLayer) + "TFDPRPretrainedReader", # Like an Encoder. + "TransfoXLCorpus", # Internal type. + "WordpieceTokenizer", # Internal, should never have been in the main init. + "absl", # External module + "add_end_docstrings", # Internal, should never have been in the main init. + "add_start_docstrings", # Internal, should never have been in the main init. + "convert_tf_weight_name_to_pt_weight_name", # Internal used to convert model weights + "logger", # Internal logger + "logging", # External module + "requires_backends", # Internal function + "AltRobertaModel", # Internal module + "VitPoseBackbone", # Internal module + "VitPoseBackboneConfig", # Internal module + "get_values", # Internal object + "SinkCache", # Moved to a custom_generate repository, to be deleted from transformers in v4.59.0 +] + +# This list should be empty. Objects in it should get their own doc page. +SHOULD_HAVE_THEIR_OWN_PAGE = [ + "AutoBackbone", + "BeitBackbone", + "BitBackbone", + "ConvNextBackbone", + "ConvNextV2Backbone", + "DinatBackbone", + "Dinov2Backbone", + "Dinov2WithRegistersBackbone", + "FocalNetBackbone", + "HieraBackbone", + "MaskFormerSwinBackbone", + "MaskFormerSwinConfig", + "MaskFormerSwinModel", + "NatBackbone", + "PvtV2Backbone", + "ResNetBackbone", + "SwinBackbone", + "Swinv2Backbone", + "TextNetBackbone", + "TimmBackbone", + "TimmBackboneConfig", + "VitDetBackbone", +] + + +def ignore_undocumented(name: str) -> bool: + """Rules to determine if `name` should be undocumented (returns `True` if it should not be documented).""" + # NOT DOCUMENTED ON PURPOSE. + # Constants uppercase are not documented. + if name.isupper(): + return True + # PreTrainedModels / Encoders / Decoders / Layers / Embeddings / Attention are not documented. + if ( + name.endswith("PreTrainedModel") + or name.endswith("Decoder") + or name.endswith("Encoder") + or name.endswith("Layer") + or name.endswith("Embeddings") + or name.endswith("Attention") + or name.endswith("OnnxConfig") + ): + return True + # Submodules are not documented. + if os.path.isdir(os.path.join(PATH_TO_TRANSFORMERS, name)) or os.path.isfile( + os.path.join(PATH_TO_TRANSFORMERS, f"{name}.py") + ): + return True + # All load functions are not documented. + if name.startswith("load_tf") or name.startswith("load_pytorch"): + return True + # is_xxx_available functions are not documented. + if name.startswith("is_") and name.endswith("_available"): + return True + # Deprecated objects are not documented. + if name in DEPRECATED_OBJECTS or name in UNDOCUMENTED_OBJECTS: + return True + # MMBT model does not really work. + if name.startswith("MMBT"): + return True + if name in SHOULD_HAVE_THEIR_OWN_PAGE: + return True + return False + + +def check_all_objects_are_documented(): + """Check all models are properly documented.""" + documented_objs, documented_methods_map = find_all_documented_objects() + modules = transformers._modules + objects = [c for c in dir(transformers) if c not in modules and not c.startswith("_")] + undocumented_objs = [c for c in objects if c not in documented_objs and not ignore_undocumented(c)] + if len(undocumented_objs) > 0: + raise Exception( + "The following objects are in the public init, but not in the docs:\n - " + "\n - ".join(undocumented_objs) + ) + check_model_type_doc_match() + check_public_method_exists(documented_methods_map) + + +def check_public_method_exists(documented_methods_map): + """Check that all explicitly documented public methods are defined in the corresponding class.""" + failures = [] + for obj, methods in documented_methods_map.items(): + # Let's ensure there is no repetition + if len(set(methods)) != len(methods): + failures.append(f"Error in the documentation of {obj}: there are repeated documented methods.") + + # Navigates into the object, given the full import path + nested_path = obj.split(".") + submodule = transformers + if len(nested_path) > 1: + nested_submodules = nested_path[:-1] + for submodule_name in nested_submodules: + if submodule_name == "transformers": + continue + + try: + submodule = getattr(submodule, submodule_name) + except AttributeError: + failures.append(f"Could not parse {submodule_name}. Are the required dependencies installed?") + continue + + class_name = nested_path[-1] + + try: + obj_class = getattr(submodule, class_name) + except AttributeError: + failures.append(f"Could not parse {class_name}. Are the required dependencies installed?") + continue + + # Checks that all explicitly documented methods are defined in the class + for method in methods: + if method == "all": # Special keyword to document all public methods + continue + try: + if not hasattr(obj_class, method): + failures.append( + "The following public method is explicitly documented but not defined in the corresponding " + f"class. class: {obj}, method: {method}. If the method is defined, this error can be due to " + f"lacking dependencies." + ) + except ImportError: + pass + + if len(failures) > 0: + raise Exception("\n".join(failures)) + + +def check_model_type_doc_match(): + """Check all doc pages have a corresponding model type.""" + model_doc_folder = Path(PATH_TO_DOC) / "model_doc" + model_docs = [m.stem for m in model_doc_folder.glob("*.md")] + + model_types = list(transformers.models.auto.configuration_auto.MODEL_NAMES_MAPPING.keys()) + model_types = [MODEL_TYPE_TO_DOC_MAPPING.get(m, m) for m in model_types] + + errors = [] + for m in model_docs: + if m not in model_types and m != "auto": + close_matches = get_close_matches(m, model_types) + error_message = f"{m} is not a proper model identifier." + if len(close_matches) > 0: + close_matches = "/".join(close_matches) + error_message += f" Did you mean {close_matches}?" + errors.append(error_message) + + if len(errors) > 0: + raise ValueError( + "Some model doc pages do not match any existing model type:\n" + + "\n".join(errors) + + "\nYou can add any missing model type to the `MODEL_NAMES_MAPPING` constant in " + "models/auto/configuration_auto.py." + ) + + +def check_deprecated_constant_is_up_to_date(): + """ + Check if the constant `DEPRECATED_MODELS` in `models/auto/configuration_auto.py` is up to date. + """ + deprecated_folder = os.path.join(PATH_TO_TRANSFORMERS, "models", "deprecated") + deprecated_models = [m for m in os.listdir(deprecated_folder) if not m.startswith("_")] + + constant_to_check = transformers.models.auto.configuration_auto.DEPRECATED_MODELS + message = [] + missing_models = sorted(set(deprecated_models) - set(constant_to_check)) + if len(missing_models) != 0: + missing_models = ", ".join(missing_models) + message.append( + "The following models are in the deprecated folder, make sure to add them to `DEPRECATED_MODELS` in " + f"`models/auto/configuration_auto.py`: {missing_models}." + ) + + extra_models = sorted(set(constant_to_check) - set(deprecated_models)) + if len(extra_models) != 0: + extra_models = ", ".join(extra_models) + message.append( + "The following models are in the `DEPRECATED_MODELS` constant but not in the deprecated folder. Either " + f"remove them from the constant or move to the deprecated folder: {extra_models}." + ) + + if len(message) > 0: + raise Exception("\n".join(message)) + + +def check_repo_quality(): + """Check all models are tested and documented.""" + print("Repository-wide checks:") + print(" - checking all models are included.") + check_model_list() + print(" - checking all models are public.") + check_models_are_in_init() + print(" - checking all models have tests.") + check_all_decorator_order() + check_all_models_are_tested() + print(" - checking all objects have documentation.") + check_all_objects_are_documented() + print(" - checking all models are in at least one auto class.") + check_all_models_are_auto_configured() + print(" - checking all names in auto name mappings are defined.") + check_all_auto_object_names_being_defined() + print(" - checking all keys in auto name mappings are defined in `CONFIG_MAPPING_NAMES`.") + check_all_auto_mapping_names_in_config_mapping_names() + print(" - checking all auto mappings could be imported.") + check_all_auto_mappings_importable() + print(" - checking all objects are equally (across frameworks) in the main __init__.") + check_objects_being_equally_in_main_init() + print(" - checking the DEPRECATED_MODELS constant is up to date.") + check_deprecated_constant_is_up_to_date() + + +if __name__ == "__main__": + check_repo_quality() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_self_hosted_runner.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_self_hosted_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..0c651d1a1248e3ee73000850838fd8fb32d375c4 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_self_hosted_runner.py @@ -0,0 +1,57 @@ +import argparse +import json +import subprocess + + +def get_runner_status(target_runners, token): + offline_runners = [] + + cmd = [ + "curl", + "-H", + "Accept: application/vnd.github+json", + "-H", + f"Authorization: Bearer {token}", + "https://api.github.com/repos/huggingface/transformers/actions/runners", + ] + + output = subprocess.run(cmd, check=False, shell=True, stdout=subprocess.PIPE) + o = output.stdout.decode("utf-8") + status = json.loads(o) + + runners = status["runners"] + for runner in runners: + if runner["name"] in target_runners: + if runner["status"] == "offline": + offline_runners.append(runner) + + # save the result so we can report them on Slack + with open("offline_runners.txt", "w") as fp: + fp.write(json.dumps(offline_runners)) + + if len(offline_runners) > 0: + failed = "\n".join([x["name"] for x in offline_runners]) + raise ValueError(f"The following runners are offline:\n{failed}") + + +if __name__ == "__main__": + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument( + "--target_runners", + default=None, + type=list_str, + required=True, + help="Comma-separated list of runners to check status.", + ) + + parser.add_argument( + "--token", default=None, type=str, required=True, help="A token that has actions:read permission." + ) + args = parser.parse_args() + + get_runner_status(args.target_runners, args.token) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_tf_ops.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_tf_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..f6c2b8bae4e26b74e38728fc1440a58cf4837c1b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/check_tf_ops.py @@ -0,0 +1,101 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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. + +import argparse +import json +import os + +from tensorflow.core.protobuf.saved_model_pb2 import SavedModel + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/check_copies.py +REPO_PATH = "." + +# Internal TensorFlow ops that can be safely ignored (mostly specific to a saved model) +INTERNAL_OPS = [ + "Assert", + "AssignVariableOp", + "EmptyTensorList", + "MergeV2Checkpoints", + "ReadVariableOp", + "ResourceGather", + "RestoreV2", + "SaveV2", + "ShardedFilename", + "StatefulPartitionedCall", + "StaticRegexFullMatch", + "VarHandleOp", +] + + +def onnx_compliancy(saved_model_path, strict, opset): + saved_model = SavedModel() + onnx_ops = [] + + with open(os.path.join(REPO_PATH, "utils", "tf_ops", "onnx.json")) as f: + onnx_opsets = json.load(f)["opsets"] + + for i in range(1, opset + 1): + onnx_ops.extend(onnx_opsets[str(i)]) + + with open(saved_model_path, "rb") as f: + saved_model.ParseFromString(f.read()) + + model_op_names = set() + + # Iterate over every metagraph in case there is more than one (a saved model can contain multiple graphs) + for meta_graph in saved_model.meta_graphs: + # Add operations in the graph definition + model_op_names.update(node.op for node in meta_graph.graph_def.node) + + # Go through the functions in the graph definition + for func in meta_graph.graph_def.library.function: + # Add operations in each function + model_op_names.update(node.op for node in func.node_def) + + # Convert to list, sorted if you want + model_op_names = sorted(model_op_names) + incompatible_ops = [] + + for op in model_op_names: + if op not in onnx_ops and op not in INTERNAL_OPS: + incompatible_ops.append(op) + + if strict and len(incompatible_ops) > 0: + raise Exception(f"Found the following incompatible ops for the opset {opset}:\n" + incompatible_ops) + elif len(incompatible_ops) > 0: + print(f"Found the following incompatible ops for the opset {opset}:") + print(*incompatible_ops, sep="\n") + else: + print(f"The saved model {saved_model_path} can properly be converted with ONNX.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--saved_model_path", help="Path of the saved model to check (the .pb file).") + parser.add_argument( + "--opset", default=12, type=int, help="The ONNX opset against which the model has to be tested." + ) + parser.add_argument( + "--framework", choices=["onnx"], default="onnx", help="Frameworks against which to test the saved model." + ) + parser.add_argument( + "--strict", action="store_true", help="Whether make the checking strict (raise errors) or not (raise warnings)" + ) + args = parser.parse_args() + + if args.framework == "onnx": + onnx_compliancy(args.saved_model_path, args.strict, args.opset) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/collated_reports.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/collated_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..566cc05db7c11633ec841223a388e91304b3eb72 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/collated_reports.py @@ -0,0 +1,219 @@ +# Copyright 2025 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. + +import argparse +import json +import subprocess +from dataclasses import dataclass +from pathlib import Path + + +DEFAULT_GPU_NAMES = ["mi300", "mi325", "mi355", "h100", "a10"] + + +def simplify_gpu_name(gpu_name: str, simplified_names: list[str]) -> str: + matches = [] + for simplified_name in simplified_names: + if simplified_name in gpu_name: + matches.append(simplified_name) + if len(matches) == 1: + return matches[0] + return gpu_name + + +def parse_short_summary_line(line: str) -> tuple[str | None, int]: + if line.startswith("PASSED"): + return "passed", 1 + if line.startswith("FAILED"): + return "failed", 1 + if line.startswith("SKIPPED"): + line = line.split("[", maxsplit=1)[1] + line = line.split("]", maxsplit=1)[0] + return "skipped", int(line) + if line.startswith("ERROR"): + return "error", 1 + return None, 0 + + +def validate_path(p: str) -> Path: + # Validate path and apply glob pattern if provided + path = Path(p) + assert path.is_dir(), f"Path {path} is not a directory" + return path + + +def get_gpu_name(gpu_name: str | None) -> str: + # Get GPU name if available + if gpu_name is None: + try: + import torch + + gpu_name = torch.cuda.get_device_name() + except Exception as e: + print(f"Failed to get GPU name with {e}") + gpu_name = "unknown" + else: + gpu_name = gpu_name.replace(" ", "_").lower() + gpu_name = simplify_gpu_name(gpu_name, DEFAULT_GPU_NAMES) + + return gpu_name + + +def get_commit_hash(commit_hash: str | None) -> str: + # Get commit hash if available + if commit_hash is None: + try: + commit_hash = subprocess.check_output(["git", "rev-parse", "HEAD"]).decode("utf-8").strip() + except Exception as e: + print(f"Failed to get commit hash with {e}") + commit_hash = "unknown" + + return commit_hash[:7] + + +@dataclass +class Args: + path: Path + machine_type: str + gpu_name: str + commit_hash: str + job: str | None + report_repo_id: str | None + + +def get_arguments(args: argparse.Namespace) -> Args: + path = validate_path(args.path) + machine_type = args.machine_type + gpu_name = get_gpu_name(args.gpu_name) + commit_hash = get_commit_hash(args.commit_hash) + job = args.job + report_repo_id = args.report_repo_id + return Args(path, machine_type, gpu_name, commit_hash, job, report_repo_id) + + +def upload_collated_report(job: str, report_repo_id: str, filename: str): + # Alternatively we can check for the existence of the collated_reports file and upload in notification_service.py + import os + + from get_previous_daily_ci import get_last_daily_ci_run + from huggingface_hub import HfApi + + api = HfApi() + + # if it is not a scheduled run, upload the reports to a subfolder under `report_repo_folder` + report_repo_subfolder = "" + if os.getenv("GITHUB_EVENT_NAME") != "schedule": + report_repo_subfolder = f"{os.getenv('GITHUB_RUN_NUMBER')}-{os.getenv('GITHUB_RUN_ID')}" + report_repo_subfolder = f"runs/{report_repo_subfolder}" + + workflow_run = get_last_daily_ci_run( + token=os.environ["ACCESS_REPO_INFO_TOKEN"], workflow_run_id=os.getenv("GITHUB_RUN_ID") + ) + workflow_run_created_time = workflow_run["created_at"] + report_repo_folder = workflow_run_created_time.split("T")[0] + + if report_repo_subfolder: + report_repo_folder = f"{report_repo_folder}/{report_repo_subfolder}" + + api.upload_file( + path_or_fileobj=f"ci_results_{job}/{filename}", + path_in_repo=f"{report_repo_folder}/ci_results_{job}/{filename}", + repo_id=report_repo_id, + repo_type="dataset", + token=os.getenv("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN"), + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Post process models test reports.") + parser.add_argument("--path", "-p", help="Path to the reports folder") + parser.add_argument( + "--machine-type", "-m", help="Process single or multi GPU results", choices=["single-gpu", "multi-gpu"] + ) + parser.add_argument("--gpu-name", "-g", help="GPU name", default=None) + parser.add_argument("--commit-hash", "-c", help="Commit hash", default=None) + parser.add_argument("--job", "-j", help="Optional job name required for uploading reports", default=None) + parser.add_argument( + "--report-repo-id", "-r", help="Optional report repository ID required for uploading reports", default=None + ) + args = get_arguments(parser.parse_args()) + + # Initialize accumulators for collated report + total_status_count = { + "passed": 0, + "failed": 0, + "skipped": 0, + "error": 0, + None: 0, + } + collated_report_buffer = [] + + path = args.path + machine_type = args.machine_type + gpu_name = args.gpu_name + commit_hash = args.commit_hash + job = args.job + report_repo_id = args.report_repo_id + + # Find the origin directory based on machine type + origin = path + for p in path.iterdir(): + if machine_type in p.name: + origin = p + break + + # Loop through model directories and create collated reports + for model_dir in sorted(origin.iterdir()): + # Create a new entry for the model + model_name = model_dir.name.removesuffix("_test_reports") + report = {"model": model_name, "results": []} + results = [] + + # Read short summary + with open(model_dir / "summary_short.txt", "r") as f: + short_summary_lines = f.readlines() + + # Parse short summary + for line in short_summary_lines[1:]: + status, count = parse_short_summary_line(line) + total_status_count[status] += count + if status: + result = { + "status": status, + "test": line.split(status.upper(), maxsplit=1)[1].strip(), + "count": count, + } + results.append(result) + + # Add short summaries to report + report["results"] = results + + collated_report_buffer.append(report) + + # Write collated report + with open(f"collated_reports_{commit_hash}.json", "w") as f: + json.dump( + { + "gpu_name": gpu_name, + "machine_type": machine_type, + "commit_hash": commit_hash, + "total_status_count": total_status_count, + "results": collated_report_buffer, + }, + f, + indent=2, + ) + + if job and report_repo_id: + upload_collated_report(job, report_repo_id, f"collated_reports_{commit_hash}.json") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/compare_test_runs.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/compare_test_runs.py new file mode 100644 index 0000000000000000000000000000000000000000..9724c5506bd5337e0c2dfae64d0b24e7b9967768 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/compare_test_runs.py @@ -0,0 +1,91 @@ +# Copyright 2025 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. + +import re + + +def normalize_test_line(line): + line = line.strip() + + # Normalize SKIPPED/XFAIL/etc with path:line and reason + match = re.match(r"^(SKIPPED|XFAIL|XPASS|EXPECTEDFAIL)\s+\[?\d*\]?\s*(\S+:\d+)", line) + if match: + status, location = match.groups() + return f"{status} {location}" + + # Normalize ERROR/FAILED lines with optional message + if line.startswith("ERROR") or line.startswith("FAILED"): + return re.split(r"\s+-\s+", line)[0].strip() + + return line + + +def parse_summary_file(file_path): + test_set = set() + with open(file_path, "r", encoding="utf-8") as f: + in_summary = False + for line in f: + if line.strip().startswith("==="): + in_summary = not in_summary + continue + if in_summary: + stripped = line.strip() + if stripped: + normalized = normalize_test_line(stripped) + test_set.add(normalized) + return test_set + + +def compare_job_sets(job_set1, job_set2): + all_job_names = sorted(set(job_set1) | set(job_set2)) + report_lines = [] + + for job_name in all_job_names: + file1 = job_set1.get(job_name) + file2 = job_set2.get(job_name) + + tests1 = parse_summary_file(file1) if file1 else set() + tests2 = parse_summary_file(file2) if file2 else set() + + added = tests2 - tests1 + removed = tests1 - tests2 + + if added or removed: + report_lines.append(f"=== Diff for job: {job_name} ===") + if removed: + report_lines.append("--- Absent in current run:") + for test in sorted(removed): + report_lines.append(f" - {test}") + if added: + report_lines.append("+++ Appeared in current run:") + for test in sorted(added): + report_lines.append(f" + {test}") + report_lines.append("") # blank line + + return "\n".join(report_lines) if report_lines else "No differences found." + + +# Example usage: +# job_set_1 = { +# "albert": "prev/multi-gpu_run_models_gpu_models/albert_test_reports/summary_short.txt", +# "bloom": "prev/multi-gpu_run_models_gpu_models/bloom_test_reports/summary_short.txt", +# } + +# job_set_2 = { +# "albert": "curr/multi-gpu_run_models_gpu_models/albert_test_reports/summary_short.txt", +# "bloom": "curr/multi-gpu_run_models_gpu_models/bloom_test_reports/summary_short.txt", +# } + +# report = compare_job_sets(job_set_1, job_set_2) +# print(report) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/create_dependency_mapping.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/create_dependency_mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..84fec10e939304721489bd034d1b90fbba12b560 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/create_dependency_mapping.py @@ -0,0 +1,91 @@ +import ast +from collections import defaultdict + + +# Function to perform topological sorting +def topological_sort(dependencies: dict) -> list[list[str]]: + """Given the dependencies graph construct sorted list of list of modular files + + For example, returned list of lists might be: + [ + ["../modular_llama.py", "../modular_gemma.py"], # level 0 + ["../modular_llama4.py", "../modular_gemma2.py"], # level 1 + ["../modular_glm4.py"], # level 2 + ] + which means llama and gemma do not depend on any other modular models, while llama4 and gemma2 + depend on the models in the first list, and glm4 depends on the models in the second and (optionally) in the first list. + """ + + # Nodes are the name of the models to convert (we only add those to the graph) + nodes = {node.rsplit("modular_", 1)[1].replace(".py", "") for node in dependencies} + # This will be a graph from models to convert, to models to convert that should be converted before (as they are a dependency) + graph = {} + name_mapping = {} + for node, deps in dependencies.items(): + node_name = node.rsplit("modular_", 1)[1].replace(".py", "") + dep_names = {dep.split(".")[-2] for dep in deps} + dependencies = {dep for dep in dep_names if dep in nodes and dep != node_name} + graph[node_name] = dependencies + name_mapping[node_name] = node + + sorting_list = [] + while len(graph) > 0: + # Find the nodes with 0 out-degree + leaf_nodes = {node for node in graph if len(graph[node]) == 0} + # Add them to the list as next level + sorting_list.append([name_mapping[node] for node in leaf_nodes]) + # Remove the leafs from the graph (and from the deps of other nodes) + graph = {node: deps - leaf_nodes for node, deps in graph.items() if node not in leaf_nodes} + + return sorting_list + + +# Function to extract class and import info from a file +def extract_classes_and_imports(file_path): + with open(file_path, "r", encoding="utf-8") as file: + tree = ast.parse(file.read(), filename=file_path) + imports = set() + + for node in ast.walk(tree): + if isinstance(node, (ast.Import, ast.ImportFrom)): + module = node.module if isinstance(node, ast.ImportFrom) else None + if module and (".modeling_" in module or "transformers.models" in module): + imports.add(module) + return imports + + +# Function to map dependencies between classes +def map_dependencies(py_files): + dependencies = defaultdict(set) + # First pass: Extract all classes and map to files + for file_path in py_files: + # dependencies[file_path].add(None) + class_to_file = extract_classes_and_imports(file_path) + for module in class_to_file: + dependencies[file_path].add(module) + return dependencies + + +def find_priority_list(py_files): + """ + Given a list of modular files, sorts them by topological order. Modular models that DON'T depend on other modular + models will be higher in the topological order. + + Args: + py_files: List of paths to the modular files + + Returns: + Ordered list of lists of files and their dependencies (dict) + + For example, ordered_files might be: + [ + ["../modular_llama.py", "../modular_gemma.py"], # level 0 + ["../modular_llama4.py", "../modular_gemma2.py"], # level 1 + ["../modular_glm4.py"], # level 2 + ] + which means llama and gemma do not depend on any other modular models, while llama4 and gemma2 + depend on the models in the first list, and glm4 depends on the models in the second and (optionally) in the first list. + """ + dependencies = map_dependencies(py_files) + ordered_files = topological_sort(dependencies) + return ordered_files, dependencies diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/create_dummy_models.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/create_dummy_models.py new file mode 100644 index 0000000000000000000000000000000000000000..c8e2bd4557ab5b1d5b2c714aa0fccaef1c1f9950 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/create_dummy_models.py @@ -0,0 +1,1577 @@ +# coding=utf-8 +# Copyright 2022 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. + +import argparse +import collections.abc +import copy +import inspect +import json +import multiprocessing +import os +import shutil +import tempfile +import traceback +from pathlib import Path + +from check_config_docstrings import get_checkpoint_from_config_class +from datasets import load_dataset +from get_test_info import get_model_to_tester_mapping, get_tester_classes_for_model +from huggingface_hub import Repository, create_repo, hf_api, upload_folder + +from transformers import ( + CONFIG_MAPPING, + FEATURE_EXTRACTOR_MAPPING, + IMAGE_PROCESSOR_MAPPING, + PROCESSOR_MAPPING, + TOKENIZER_MAPPING, + AutoTokenizer, + LayoutLMv3TokenizerFast, + PreTrainedTokenizer, + PreTrainedTokenizerFast, + logging, +) +from transformers.feature_extraction_utils import FeatureExtractionMixin +from transformers.file_utils import is_tf_available, is_torch_available +from transformers.image_processing_utils import BaseImageProcessor +from transformers.models.auto.configuration_auto import AutoConfig, model_type_to_module_name +from transformers.models.fsmt import configuration_fsmt +from transformers.processing_utils import ProcessorMixin, transformers_module +from transformers.tokenization_utils_base import PreTrainedTokenizerBase + + +# make sure tokenizer plays nice with multiprocessing +os.environ["TOKENIZERS_PARALLELISM"] = "false" + +logging.set_verbosity_error() +logging.disable_progress_bar() +logger = logging.get_logger(__name__) + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + +if not is_torch_available(): + raise ValueError("Please install PyTorch.") + +if not is_tf_available(): + raise ValueError("Please install TensorFlow.") + + +FRAMEWORKS = ["pytorch", "tensorflow"] +INVALID_ARCH = [] +TARGET_VOCAB_SIZE = 1024 + +data = {"training_ds": None, "testing_ds": None} + +COMPOSITE_MODELS = { + "EncoderDecoderModel": "EncoderDecoderModel-bert-bert", + "SpeechEncoderDecoderModel": "SpeechEncoderDecoderModel-wav2vec2-bert", + "VisionEncoderDecoderModel": "VisionEncoderDecoderModel-vit-gpt2", + "VisionTextDualEncoderModel": "VisionTextDualEncoderModel-vit-bert", +} + +# This list contains the model architectures for which a tiny version could not be created. +# Avoid to add new architectures here - unless we have verified carefully that it's (almost) impossible to create them. +# One such case is: no model tester class is implemented for a model type (like `MT5`) because its architecture is +# identical to another one (`MT5` is based on `T5`), but trained on different datasets or with different techniques. +UNCONVERTIBLE_MODEL_ARCHITECTURES = { + "BertGenerationEncoder", + "BertGenerationDecoder", + "CamembertForSequenceClassification", + "CamembertForMultipleChoice", + "CamembertForMaskedLM", + "CamembertForCausalLM", + "CamembertForTokenClassification", + "CamembertForQuestionAnswering", + "CamembertModel", + "TFCamembertForMultipleChoice", + "TFCamembertForTokenClassification", + "TFCamembertForQuestionAnswering", + "TFCamembertForSequenceClassification", + "TFCamembertForMaskedLM", + "TFCamembertModel", + "TFCamembertForCausalLM", + "DecisionTransformerModel", + "GraphormerModel", + "InformerModel", + "JukeboxModel", + "MarianForCausalLM", + "MaskFormerSwinModel", + "MaskFormerSwinBackbone", + "MT5Model", + "MT5ForConditionalGeneration", + "UMT5ForConditionalGeneration", + "TFMT5ForConditionalGeneration", + "TFMT5Model", + "QDQBertForSequenceClassification", + "QDQBertForMaskedLM", + "QDQBertModel", + "QDQBertForTokenClassification", + "QDQBertLMHeadModel", + "QDQBertForMultipleChoice", + "QDQBertForQuestionAnswering", + "QDQBertForNextSentencePrediction", + "ReformerModelWithLMHead", + "RetriBertModel", + "Speech2Text2ForCausalLM", + "TimeSeriesTransformerModel", + "TrajectoryTransformerModel", + "TrOCRForCausalLM", + "XLMProphetNetForConditionalGeneration", + "XLMProphetNetForCausalLM", + "XLMProphetNetModel", + "XLMRobertaModel", + "XLMRobertaForTokenClassification", + "XLMRobertaForMultipleChoice", + "XLMRobertaForMaskedLM", + "XLMRobertaForCausalLM", + "XLMRobertaForSequenceClassification", + "XLMRobertaForQuestionAnswering", + "TFXLMRobertaForSequenceClassification", + "TFXLMRobertaForMaskedLM", + "TFXLMRobertaForCausalLM", + "TFXLMRobertaForQuestionAnswering", + "TFXLMRobertaModel", + "TFXLMRobertaForMultipleChoice", + "TFXLMRobertaForTokenClassification", +} + + +def get_processor_types_from_config_class(config_class, allowed_mappings=None): + """Return a tuple of processors for `config_class`. + + We use `tuple` here to include (potentially) both slow & fast tokenizers. + """ + + # To make a uniform return type + def _to_tuple(x): + if not isinstance(x, collections.abc.Sequence): + x = (x,) + else: + x = tuple(x) + return x + + if allowed_mappings is None: + allowed_mappings = ["processor", "tokenizer", "image_processor", "feature_extractor"] + + processor_types = () + + # Check first if a model has `ProcessorMixin`. Otherwise, check if it has tokenizers, and/or an image processor or + # a feature extractor + if config_class in PROCESSOR_MAPPING and "processor" in allowed_mappings: + processor_types = _to_tuple(PROCESSOR_MAPPING[config_class]) + else: + if config_class in TOKENIZER_MAPPING and "tokenizer" in allowed_mappings: + processor_types = TOKENIZER_MAPPING[config_class] + + if config_class in IMAGE_PROCESSOR_MAPPING and "image_processor" in allowed_mappings: + processor_types += _to_tuple(IMAGE_PROCESSOR_MAPPING[config_class]) + elif config_class in FEATURE_EXTRACTOR_MAPPING and "feature_extractor" in allowed_mappings: + processor_types += _to_tuple(FEATURE_EXTRACTOR_MAPPING[config_class]) + + # Remark: some configurations have no processor at all. For example, generic composite models like + # `EncoderDecoderModel` is used for any (compatible) text models. Also, `DecisionTransformer` doesn't + # require any processor. + + # We might get `None` for some tokenizers - remove them here. + processor_types = tuple(p for p in processor_types if p is not None) + + return processor_types + + +def get_architectures_from_config_class(config_class, arch_mappings, models_to_skip=None): + """Return a tuple of all possible architectures attributed to a configuration class `config_class`. + + For example, BertConfig -> [BertModel, BertForMaskedLM, ..., BertForQuestionAnswering]. + """ + # A model architecture could appear in several mappings. For example, `BartForConditionalGeneration` is in + # - MODEL_FOR_PRETRAINING_MAPPING_NAMES + # - MODEL_WITH_LM_HEAD_MAPPING_NAMES + # - MODEL_FOR_MASKED_LM_MAPPING_NAMES + # - MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES + # We avoid the duplication. + architectures = set() + + if models_to_skip is None: + models_to_skip = [] + models_to_skip = UNCONVERTIBLE_MODEL_ARCHITECTURES.union(models_to_skip) + + for mapping in arch_mappings: + if config_class in mapping: + models = mapping[config_class] + models = tuple(models) if isinstance(models, collections.abc.Sequence) else (models,) + for model in models: + if model.__name__ not in models_to_skip: + architectures.add(model) + + architectures = tuple(architectures) + + return architectures + + +def get_config_class_from_processor_class(processor_class): + """Get the config class from a processor class. + + Some config/model classes use tokenizers/feature_extractors from other models. For example, `GPT-J` uses + `GPT2Tokenizer`. If no checkpoint is found for a config class, or a checkpoint is found without necessary file(s) to + create the processor for `processor_class`, we get the config class that corresponds to `processor_class` and use it + to find a checkpoint in order to create the processor. + """ + + processor_prefix = processor_class.__name__ + for postfix in ["TokenizerFast", "Tokenizer", "ImageProcessor", "FeatureExtractor", "Processor"]: + processor_prefix = processor_prefix.replace(postfix, "") + + # `Wav2Vec2CTCTokenizer` -> `Wav2Vec2Config` + if processor_prefix == "Wav2Vec2CTC": + processor_prefix = "Wav2Vec2" + + # Find the new configuration class + new_config_name = f"{processor_prefix}Config" + new_config_class = getattr(transformers_module, new_config_name) + + return new_config_class + + +def build_processor(config_class, processor_class, allow_no_checkpoint=False): + """Create a processor for `processor_class`. + + If a processor is not able to be built with the original arguments, this method tries to change the arguments and + call itself recursively, by inferring a new `config_class` or a new `processor_class` from another one, in order to + find a checkpoint containing the necessary files to build a processor. + + The processor is not saved here. Instead, it will be saved in `convert_processors` after further changes in + `convert_processors`. For each model architecture`, a copy will be created and saved along the built model. + """ + # Currently, this solely uses the docstring in the source file of `config_class` to find a checkpoint. + checkpoint = get_checkpoint_from_config_class(config_class) + + if checkpoint is None: + # try to get the checkpoint from the config class for `processor_class`. + # This helps cases like `XCLIPConfig` and `VideoMAEFeatureExtractor` to find a checkpoint from `VideoMAEConfig`. + config_class_from_processor_class = get_config_class_from_processor_class(processor_class) + checkpoint = get_checkpoint_from_config_class(config_class_from_processor_class) + + processor = None + try: + processor = processor_class.from_pretrained(checkpoint) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + + # Try to get a new processor class from checkpoint. This is helpful for a checkpoint without necessary file to load + # processor while `processor_class` is an Auto class. For example, `sew` has `Wav2Vec2Processor` in + # `PROCESSOR_MAPPING_NAMES`, its `tokenizer_class` is `AutoTokenizer`, and the checkpoint + # `https://huggingface.co/asapp/sew-tiny-100k` has no tokenizer file, but we can get + # `tokenizer_class: Wav2Vec2CTCTokenizer` from the config file. (The new processor class won't be able to load from + # `checkpoint`, but it helps this recursive method to find a way to build a processor). + if ( + processor is None + and checkpoint is not None + and issubclass(processor_class, (PreTrainedTokenizerBase, AutoTokenizer)) + ): + try: + config = AutoConfig.from_pretrained(checkpoint) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + config = None + if config is not None: + if not isinstance(config, config_class): + raise ValueError( + f"`config` (which is of type {config.__class__.__name__}) should be an instance of `config_class`" + f" ({config_class.__name__})!" + ) + tokenizer_class = config.tokenizer_class + new_processor_class = None + if tokenizer_class is not None: + new_processor_class = getattr(transformers_module, tokenizer_class) + if new_processor_class != processor_class: + processor = build_processor(config_class, new_processor_class) + # If `tokenizer_class` is not specified in `config`, let's use `config` to get the process class via auto + # mappings, but only allow the tokenizer mapping being used. This is to make `Wav2Vec2Conformer` build + if processor is None: + new_processor_classes = get_processor_types_from_config_class( + config.__class__, allowed_mappings=["tokenizer"] + ) + # Used to avoid infinite recursion between a pair of fast/slow tokenizer types + names = [ + x.__name__.replace("Fast", "") for x in [processor_class, new_processor_class] if x is not None + ] + new_processor_classes = [ + x for x in new_processor_classes if x is not None and x.__name__.replace("Fast", "") not in names + ] + if len(new_processor_classes) > 0: + new_processor_class = new_processor_classes[0] + # Let's use fast tokenizer if there is any + for x in new_processor_classes: + if x.__name__.endswith("Fast"): + new_processor_class = x + break + processor = build_processor(config_class, new_processor_class) + + if processor is None: + # Try to build each component (tokenizer & feature extractor) of a `ProcessorMixin`. + if issubclass(processor_class, ProcessorMixin): + attrs = {} + for attr_name in processor_class.attributes: + attrs[attr_name] = [] + # This could be a tuple (for tokenizers). For example, `CLIPProcessor` has + # - feature_extractor_class = "CLIPFeatureExtractor" + # - tokenizer_class = ("CLIPTokenizer", "CLIPTokenizerFast") + attr_class_names = getattr(processor_class, f"{attr_name}_class") + if not isinstance(attr_class_names, tuple): + attr_class_names = (attr_class_names,) + + for name in attr_class_names: + attr_class = getattr(transformers_module, name) + attr = build_processor(config_class, attr_class) + if attr is not None: + attrs[attr_name].append(attr) + + # try to build a `ProcessorMixin`, so we can return a single value + if all(len(v) > 0 for v in attrs.values()): + try: + processor = processor_class(**{k: v[0] for k, v in attrs.items()}) + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + else: + # `checkpoint` might lack some file(s) to load a processor. For example, `facebook/hubert-base-ls960` + # has no tokenizer file to load `Wav2Vec2CTCTokenizer`. In this case, we try to build a processor + # with the configuration class (for example, `Wav2Vec2Config`) corresponding to `processor_class`. + config_class_from_processor_class = get_config_class_from_processor_class(processor_class) + if config_class_from_processor_class != config_class: + processor = build_processor(config_class_from_processor_class, processor_class) + + # Try to create an image processor or a feature extractor without any checkpoint + if ( + processor is None + and allow_no_checkpoint + and (issubclass(processor_class, BaseImageProcessor) or issubclass(processor_class, FeatureExtractionMixin)) + ): + try: + processor = processor_class() + except Exception as e: + logger.error(f"{e.__class__.__name__}: {e}") + + # validation + if processor is not None: + if not (isinstance(processor, processor_class) or processor_class.__name__.startswith("Auto")): + raise ValueError( + f"`processor` (which is of type {processor.__class__.__name__}) should be an instance of" + f" {processor_class.__name__} or an Auto class!" + ) + + return processor + + +def get_tiny_config(config_class, model_class=None, **model_tester_kwargs): + """Retrieve a tiny configuration from `config_class` using each model's `ModelTester`. + + Args: + config_class: Subclass of `PreTrainedConfig`. + + Returns: + An instance of `config_class` with tiny hyperparameters + """ + model_type = config_class.model_type + + # For model type like `data2vec-vision` and `donut-swin`, we can't get the config/model file name directly via + # `model_type` as it would be sth. like `configuration_data2vec_vision.py`. + # A simple way is to use `inspect.getsourcefile(config_class)`. + config_source_file = inspect.getsourcefile(config_class) + # The modeling file name without prefix (`modeling_`) and postfix (`.py`) + modeling_name = config_source_file.split(os.path.sep)[-1].replace("configuration_", "").replace(".py", "") + + try: + print("Importing", model_type_to_module_name(model_type)) + module_name = model_type_to_module_name(model_type) + if not modeling_name.startswith(module_name): + raise ValueError(f"{modeling_name} doesn't start with {module_name}!") + test_file = os.path.join("tests", "models", module_name, f"test_modeling_{modeling_name}.py") + models_to_model_testers = get_model_to_tester_mapping(test_file) + # Find the model tester class + model_tester_class = None + tester_classes = [] + if model_class is not None: + tester_classes = get_tester_classes_for_model(test_file, model_class) + else: + for _tester_classes in models_to_model_testers.values(): + tester_classes.extend(_tester_classes) + if len(tester_classes) > 0: + # sort with the length of the class names first, then the alphabetical order + # This is to avoid `T5EncoderOnlyModelTest` is used instead of `T5ModelTest`, which has + # `is_encoder_decoder=False` and causes some pipeline tests failing (also failures in `Optimum` CI). + # TODO: More fine grained control of the desired tester class. + model_tester_class = sorted(tester_classes, key=lambda x: (len(x.__name__), x.__name__))[0] + except ModuleNotFoundError: + error = f"Tiny config not created for {model_type} - cannot find the testing module from the model name." + raise ValueError(error) + + if model_tester_class is None: + error = f"Tiny config not created for {model_type} - no model tester is found in the testing module." + raise ValueError(error) + + # CLIP-like models have `text_model_tester` and `vision_model_tester`, and we need to pass `vocab_size` to + # `text_model_tester` via `text_kwargs`. The same trick is also necessary for `Flava`. + + if "vocab_size" in model_tester_kwargs: + if "text_kwargs" in inspect.signature(model_tester_class.__init__).parameters: + vocab_size = model_tester_kwargs.pop("vocab_size") + model_tester_kwargs["text_kwargs"] = {"vocab_size": vocab_size} + + # `parent` is an instance of `unittest.TestCase`, but we don't need it here. + model_tester = model_tester_class(parent=None, **model_tester_kwargs) + + if hasattr(model_tester, "get_pipeline_config"): + config = model_tester.get_pipeline_config() + elif hasattr(model_tester, "prepare_config_and_inputs"): + # `PoolFormer` has no `get_config` defined. Furthermore, it's better to use `prepare_config_and_inputs` even if + # `get_config` is defined, since there might be some extra changes in `prepare_config_and_inputs`. + config = model_tester.prepare_config_and_inputs()[0] + elif hasattr(model_tester, "get_config"): + config = model_tester.get_config() + else: + error = ( + f"Tiny config not created for {model_type} - the model tester {model_tester_class.__name__} lacks" + " necessary method to create config." + ) + raise ValueError(error) + + # make sure this is long enough (some model tester has `20` for this attr.) to pass `text-generation` + # pipeline tests. + max_positions = [] + for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]: + if getattr(config, key, 0) > 0: + max_positions.append(getattr(config, key)) + if getattr(config, "text_config", None) is not None: + if getattr(config.text_config, key, None) is not None: + max_positions.append(getattr(config.text_config, key)) + if len(max_positions) > 0: + max_position = max(200, min(max_positions)) + for key in ["max_position_embeddings", "max_source_positions", "max_target_positions"]: + if getattr(config, key, 0) > 0: + setattr(config, key, max_position) + if getattr(config, "text_config", None) is not None: + if getattr(config.text_config, key, None) is not None: + setattr(config.text_config, key, max_position) + + return config + + +def convert_tokenizer(tokenizer_fast: PreTrainedTokenizerFast): + new_tokenizer = tokenizer_fast.train_new_from_iterator( + data["training_ds"]["text"], TARGET_VOCAB_SIZE, show_progress=False + ) + + # Make sure it at least runs + if not isinstance(new_tokenizer, LayoutLMv3TokenizerFast): + new_tokenizer(data["testing_ds"]["text"]) + + return new_tokenizer + + +def convert_feature_extractor(feature_extractor, tiny_config): + to_convert = False + kwargs = {} + if hasattr(tiny_config, "image_size"): + kwargs["size"] = tiny_config.image_size + kwargs["crop_size"] = tiny_config.image_size + to_convert = True + elif ( + hasattr(tiny_config, "vision_config") + and tiny_config.vision_config is not None + and hasattr(tiny_config.vision_config, "image_size") + ): + kwargs["size"] = tiny_config.vision_config.image_size + kwargs["crop_size"] = tiny_config.vision_config.image_size + to_convert = True + + # Speech2TextModel specific. + if hasattr(tiny_config, "input_feat_per_channel"): + kwargs["feature_size"] = tiny_config.input_feat_per_channel + kwargs["num_mel_bins"] = tiny_config.input_feat_per_channel + to_convert = True + + if to_convert: + feature_extractor = feature_extractor.__class__(**kwargs) + + # Sanity check: on tiny image feature extractors, a large image size results in slow CI -- up to the point where it + # can result in timeout issues. + if ( + isinstance(feature_extractor, BaseImageProcessor) + and hasattr(feature_extractor, "size") + and isinstance(feature_extractor.size, dict) + ): + largest_image_size = max(feature_extractor.size.values()) + if largest_image_size > 64: + # hardcoded exceptions + models_with_large_image_size = ("deformable_detr", "flava", "grounding_dino", "mgp_str", "swiftformer") + if any(model_name in tiny_config.model_type for model_name in models_with_large_image_size): + pass + else: + raise ValueError( + f"Image size of {tiny_config.model_type} is too large ({feature_extractor.size}). " + "Please reduce it to 64 or less on each dimension. The following steps are usually the " + "easiest solution: 1) confirm that you're setting `image_size` in your ModelTester class; " + "2) ensure that it gets passed to the tester config init, `get_config()`." + ) + + return feature_extractor + + +def convert_processors(processors, tiny_config, output_folder, result): + """Change a processor to work with smaller inputs. + + For tokenizers, we try to reduce their vocabulary size. + + For feature extractor, we use smaller image size or change + other attributes using the values from `tiny_config`. See `convert_feature_extractor`. + + This method should not fail: we catch the errors and put them in `result["warnings"]` with descriptive messages. + """ + + def _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False): + """Set tokenizer(s) to `None` if the fast/slow tokenizers have different values for `vocab_size` or `length`. + + If `keep_fast_tokenizer=True`, the fast tokenizer will be kept. + """ + # sanity check 1: fast and slow tokenizers should be compatible (vocab_size) + if fast_tokenizer is not None and slow_tokenizer is not None: + if fast_tokenizer.vocab_size != slow_tokenizer.vocab_size: + warning_message = ( + "The fast/slow tokenizers " + f"({fast_tokenizer.__class__.__name__}/{slow_tokenizer.__class__.__name__}) have different " + "vocabulary size: " + f"fast_tokenizer.vocab_size = {fast_tokenizer.vocab_size} and " + f"slow_tokenizer.vocab_size = {slow_tokenizer.vocab_size}." + ) + result["warnings"].append(warning_message) + if not keep_fast_tokenizer: + fast_tokenizer = None + slow_tokenizer = None + + # sanity check 2: fast and slow tokenizers should be compatible (length) + if fast_tokenizer is not None and slow_tokenizer is not None: + if len(fast_tokenizer) != len(slow_tokenizer): + warning_message = ( + f"The fast/slow tokenizers () have different length: " + f"len(fast_tokenizer) = {len(fast_tokenizer)} and " + f"len(slow_tokenizer) = {len(slow_tokenizer)}." + ) + result["warnings"].append(warning_message) + if not keep_fast_tokenizer: + fast_tokenizer = None + slow_tokenizer = None + + return fast_tokenizer, slow_tokenizer + + tokenizers = [] + feature_extractors = [] + for processor in processors: + if isinstance(processor, PreTrainedTokenizerBase): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}: + tokenizers.append(processor) + elif isinstance(processor, BaseImageProcessor): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}: + feature_extractors.append(processor) + elif isinstance(processor, FeatureExtractionMixin): + if processor.__class__.__name__ not in {x.__class__.__name__ for x in feature_extractors}: + feature_extractors.append(processor) + elif isinstance(processor, ProcessorMixin): + if hasattr(processor, "tokenizer"): + if processor.tokenizer.__class__.__name__ not in {x.__class__.__name__ for x in tokenizers}: + tokenizers.append(processor.tokenizer) + # Currently, we only have these 2 possibilities + if hasattr(processor, "image_processor"): + if processor.image_processor.__class__.__name__ not in { + x.__class__.__name__ for x in feature_extractors + }: + feature_extractors.append(processor.image_processor) + elif hasattr(processor, "feature_extractor"): + if processor.feature_extractor.__class__.__name__ not in { + x.__class__.__name__ for x in feature_extractors + }: + feature_extractors.append(processor.feature_extractor) + + # check the built processors have the unique type + num_types = len({x.__class__.__name__ for x in feature_extractors}) + if num_types >= 2: + raise ValueError(f"`feature_extractors` should contain at most 1 type, but it contains {num_types} types!") + num_types = len({x.__class__.__name__.replace("Fast", "") for x in tokenizers}) + if num_types >= 2: + raise ValueError(f"`tokenizers` should contain at most 1 tokenizer type, but it contains {num_types} types!") + + fast_tokenizer = None + slow_tokenizer = None + + for tokenizer in tokenizers: + if isinstance(tokenizer, PreTrainedTokenizerFast): + fast_tokenizer = tokenizer + else: + slow_tokenizer = tokenizer + + # If the (original) fast/slow tokenizers don't correspond, keep only the fast tokenizer. + # This doesn't necessarily imply the fast/slow tokenizers in a single Hub repo. has issues. + # It's more of an issue in `build_processor` which tries to get a checkpoint with as much effort as possible. + # For `YosoModel` (which uses `AlbertTokenizer(Fast)`), its real (Hub) checkpoint doesn't contain valid files to + # load the slower tokenizer (`AlbertTokenizer`), and it ends up finding the (canonical) checkpoint of `AlbertModel`, + # which has different vocabulary. + # TODO: Try to improve `build_processor`'s definition and/or usage to avoid the above situation in the first place. + fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=True) + original_fast_tokenizer, original_slow_tokenizer = fast_tokenizer, slow_tokenizer + + if fast_tokenizer: + try: + # Wav2Vec2ForCTC , ByT5Tokenizer etc. all are already small enough and have no fast version that can + # be retrained + if fast_tokenizer.vocab_size > TARGET_VOCAB_SIZE: + fast_tokenizer = convert_tokenizer(fast_tokenizer) + except Exception: + result["warnings"].append( + ( + f"Failed to convert the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + + # If `fast_tokenizer` exists, `slow_tokenizer` should correspond to it. + if fast_tokenizer: + # Make sure the fast tokenizer can be saved + try: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + fast_tokenizer.save_pretrained(tmpdir) + try: + slow_tokenizer = AutoTokenizer.from_pretrained(tmpdir, use_fast=False) + except Exception: + result["warnings"].append( + ( + f"Failed to load the slow tokenizer saved from {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + # Let's just keep the fast version + slow_tokenizer = None + except Exception: + result["warnings"].append( + ( + f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + fast_tokenizer = None + + # If the (possibly converted) fast/slow tokenizers don't correspond, set them to `None`, and use the original + # tokenizers. + fast_tokenizer, slow_tokenizer = _sanity_check(fast_tokenizer, slow_tokenizer, keep_fast_tokenizer=False) + + # If there is any conversion failed, we keep the original tokenizers. + if (original_fast_tokenizer is not None and fast_tokenizer is None) or ( + original_slow_tokenizer is not None and slow_tokenizer is None + ): + warning_messagae = ( + "There are some issues when converting the fast/slow tokenizers. The original tokenizers from the Hub " + " will be used instead." + ) + result["warnings"].append(warning_messagae) + # Let's use the original version at the end (`original_fast_tokenizer` and `original_slow_tokenizer`) + fast_tokenizer = original_fast_tokenizer + slow_tokenizer = original_slow_tokenizer + + # Make sure the fast tokenizer can be saved + if fast_tokenizer: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + try: + fast_tokenizer.save_pretrained(tmpdir) + except Exception: + result["warnings"].append( + ( + f"Failed to save the fast tokenizer for {fast_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + fast_tokenizer = None + # Make sure the slow tokenizer can be saved + if slow_tokenizer: + # We don't save it to `output_folder` at this moment - only at the end of this function. + with tempfile.TemporaryDirectory() as tmpdir: + try: + slow_tokenizer.save_pretrained(tmpdir) + except Exception: + result["warnings"].append( + ( + f"Failed to save the slow tokenizer for {slow_tokenizer.__class__.__name__}.", + traceback.format_exc(), + ) + ) + slow_tokenizer = None + + # update feature extractors using the tiny config + try: + feature_extractors = [convert_feature_extractor(p, tiny_config) for p in feature_extractors] + except Exception: + result["warnings"].append( + ( + "Failed to convert feature extractors.", + traceback.format_exc(), + ) + ) + feature_extractors = [] + + if hasattr(tiny_config, "max_position_embeddings") and tiny_config.max_position_embeddings > 0: + if fast_tokenizer is not None: + if fast_tokenizer.__class__.__name__ in [ + "RobertaTokenizerFast", + "XLMRobertaTokenizerFast", + "LongformerTokenizerFast", + "MPNetTokenizerFast", + ]: + fast_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2 + else: + fast_tokenizer.model_max_length = tiny_config.max_position_embeddings + if slow_tokenizer is not None: + if slow_tokenizer.__class__.__name__ in [ + "RobertaTokenizer", + "XLMRobertaTokenizer", + "LongformerTokenizer", + "MPNetTokenizer", + ]: + slow_tokenizer.model_max_length = tiny_config.max_position_embeddings - 2 + else: + slow_tokenizer.model_max_length = tiny_config.max_position_embeddings + + processors = [fast_tokenizer, slow_tokenizer] + feature_extractors + processors = [p for p in processors if p is not None] + for p in processors: + p.save_pretrained(output_folder) + + return processors + + +def get_checkpoint_dir(output_dir, model_arch): + """Get framework-agnostic architecture name. Used to save all PT/TF/Flax models into the same directory.""" + + arch_name = model_arch.__name__ + if arch_name.startswith("TF"): + arch_name = arch_name[2:] + elif arch_name.startswith("Flax"): + arch_name = arch_name[4:] + + return os.path.join(output_dir, arch_name) + + +def build_model(model_arch, tiny_config, output_dir): + """Create and save a model for `model_arch`. + + Also copy the set of processors to each model (under the same model type) output folder. + """ + + checkpoint_dir = get_checkpoint_dir(output_dir, model_arch) + + processor_output_dir = os.path.join(output_dir, "processors") + # copy the (same set of) processors (for a model type) to the model arch. specific folder + if os.path.isdir(processor_output_dir): + shutil.copytree(processor_output_dir, checkpoint_dir, dirs_exist_ok=True) + + tiny_config = copy.deepcopy(tiny_config) + + if any(model_arch.__name__.endswith(x) for x in ["ForCausalLM", "LMHeadModel"]): + tiny_config.is_encoder_decoder = False + tiny_config.is_decoder = True + + model = model_arch(config=tiny_config) + model.save_pretrained(checkpoint_dir) + model.from_pretrained(checkpoint_dir) + + return model + + +def fill_result_with_error(result, error, trace, models_to_create): + """Fill `result` with errors for all target model arch if we can't build processor""" + error = (error, trace) + result["error"] = error + for framework in FRAMEWORKS: + if framework in models_to_create: + result[framework] = {} + for model_arch in models_to_create[framework]: + result[framework][model_arch.__name__] = {"model": None, "checkpoint": None, "error": error} + + result["processor"] = {p.__class__.__name__: p.__class__.__name__ for p in result["processor"].values()} + + +def upload_model(model_dir, organization, token): + """Upload the tiny models""" + + arch_name = model_dir.split(os.path.sep)[-1] + repo_name = f"tiny-random-{arch_name}" + repo_id = f"{organization}/{repo_name}" + + repo_exist = False + error = None + try: + create_repo(repo_id=repo_id, exist_ok=False, repo_type="model", token=token) + except Exception as e: + error = e + if "You already created" in str(e): + error = None + logger.warning("Remote repository exists and will be cloned.") + repo_exist = True + try: + create_repo(repo_id=repo_id, exist_ok=True, repo_type="model", token=token) + except Exception as e: + error = e + if error is not None: + raise error + + with tempfile.TemporaryDirectory() as tmpdir: + repo = Repository(local_dir=tmpdir, clone_from=repo_id, token=token) + repo.git_pull() + shutil.copytree(model_dir, tmpdir, dirs_exist_ok=True) + + if repo_exist: + # Open a PR on the existing Hub repo. + hub_pr_url = upload_folder( + folder_path=model_dir, + repo_id=repo_id, + repo_type="model", + commit_message=f"Update tiny models for {arch_name}", + commit_description=f"Upload tiny models for {arch_name}", + create_pr=True, + token=token, + ) + logger.warning(f"PR open in {hub_pr_url}.") + # TODO: We need this information? + else: + # Push to Hub repo directly + repo.git_add(auto_lfs_track=True) + repo.git_commit(f"Upload tiny models for {arch_name}") + repo.git_push(blocking=True) # this prints a progress bar with the upload + logger.warning(f"Tiny models {arch_name} pushed to {repo_id}.") + + +def build_composite_models(config_class, output_dir): + import tempfile + + from transformers import ( + BertConfig, + BertLMHeadModel, + BertModel, + BertTokenizer, + BertTokenizerFast, + EncoderDecoderModel, + GPT2Config, + GPT2LMHeadModel, + GPT2Tokenizer, + GPT2TokenizerFast, + SpeechEncoderDecoderModel, + TFEncoderDecoderModel, + TFVisionEncoderDecoderModel, + TFVisionTextDualEncoderModel, + VisionEncoderDecoderModel, + VisionTextDualEncoderModel, + ViTConfig, + ViTFeatureExtractor, + ViTModel, + Wav2Vec2Config, + Wav2Vec2Model, + Wav2Vec2Processor, + ) + + # These will be removed at the end if they are empty + result = {"error": None, "warnings": []} + + if config_class.model_type == "encoder-decoder": + encoder_config_class = BertConfig + decoder_config_class = BertConfig + encoder_processor = (BertTokenizerFast, BertTokenizer) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = BertModel + decoder_class = BertLMHeadModel + model_class = EncoderDecoderModel + tf_model_class = TFEncoderDecoderModel + elif config_class.model_type == "vision-encoder-decoder": + encoder_config_class = ViTConfig + decoder_config_class = GPT2Config + encoder_processor = (ViTFeatureExtractor,) + decoder_processor = (GPT2TokenizerFast, GPT2Tokenizer) + encoder_class = ViTModel + decoder_class = GPT2LMHeadModel + model_class = VisionEncoderDecoderModel + tf_model_class = TFVisionEncoderDecoderModel + elif config_class.model_type == "speech-encoder-decoder": + encoder_config_class = Wav2Vec2Config + decoder_config_class = BertConfig + encoder_processor = (Wav2Vec2Processor,) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = Wav2Vec2Model + decoder_class = BertLMHeadModel + model_class = SpeechEncoderDecoderModel + tf_model_class = None + elif config_class.model_type == "vision-text-dual-encoder": + # Not encoder-decoder, but encoder-encoder. We just keep the same name as above to make code easier + encoder_config_class = ViTConfig + decoder_config_class = BertConfig + encoder_processor = (ViTFeatureExtractor,) + decoder_processor = (BertTokenizerFast, BertTokenizer) + encoder_class = ViTModel + decoder_class = BertModel + model_class = VisionTextDualEncoderModel + tf_model_class = TFVisionTextDualEncoderModel + + with tempfile.TemporaryDirectory() as tmpdir: + try: + # build encoder + models_to_create = {"processor": encoder_processor, "pytorch": (encoder_class,), "tensorflow": []} + encoder_output_dir = os.path.join(tmpdir, "encoder") + build(encoder_config_class, models_to_create, encoder_output_dir) + + # build decoder + models_to_create = {"processor": decoder_processor, "pytorch": (decoder_class,), "tensorflow": []} + decoder_output_dir = os.path.join(tmpdir, "decoder") + build(decoder_config_class, models_to_create, decoder_output_dir) + + # build encoder-decoder + encoder_path = os.path.join(encoder_output_dir, encoder_class.__name__) + decoder_path = os.path.join(decoder_output_dir, decoder_class.__name__) + + if config_class.model_type != "vision-text-dual-encoder": + # Specify these explicitly for encoder-decoder like models, but not for `vision-text-dual-encoder` as it + # has no decoder. + decoder_config = decoder_config_class.from_pretrained(decoder_path) + decoder_config.is_decoder = True + decoder_config.add_cross_attention = True + model = model_class.from_encoder_decoder_pretrained( + encoder_path, + decoder_path, + decoder_config=decoder_config, + ) + elif config_class.model_type == "vision-text-dual-encoder": + model = model_class.from_vision_text_pretrained(encoder_path, decoder_path) + + model_path = os.path.join( + output_dir, + f"{model_class.__name__}-{encoder_config_class.model_type}-{decoder_config_class.model_type}", + ) + model.save_pretrained(model_path) + + if tf_model_class is not None: + model = tf_model_class.from_pretrained(model_path) + model.save_pretrained(model_path) + + # copy the processors + encoder_processor_path = os.path.join(encoder_output_dir, "processors") + decoder_processor_path = os.path.join(decoder_output_dir, "processors") + if os.path.isdir(encoder_processor_path): + shutil.copytree(encoder_processor_path, model_path, dirs_exist_ok=True) + if os.path.isdir(decoder_processor_path): + shutil.copytree(decoder_processor_path, model_path, dirs_exist_ok=True) + + # fill `result` + result["processor"] = {x.__name__: x.__name__ for x in encoder_processor + decoder_processor} + + result["pytorch"] = {model_class.__name__: {"model": model_class.__name__, "checkpoint": model_path}} + + result["tensorflow"] = {} + if tf_model_class is not None: + result["tensorflow"] = { + tf_model_class.__name__: {"model": tf_model_class.__name__, "checkpoint": model_path} + } + except Exception: + result["error"] = ( + f"Failed to build models for {config_class.__name__}.", + traceback.format_exc(), + ) + + if not result["error"]: + del result["error"] + if not result["warnings"]: + del result["warnings"] + + return result + + +def get_token_id_from_tokenizer(token_id_name, tokenizer, original_token_id): + """Use `tokenizer` to get the values of `bos_token_id`, `eos_token_ids`, etc. + + The argument `token_id_name` should be a string ending with `_token_id`, and `original_token_id` should be an + integer that will be return if `tokenizer` has no token corresponding to `token_id_name`. + """ + + token_id = original_token_id + + if not token_id_name.endswith("_token_id"): + raise ValueError(f"`token_id_name` is {token_id_name}, which doesn't end with `_token_id`!") + + token = getattr(tokenizer, token_id_name.replace("_token_id", "_token"), None) + if token is not None: + if isinstance(tokenizer, PreTrainedTokenizerFast): + token_id = tokenizer._convert_token_to_id_with_added_voc(token) + else: + token_id = tokenizer._convert_token_to_id(token) + + return token_id + + +def get_config_overrides(config_class, processors): + # `Bark` configuration is too special. Let's just not handle this for now. + if config_class.__name__ == "BarkConfig": + return {} + + config_overrides = {} + + # Check if there is any tokenizer (prefer fast version if any) + tokenizer = None + for processor in processors: + if isinstance(processor, PreTrainedTokenizerFast): + tokenizer = processor + break + elif isinstance(processor, PreTrainedTokenizer): + tokenizer = processor + + if tokenizer is None: + return config_overrides + + # Get some properties of the (already converted) tokenizer (smaller vocab size, special token ids, etc.) + # We use `len(tokenizer)` instead of `tokenizer.vocab_size` to avoid potential issues for tokenizers with non-empty + # `added_tokens_encoder`. One example is the `DebertaV2Tokenizer` where the mask token is the extra token. + vocab_size = len(tokenizer) + + # The original checkpoint has length `35998`, but it doesn't have ids `30400` and `30514` but instead `35998` and + # `35999`. + if config_class.__name__ == "GPTSanJapaneseConfig": + vocab_size += 2 + + config_overrides["vocab_size"] = vocab_size + + # Used to create a new model tester with `tokenizer.vocab_size` in order to get the (updated) special token ids. + model_tester_kwargs = {"vocab_size": vocab_size} + # `FSMTModelTester` accepts `src_vocab_size` and `tgt_vocab_size` but not `vocab_size`. + if config_class.__name__ == "FSMTConfig": + del model_tester_kwargs["vocab_size"] + model_tester_kwargs["src_vocab_size"] = tokenizer.src_vocab_size + model_tester_kwargs["tgt_vocab_size"] = tokenizer.tgt_vocab_size + + _tiny_config = get_tiny_config(config_class, **model_tester_kwargs) + + # handle the possibility of `text_config` inside `_tiny_config` for clip-like models (`owlvit`, `groupvit`, etc.) + if hasattr(_tiny_config, "text_config"): + _tiny_config = _tiny_config.text_config + + # Collect values of some special token ids + for attr in dir(_tiny_config): + if attr.endswith("_token_id"): + token_id = getattr(_tiny_config, attr) + if token_id is not None: + # Using the token id values from `tokenizer` instead of from `_tiny_config`. + token_id = get_token_id_from_tokenizer(attr, tokenizer, original_token_id=token_id) + config_overrides[attr] = token_id + + if config_class.__name__ == "FSMTConfig": + config_overrides["src_vocab_size"] = tokenizer.src_vocab_size + config_overrides["tgt_vocab_size"] = tokenizer.tgt_vocab_size + # `FSMTConfig` has `DecoderConfig` as `decoder` attribute. + config_overrides["decoder"] = configuration_fsmt.DecoderConfig( + vocab_size=tokenizer.tgt_vocab_size, bos_token_id=config_overrides["eos_token_id"] + ) + + return config_overrides + + +def build(config_class, models_to_create, output_dir): + """Create all models for a certain model type. + + Args: + config_class (`PretrainedConfig`): + A subclass of `PretrainedConfig` that is used to determine `models_to_create`. + models_to_create (`dict`): + A dictionary containing the processor/model classes that we want to create the instances. These models are + of the same model type which is associated to `config_class`. + output_dir (`str`): + The directory to save all the checkpoints. Each model architecture will be saved in a subdirectory under + it. Models in different frameworks with the same architecture will be saved in the same subdirectory. + """ + if data["training_ds"] is None or data["testing_ds"] is None: + ds = load_dataset("Salesforce/wikitext", "wikitext-2-raw-v1") + data["training_ds"] = ds["train"] + data["testing_ds"] = ds["test"] + + if config_class.model_type in [ + "encoder-decoder", + "vision-encoder-decoder", + "speech-encoder-decoder", + "vision-text-dual-encoder", + ]: + return build_composite_models(config_class, output_dir) + + result = {k: {} for k in models_to_create} + + # These will be removed at the end if they are empty + result["error"] = None + result["warnings"] = [] + + # Build processors + processor_classes = models_to_create["processor"] + + if len(processor_classes) == 0: + error = f"No processor class could be found in {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + for processor_class in processor_classes: + try: + processor = build_processor(config_class, processor_class, allow_no_checkpoint=True) + if processor is not None: + result["processor"][processor_class] = processor + except Exception: + error = f"Failed to build processor for {processor_class.__name__}." + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + if len(result["processor"]) == 0: + error = f"No processor could be built for {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + try: + tiny_config = get_tiny_config(config_class) + except Exception as e: + error = f"Failed to get tiny config for {config_class.__name__}: {e}" + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + # Convert the processors (reduce vocabulary size, smaller image size, etc.) + processors = list(result["processor"].values()) + processor_output_folder = os.path.join(output_dir, "processors") + try: + processors = convert_processors(processors, tiny_config, processor_output_folder, result) + except Exception: + error = "Failed to convert the processors." + trace = traceback.format_exc() + result["warnings"].append((error, trace)) + + if len(processors) == 0: + error = f"No processor is returned by `convert_processors` for {config_class.__name__}." + fill_result_with_error(result, error, None, models_to_create) + logger.error(result["error"][0]) + return result + + try: + config_overrides = get_config_overrides(config_class, processors) + except Exception as e: + error = f"Failure occurs while calling `get_config_overrides`: {e}" + trace = traceback.format_exc() + fill_result_with_error(result, error, trace, models_to_create) + logger.error(result["error"][0]) + return result + + # Just for us to see this easily in the report + if "vocab_size" in config_overrides: + result["vocab_size"] = config_overrides["vocab_size"] + + # Update attributes that `vocab_size` involves + for k, v in config_overrides.items(): + if hasattr(tiny_config, k): + setattr(tiny_config, k, v) + # So far, we only have to deal with `text_config`, as `config_overrides` contains text-related attributes only. + # `FuyuConfig` saves data under both FuyuConfig and its `text_config`. This is not good, but let's just update + # every involved fields to avoid potential failure. + if ( + hasattr(tiny_config, "text_config") + and tiny_config.text_config is not None + and hasattr(tiny_config.text_config, k) + ): + setattr(tiny_config.text_config, k, v) + # If `text_config_dict` exists, we need to update its value here too in order to # make + # `save_pretrained -> from_pretrained` work. + if hasattr(tiny_config, "text_config_dict"): + tiny_config.text_config_dict[k] = v + + if result["warnings"]: + logger.warning(result["warnings"][0][0]) + + # update `result["processor"]` + result["processor"] = {type(p).__name__: p.__class__.__name__ for p in processors} + + for pytorch_arch in models_to_create["pytorch"]: + result["pytorch"][pytorch_arch.__name__] = {} + error = None + try: + model = build_model(pytorch_arch, tiny_config, output_dir=output_dir) + except Exception as e: + model = None + error = f"Failed to create the pytorch model for {pytorch_arch}: {e}" + trace = traceback.format_exc() + + result["pytorch"][pytorch_arch.__name__]["model"] = model.__class__.__name__ if model is not None else None + result["pytorch"][pytorch_arch.__name__]["checkpoint"] = ( + get_checkpoint_dir(output_dir, pytorch_arch) if model is not None else None + ) + if error is not None: + result["pytorch"][pytorch_arch.__name__]["error"] = (error, trace) + logger.error(f"{pytorch_arch.__name__}: {error}") + + for tensorflow_arch in models_to_create["tensorflow"]: + # Make PT/TF weights compatible + pt_arch_name = tensorflow_arch.__name__[2:] # Remove `TF` + pt_arch = getattr(transformers_module, pt_arch_name) + + result["tensorflow"][tensorflow_arch.__name__] = {} + error = None + if pt_arch.__name__ in result["pytorch"] and result["pytorch"][pt_arch.__name__]["checkpoint"] is not None: + ckpt = get_checkpoint_dir(output_dir, pt_arch) + # Use the same weights from PyTorch. + try: + model = tensorflow_arch.from_pretrained(ckpt) + model.save_pretrained(ckpt) + except Exception as e: + # Conversion may fail. Let's not create a model with different weights to avoid confusion (for now). + model = None + error = f"Failed to convert the pytorch model to the tensorflow model for {pt_arch}: {e}" + trace = traceback.format_exc() + else: + try: + model = build_model(tensorflow_arch, tiny_config, output_dir=output_dir) + except Exception as e: + model = None + error = f"Failed to create the tensorflow model for {tensorflow_arch}: {e}" + trace = traceback.format_exc() + + result["tensorflow"][tensorflow_arch.__name__]["model"] = ( + model.__class__.__name__ if model is not None else None + ) + result["tensorflow"][tensorflow_arch.__name__]["checkpoint"] = ( + get_checkpoint_dir(output_dir, tensorflow_arch) if model is not None else None + ) + if error is not None: + result["tensorflow"][tensorflow_arch.__name__]["error"] = (error, trace) + logger.error(f"{tensorflow_arch.__name__}: {error}") + + if not result["error"]: + del result["error"] + if not result["warnings"]: + del result["warnings"] + + return result + + +def build_tiny_model_summary(results, organization=None, token=None): + """Build a summary: a dictionary of the form + { + model architecture name: + { + "tokenizer_classes": [...], + "processor_classes": [...], + "model_classes": [...], + } + .. + } + """ + tiny_model_summary = {} + for config_name in results: + processors = [key for key, value in results[config_name]["processor"].items()] + tokenizer_classes = sorted([x for x in processors if x.endswith("TokenizerFast") or x.endswith("Tokenizer")]) + processor_classes = sorted([x for x in processors if x not in tokenizer_classes]) + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + model_classes = [arch_name] + base_arch_name = arch_name[2:] if arch_name.startswith("TF") else arch_name + # tiny model is not created for `arch_name` + if results[config_name][framework][arch_name]["model"] is None: + model_classes = [] + if base_arch_name not in tiny_model_summary: + tiny_model_summary[base_arch_name] = {} + tiny_model_summary[base_arch_name].update( + { + "tokenizer_classes": tokenizer_classes, + "processor_classes": processor_classes, + } + ) + tiny_model_summary[base_arch_name]["model_classes"] = sorted( + tiny_model_summary[base_arch_name].get("model_classes", []) + model_classes + ) + if organization is not None: + repo_name = f"tiny-random-{base_arch_name}" + # composite models' checkpoints have more precise repo. names on the Hub. + if base_arch_name in COMPOSITE_MODELS: + repo_name = f"tiny-random-{COMPOSITE_MODELS[base_arch_name]}" + repo_id = f"{organization}/{repo_name}" + try: + commit_hash = hf_api.repo_info(repo_id, token=token).sha + except Exception: + # The directory is not created, but processor(s) is/are included in `results`. + logger.warning(f"Failed to get information for {repo_id}.\n{traceback.format_exc()}") + del tiny_model_summary[base_arch_name] + continue + tiny_model_summary[base_arch_name]["sha"] = commit_hash + + return tiny_model_summary + + +def build_failed_report(results, include_warning=True): + failed_results = {} + for config_name in results: + if "error" in results[config_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + failed_results[config_name] = {"error": results[config_name]["error"]} + + if include_warning and "warnings" in results[config_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + failed_results[config_name]["warnings"] = results[config_name]["warnings"] + + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + if "error" in results[config_name][framework][arch_name]: + if config_name not in failed_results: + failed_results[config_name] = {} + if framework not in failed_results[config_name]: + failed_results[config_name][framework] = {} + if arch_name not in failed_results[config_name][framework]: + failed_results[config_name][framework][arch_name] = {} + error = results[config_name][framework][arch_name]["error"] + failed_results[config_name][framework][arch_name]["error"] = error + + return failed_results + + +def build_simple_report(results): + text = "" + failed_text = "" + for config_name in results: + for framework in FRAMEWORKS: + if framework not in results[config_name]: + continue + for arch_name in results[config_name][framework]: + if "error" in results[config_name][framework][arch_name]: + result = results[config_name][framework][arch_name]["error"] + failed_text += f"{arch_name}: {result[0]}\n" + else: + result = ("OK",) + text += f"{arch_name}: {result[0]}\n" + + return text, failed_text + + +def update_tiny_model_summary_file(report_path): + with open(os.path.join(report_path, "tiny_model_summary.json")) as fp: + new_data = json.load(fp) + with open("tests/utils/tiny_model_summary.json") as fp: + data = json.load(fp) + for key, value in new_data.items(): + if key not in data: + data[key] = value + else: + for attr in ["tokenizer_classes", "processor_classes", "model_classes"]: + # we might get duplication here. We will remove them below when creating `updated_data`. + data[key][attr].extend(value[attr]) + new_sha = value.get("sha", None) + if new_sha is not None: + data[key]["sha"] = new_sha + + updated_data = {} + for key in sorted(data.keys()): + updated_data[key] = {} + for attr, value in data[key].items(): + # deduplication and sort + updated_data[key][attr] = sorted(set(value)) if attr != "sha" else value + + with open(os.path.join(report_path, "updated_tiny_model_summary.json"), "w") as fp: + json.dump(updated_data, fp, indent=4, ensure_ascii=False) + + +def create_tiny_models( + output_path, + all, + model_types, + models_to_skip, + no_check, + upload, + organization, + token, + num_workers=1, +): + clone_path = os.path.abspath(os.path.dirname(os.path.dirname(__file__))) + if os.getcwd() != clone_path: + raise ValueError(f"This script should be run from the root of the clone of `transformers` {clone_path}") + + report_path = os.path.join(output_path, "reports") + os.makedirs(report_path, exist_ok=True) + + _pytorch_arch_mappings = [ + x + for x in dir(transformers_module) + if x.startswith("MODEL_") and x.endswith("_MAPPING") and x != "MODEL_NAMES_MAPPING" + ] + _tensorflow_arch_mappings = [ + x for x in dir(transformers_module) if x.startswith("TF_MODEL_") and x.endswith("_MAPPING") + ] + + pytorch_arch_mappings = [getattr(transformers_module, x) for x in _pytorch_arch_mappings] + tensorflow_arch_mappings = [getattr(transformers_module, x) for x in _tensorflow_arch_mappings] + + config_classes = CONFIG_MAPPING.values() + if not all: + config_classes = [CONFIG_MAPPING[model_type] for model_type in model_types] + + # A map from config classes to tuples of processors (tokenizer, feature extractor, processor) classes + processor_type_map = {c: get_processor_types_from_config_class(c) for c in config_classes} + + to_create = {} + for c in config_classes: + processors = processor_type_map[c] + models = get_architectures_from_config_class(c, pytorch_arch_mappings, models_to_skip) + tf_models = get_architectures_from_config_class(c, tensorflow_arch_mappings, models_to_skip) + if len(models) + len(tf_models) > 0: + to_create[c] = {"processor": processors, "pytorch": models, "tensorflow": tf_models} + + results = {} + if num_workers <= 1: + for c, models_to_create in list(to_create.items()): + print(f"Create models for {c.__name__} ...") + result = build(c, models_to_create, output_dir=os.path.join(output_path, c.model_type)) + results[c.__name__] = result + print("=" * 40) + else: + all_build_args = [] + for c, models_to_create in list(to_create.items()): + all_build_args.append((c, models_to_create, os.path.join(output_path, c.model_type))) + with multiprocessing.Pool() as pool: + results = pool.starmap(build, all_build_args) + results = {buid_args[0].__name__: result for buid_args, result in zip(all_build_args, results)} + + if upload: + if organization is None: + raise ValueError("The argument `organization` could not be `None`. No model is uploaded") + + to_upload = [] + for model_type in os.listdir(output_path): + # This is the directory containing the reports + if model_type == "reports": + continue + for arch in os.listdir(os.path.join(output_path, model_type)): + if arch == "processors": + continue + to_upload.append(os.path.join(output_path, model_type, arch)) + to_upload = sorted(to_upload) + + upload_results = {} + if len(to_upload) > 0: + for model_dir in to_upload: + try: + upload_model(model_dir, organization, token) + except Exception as e: + error = f"Failed to upload {model_dir}. {e.__class__.__name__}: {e}" + logger.error(error) + upload_results[model_dir] = error + + with open(os.path.join(report_path, "failed_uploads.json"), "w") as fp: + json.dump(upload_results, fp, indent=4) + + # Build the tiny model summary file. The `tokenizer_classes` and `processor_classes` could be both empty lists. + # When using the items in this file to update the file `tests/utils/tiny_model_summary.json`, the model + # architectures with `tokenizer_classes` and `processor_classes` being both empty should **NOT** be added to + # `tests/utils/tiny_model_summary.json`. + tiny_model_summary = build_tiny_model_summary(results, organization=organization, token=token) + with open(os.path.join(report_path, "tiny_model_summary.json"), "w") as fp: + json.dump(tiny_model_summary, fp, indent=4) + + with open(os.path.join(report_path, "tiny_model_creation_report.json"), "w") as fp: + json.dump(results, fp, indent=4) + + # Build the warning/failure report (json format): same format as the complete `results` except this contains only + # warnings or errors. + failed_results = build_failed_report(results) + with open(os.path.join(report_path, "failed_report.json"), "w") as fp: + json.dump(failed_results, fp, indent=4) + + simple_report, failed_report = build_simple_report(results) + # The simplified report: a .txt file with each line of format: + # {model architecture name}: {OK or error message} + with open(os.path.join(report_path, "simple_report.txt"), "w") as fp: + fp.write(simple_report) + + # The simplified failure report: same above except this only contains line with errors + with open(os.path.join(report_path, "simple_failed_report.txt"), "w") as fp: + fp.write(failed_report) + + update_tiny_model_summary_file(report_path=os.path.join(output_path, "reports")) + + +if __name__ == "__main__": + # This has to be `spawn` to avoid hanging forever! + multiprocessing.set_start_method("spawn") + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + parser.add_argument("--all", action="store_true", help="Will create all tiny models.") + parser.add_argument( + "--no_check", + action="store_true", + help="If set, will not check the validity of architectures. Use with caution.", + ) + parser.add_argument( + "-m", + "--model_types", + type=list_str, + help="Comma-separated list of model type(s) from which the tiny models will be created.", + ) + parser.add_argument( + "--models_to_skip", + type=list_str, + help=( + "Comma-separated list of model class names(s) from which the tiny models won't be created.\nThis is usually " + "the list of model classes that have their tiny versions already uploaded to the Hub." + ), + ) + parser.add_argument("--upload", action="store_true", help="If to upload the created tiny models to the Hub.") + parser.add_argument( + "--organization", + default=None, + type=str, + help="The organization on the Hub to which the tiny models will be uploaded.", + ) + parser.add_argument( + "--token", default=None, type=str, help="A valid authentication token for HuggingFace Hub with write access." + ) + parser.add_argument("output_path", type=Path, help="Path indicating where to store generated model.") + parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.") + + args = parser.parse_args() + + if not args.all and not args.model_types: + raise ValueError("Please provide at least one model type or pass `--all` to export all architectures.") + + create_tiny_models( + args.output_path, + args.all, + args.model_types, + args.models_to_skip, + args.no_check, + args.upload, + args.organization, + args.token, + args.num_workers, + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/custom_init_isort.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/custom_init_isort.py new file mode 100644 index 0000000000000000000000000000000000000000..3d476c809e86db0843a6b943ade9f1b4e0d1e04b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/custom_init_isort.py @@ -0,0 +1,330 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# 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. +""" +Utility that sorts the imports in the custom inits of Transformers. Transformers uses init files that delay the +import of an object to when it's actually needed. This is to avoid the main init importing all models, which would +make the line `import transformers` very slow when the user has all optional dependencies installed. The inits with +delayed imports have two halves: one defining a dictionary `_import_structure` which maps modules to the name of the +objects in each module, and one in `TYPE_CHECKING` which looks like a normal init for type-checkers. `isort` or `ruff` +properly sort the second half which looks like traditionl imports, the goal of this script is to sort the first half. + +Use from the root of the repo with: + +```bash +python utils/custom_init_isort.py +``` + +which will auto-sort the imports (used in `make style`). + +For a check only (as used in `make quality`) run: + +```bash +python utils/custom_init_isort.py --check_only +``` +""" + +import argparse +import os +import re +from typing import Any, Callable, Optional + + +# Path is defined with the intent you should run this script from the root of the repo. +PATH_TO_TRANSFORMERS = "src/transformers" + +# Pattern that looks at the indentation in a line. +_re_indent = re.compile(r"^(\s*)\S") +# Pattern that matches `"key":" and puts `key` in group 0. +_re_direct_key = re.compile(r'^\s*"([^"]+)":') +# Pattern that matches `_import_structure["key"]` and puts `key` in group 0. +_re_indirect_key = re.compile(r'^\s*_import_structure\["([^"]+)"\]') +# Pattern that matches `"key",` and puts `key` in group 0. +_re_strip_line = re.compile(r'^\s*"([^"]+)",\s*$') +# Pattern that matches any `[stuff]` and puts `stuff` in group 0. +_re_bracket_content = re.compile(r"\[([^\]]+)\]") + + +def get_indent(line: str) -> str: + """Returns the indent in given line (as string).""" + search = _re_indent.search(line) + return "" if search is None else search.groups()[0] + + +def split_code_in_indented_blocks( + code: str, indent_level: str = "", start_prompt: Optional[str] = None, end_prompt: Optional[str] = None +) -> list[str]: + """ + Split some code into its indented blocks, starting at a given level. + + Args: + code (`str`): The code to split. + indent_level (`str`): The indent level (as string) to use for identifying the blocks to split. + start_prompt (`str`, *optional*): If provided, only starts splitting at the line where this text is. + end_prompt (`str`, *optional*): If provided, stops splitting at a line where this text is. + + Warning: + The text before `start_prompt` or after `end_prompt` (if provided) is not ignored, just not split. The input `code` + can thus be retrieved by joining the result. + + Returns: + `List[str]`: The list of blocks. + """ + # Let's split the code into lines and move to start_index. + index = 0 + lines = code.split("\n") + if start_prompt is not None: + while not lines[index].startswith(start_prompt): + index += 1 + blocks = ["\n".join(lines[:index])] + else: + blocks = [] + + # This variable contains the block treated at a given time. + current_block = [lines[index]] + index += 1 + # We split into blocks until we get to the `end_prompt` (or the end of the file). + while index < len(lines) and (end_prompt is None or not lines[index].startswith(end_prompt)): + # We have a non-empty line with the proper indent -> start of a new block + if len(lines[index]) > 0 and get_indent(lines[index]) == indent_level: + # Store the current block in the result and rest. There are two cases: the line is part of the block (like + # a closing parenthesis) or not. + if len(current_block) > 0 and get_indent(current_block[-1]).startswith(indent_level + " "): + # Line is part of the current block + current_block.append(lines[index]) + blocks.append("\n".join(current_block)) + if index < len(lines) - 1: + current_block = [lines[index + 1]] + index += 1 + else: + current_block = [] + else: + # Line is not part of the current block + blocks.append("\n".join(current_block)) + current_block = [lines[index]] + else: + # Just add the line to the current block + current_block.append(lines[index]) + index += 1 + + # Adds current block if it's nonempty. + if len(current_block) > 0: + blocks.append("\n".join(current_block)) + + # Add final block after end_prompt if provided. + if end_prompt is not None and index < len(lines): + blocks.append("\n".join(lines[index:])) + + return blocks + + +def ignore_underscore_and_lowercase(key: Callable[[Any], str]) -> Callable[[Any], str]: + """ + Wraps a key function (as used in a sort) to lowercase and ignore underscores. + """ + + def _inner(x): + return key(x).lower().replace("_", "") + + return _inner + + +def sort_objects(objects: list[Any], key: Optional[Callable[[Any], str]] = None) -> list[Any]: + """ + Sort a list of objects following the rules of isort (all uppercased first, camel-cased second and lower-cased + last). + + Args: + objects (`List[Any]`): + The list of objects to sort. + key (`Callable[[Any], str]`, *optional*): + A function taking an object as input and returning a string, used to sort them by alphabetical order. + If not provided, will default to noop (so a `key` must be provided if the `objects` are not of type string). + + Returns: + `List[Any]`: The sorted list with the same elements as in the inputs + """ + + # If no key is provided, we use a noop. + def noop(x): + return x + + if key is None: + key = noop + # Constants are all uppercase, they go first. + constants = [obj for obj in objects if key(obj).isupper()] + # Classes are not all uppercase but start with a capital, they go second. + classes = [obj for obj in objects if key(obj)[0].isupper() and not key(obj).isupper()] + # Functions begin with a lowercase, they go last. + functions = [obj for obj in objects if not key(obj)[0].isupper()] + + # Then we sort each group. + key1 = ignore_underscore_and_lowercase(key) + return sorted(constants, key=key1) + sorted(classes, key=key1) + sorted(functions, key=key1) + + +def sort_objects_in_import(import_statement: str) -> str: + """ + Sorts the imports in a single import statement. + + Args: + import_statement (`str`): The import statement in which to sort the imports. + + Returns: + `str`: The same as the input, but with objects properly sorted. + """ + + # This inner function sort imports between [ ]. + def _replace(match): + imports = match.groups()[0] + # If there is one import only, nothing to do. + if "," not in imports: + return f"[{imports}]" + keys = [part.strip().replace('"', "") for part in imports.split(",")] + # We will have a final empty element if the line finished with a comma. + if len(keys[-1]) == 0: + keys = keys[:-1] + return "[" + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + "]" + + lines = import_statement.split("\n") + if len(lines) > 3: + # Here we have to sort internal imports that are on several lines (one per name): + # key: [ + # "object1", + # "object2", + # ... + # ] + + # We may have to ignore one or two lines on each side. + idx = 2 if lines[1].strip() == "[" else 1 + keys_to_sort = [(i, _re_strip_line.search(line).groups()[0]) for i, line in enumerate(lines[idx:-idx])] + sorted_indices = sort_objects(keys_to_sort, key=lambda x: x[1]) + sorted_lines = [lines[x[0] + idx] for x in sorted_indices] + return "\n".join(lines[:idx] + sorted_lines + lines[-idx:]) + elif len(lines) == 3: + # Here we have to sort internal imports that are on one separate line: + # key: [ + # "object1", "object2", ... + # ] + if _re_bracket_content.search(lines[1]) is not None: + lines[1] = _re_bracket_content.sub(_replace, lines[1]) + else: + keys = [part.strip().replace('"', "") for part in lines[1].split(",")] + # We will have a final empty element if the line finished with a comma. + if len(keys[-1]) == 0: + keys = keys[:-1] + lines[1] = get_indent(lines[1]) + ", ".join([f'"{k}"' for k in sort_objects(keys)]) + return "\n".join(lines) + else: + # Finally we have to deal with imports fitting on one line + import_statement = _re_bracket_content.sub(_replace, import_statement) + return import_statement + + +def sort_imports(file: str, check_only: bool = True): + """ + Sort the imports defined in the `_import_structure` of a given init. + + Args: + file (`str`): The path to the init to check/fix. + check_only (`bool`, *optional*, defaults to `True`): Whether or not to just check (and not auto-fix) the init. + """ + with open(file, encoding="utf-8") as f: + code = f.read() + + # If the file is not a custom init, there is nothing to do. + if "_import_structure" not in code or "define_import_structure" in code: + return + + # Blocks of indent level 0 + main_blocks = split_code_in_indented_blocks( + code, start_prompt="_import_structure = {", end_prompt="if TYPE_CHECKING:" + ) + + # We ignore block 0 (everything untils start_prompt) and the last block (everything after end_prompt). + for block_idx in range(1, len(main_blocks) - 1): + # Check if the block contains some `_import_structure`s thingy to sort. + block = main_blocks[block_idx] + block_lines = block.split("\n") + + # Get to the start of the imports. + line_idx = 0 + while line_idx < len(block_lines) and "_import_structure" not in block_lines[line_idx]: + # Skip dummy import blocks + if "import dummy" in block_lines[line_idx]: + line_idx = len(block_lines) + else: + line_idx += 1 + if line_idx >= len(block_lines): + continue + + # Ignore beginning and last line: they don't contain anything. + internal_block_code = "\n".join(block_lines[line_idx:-1]) + indent = get_indent(block_lines[1]) + # Slit the internal block into blocks of indent level 1. + internal_blocks = split_code_in_indented_blocks(internal_block_code, indent_level=indent) + # We have two categories of import key: list or _import_structure[key].append/extend + pattern = _re_direct_key if "_import_structure = {" in block_lines[0] else _re_indirect_key + # Grab the keys, but there is a trap: some lines are empty or just comments. + keys = [(pattern.search(b).groups()[0] if pattern.search(b) is not None else None) for b in internal_blocks] + # We only sort the lines with a key. + keys_to_sort = [(i, key) for i, key in enumerate(keys) if key is not None] + sorted_indices = [x[0] for x in sorted(keys_to_sort, key=lambda x: x[1])] + + # We reorder the blocks by leaving empty lines/comments as they were and reorder the rest. + count = 0 + reorderded_blocks = [] + for i in range(len(internal_blocks)): + if keys[i] is None: + reorderded_blocks.append(internal_blocks[i]) + else: + block = sort_objects_in_import(internal_blocks[sorted_indices[count]]) + reorderded_blocks.append(block) + count += 1 + + # And we put our main block back together with its first and last line. + main_blocks[block_idx] = "\n".join(block_lines[:line_idx] + reorderded_blocks + [block_lines[-1]]) + + if code != "\n".join(main_blocks): + if check_only: + return True + else: + print(f"Overwriting {file}.") + with open(file, "w", encoding="utf-8") as f: + f.write("\n".join(main_blocks)) + + +def sort_imports_in_all_inits(check_only=True): + """ + Sort the imports defined in the `_import_structure` of all inits in the repo. + + Args: + check_only (`bool`, *optional*, defaults to `True`): Whether or not to just check (and not auto-fix) the init. + """ + failures = [] + for root, _, files in os.walk(PATH_TO_TRANSFORMERS): + if "__init__.py" in files: + result = sort_imports(os.path.join(root, "__init__.py"), check_only=check_only) + if result: + failures = [os.path.join(root, "__init__.py")] + if len(failures) > 0: + raise ValueError(f"Would overwrite {len(failures)} files, run `make style`.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") + args = parser.parse_args() + + sort_imports_in_all_inits(check_only=args.check_only) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/deprecate_models.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/deprecate_models.py new file mode 100644 index 0000000000000000000000000000000000000000..8cbe319fdb65f034ba2e4c228969483efc92a8db --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/deprecate_models.py @@ -0,0 +1,378 @@ +""" +Script which deprecates a list of given models + +Example usage: +python utils/deprecate_models.py --models bert distilbert +""" + +import argparse +import os +from collections import defaultdict +from pathlib import Path +from typing import Optional + +import requests +from custom_init_isort import sort_imports_in_all_inits +from git import Repo +from packaging import version + +from transformers import CONFIG_MAPPING, logging +from transformers import __version__ as current_version + + +REPO_PATH = Path(os.path.abspath(os.path.dirname(os.path.dirname(__file__)))) +repo = Repo(REPO_PATH) + +logger = logging.get_logger(__name__) + + +def get_last_stable_minor_release(): + # Get the last stable release of transformers + url = "https://pypi.org/pypi/transformers/json" + release_data = requests.get(url).json() + + # Find the last stable release of transformers (version below current version) + major_version, minor_version, patch_version, _ = current_version.split(".") + last_major_minor = f"{major_version}.{int(minor_version) - 1}" + last_stable_minor_releases = [ + release for release in release_data["releases"] if release.startswith(last_major_minor) + ] + last_stable_release = sorted(last_stable_minor_releases, key=version.parse)[-1] + + return last_stable_release + + +def build_tip_message(last_stable_release): + return ( + """ + + +This model is in maintenance mode only, we don't accept any new PRs changing its code. +""" + + f"""If you run into any issues running this model, please reinstall the last version that supported this model: v{last_stable_release}. +You can do so by running the following command: `pip install -U transformers=={last_stable_release}`. + +""" + ) + + +def insert_tip_to_model_doc(model_doc_path, tip_message): + tip_message_lines = tip_message.split("\n") + + with open(model_doc_path, "r") as f: + model_doc = f.read() + + # Add the tip message to the model doc page directly underneath the title + lines = model_doc.split("\n") + + new_model_lines = [] + for line in lines: + if line.startswith("# "): + new_model_lines.append(line) + new_model_lines.extend(tip_message_lines) + else: + new_model_lines.append(line) + + with open(model_doc_path, "w") as f: + f.write("\n".join(new_model_lines)) + + +def get_model_doc_path(model: str) -> tuple[Optional[str], Optional[str]]: + # Possible variants of the model name in the model doc path + model_names = [model, model.replace("_", "-"), model.replace("_", "")] + + model_doc_paths = [REPO_PATH / f"docs/source/en/model_doc/{model_name}.md" for model_name in model_names] + + for model_doc_path, model_name in zip(model_doc_paths, model_names): + if os.path.exists(model_doc_path): + return model_doc_path, model_name + + return None, None + + +def extract_model_info(model): + model_info = {} + model_doc_path, model_doc_name = get_model_doc_path(model) + model_path = REPO_PATH / f"src/transformers/models/{model}" + + if model_doc_path is None: + print(f"Model doc path does not exist for {model}") + return None + model_info["model_doc_path"] = model_doc_path + model_info["model_doc_name"] = model_doc_name + + if not os.path.exists(model_path): + print(f"Model path does not exist for {model}") + return None + model_info["model_path"] = model_path + + return model_info + + +def update_relative_imports(filename, model): + with open(filename, "r") as f: + filelines = f.read() + + new_file_lines = [] + for line in filelines.split("\n"): + if line.startswith("from .."): + new_file_lines.append(line.replace("from ..", "from ...")) + else: + new_file_lines.append(line) + + with open(filename, "w") as f: + f.write("\n".join(new_file_lines)) + + +def remove_copied_from_statements(model): + model_path = REPO_PATH / f"src/transformers/models/{model}" + for file in os.listdir(model_path): + if file == "__pycache__": + continue + file_path = model_path / file + with open(file_path, "r") as f: + file_lines = f.read() + + new_file_lines = [] + for line in file_lines.split("\n"): + if "# Copied from" in line: + continue + new_file_lines.append(line) + + with open(file_path, "w") as f: + f.write("\n".join(new_file_lines)) + + +def move_model_files_to_deprecated(model): + model_path = REPO_PATH / f"src/transformers/models/{model}" + deprecated_model_path = REPO_PATH / f"src/transformers/models/deprecated/{model}" + + if not os.path.exists(deprecated_model_path): + os.makedirs(deprecated_model_path) + + for file in os.listdir(model_path): + if file == "__pycache__": + continue + repo.git.mv(f"{model_path}/{file}", f"{deprecated_model_path}/{file}") + + # For deprecated files, we then need to update the relative imports + update_relative_imports(f"{deprecated_model_path}/{file}", model) + + +def delete_model_tests(model): + tests_path = REPO_PATH / f"tests/models/{model}" + + if os.path.exists(tests_path): + repo.git.rm("-r", tests_path) + + +def get_line_indent(s): + return len(s) - len(s.lstrip()) + + +def update_main_init_file(models): + """ + Replace all instances of model.model_name with model.deprecated.model_name in the __init__.py file + + Args: + models (List[str]): The models to mark as deprecated + """ + filename = REPO_PATH / "src/transformers/__init__.py" + with open(filename, "r") as f: + init_file = f.read() + + # 1. For each model, find all the instances of model.model_name and replace with model.deprecated.model_name + for model in models: + init_file = init_file.replace(f'models.{model}"', f'models.deprecated.{model}"') + init_file = init_file.replace(f"models.{model} import", f"models.deprecated.{model} import") + + with open(filename, "w") as f: + f.write(init_file) + + # 2. Resort the imports + sort_imports_in_all_inits(check_only=False) + + +def remove_model_references_from_file(filename, models, condition): + """ + Remove all references to the given models from the given file + + Args: + filename (str): The file to remove the references from + models (List[str]): The models to remove + condition (Callable): A function that takes the line and model and returns True if the line should be removed + """ + filename = REPO_PATH / filename + with open(filename, "r") as f: + init_file = f.read() + + new_file_lines = [] + for i, line in enumerate(init_file.split("\n")): + if any(condition(line, model) for model in models): + continue + new_file_lines.append(line) + + with open(filename, "w") as f: + f.write("\n".join(new_file_lines)) + + +def remove_model_config_classes_from_config_check(model_config_classes): + """ + Remove the deprecated model config classes from the check_config_attributes.py file + + Args: + model_config_classes (List[str]): The model config classes to remove e.g. ["BertConfig", "DistilBertConfig"] + """ + filename = REPO_PATH / "utils/check_config_attributes.py" + with open(filename, "r") as f: + check_config_attributes = f.read() + + # Keep track as we have to delete comment above too + in_special_cases_to_allow = False + in_indent = False + new_file_lines = [] + + for line in check_config_attributes.split("\n"): + indent = get_line_indent(line) + if (line.strip() == "SPECIAL_CASES_TO_ALLOW = {") or (line.strip() == "SPECIAL_CASES_TO_ALLOW.update("): + in_special_cases_to_allow = True + + elif in_special_cases_to_allow and indent == 0 and line.strip() in ("}", ")"): + in_special_cases_to_allow = False + + if in_indent: + if line.strip().endswith(("]", "],")): + in_indent = False + continue + + if in_special_cases_to_allow and any( + model_config_class in line for model_config_class in model_config_classes + ): + # Remove comments above the model config class to remove + while new_file_lines[-1].strip().startswith("#"): + new_file_lines.pop() + + if line.strip().endswith("["): + in_indent = True + + continue + + elif any(model_config_class in line for model_config_class in model_config_classes): + continue + + new_file_lines.append(line) + + with open(filename, "w") as f: + f.write("\n".join(new_file_lines)) + + +def add_models_to_deprecated_models_in_config_auto(models): + """ + Add the models to the DEPRECATED_MODELS list in configuration_auto.py and sorts the list + to be in alphabetical order. + """ + filepath = REPO_PATH / "src/transformers/models/auto/configuration_auto.py" + with open(filepath, "r") as f: + config_auto = f.read() + + new_file_lines = [] + deprecated_models_list = [] + in_deprecated_models = False + for line in config_auto.split("\n"): + if line.strip() == "DEPRECATED_MODELS = [": + in_deprecated_models = True + new_file_lines.append(line) + elif in_deprecated_models and line.strip() == "]": + in_deprecated_models = False + # Add the new models to deprecated models list + deprecated_models_list.extend([f' "{model}", ' for model in models]) + # Sort so they're in alphabetical order in the file + deprecated_models_list = sorted(deprecated_models_list) + new_file_lines.extend(deprecated_models_list) + # Make sure we still have the closing bracket + new_file_lines.append(line) + elif in_deprecated_models: + deprecated_models_list.append(line) + else: + new_file_lines.append(line) + + with open(filepath, "w") as f: + f.write("\n".join(new_file_lines)) + + +def deprecate_models(models): + # Get model info + skipped_models = [] + models_info = defaultdict(dict) + for model in models: + single_model_info = extract_model_info(model) + if single_model_info is None: + skipped_models.append(model) + else: + models_info[model] = single_model_info + + model_config_classes = [] + for model, model_info in models_info.items(): + if model in CONFIG_MAPPING: + model_config_classes.append(CONFIG_MAPPING[model].__name__) + elif model_info["model_doc_name"] in CONFIG_MAPPING: + model_config_classes.append(CONFIG_MAPPING[model_info["model_doc_name"]].__name__) + else: + skipped_models.append(model) + print(f"Model config class not found for model: {model}") + + # Filter out skipped models + models = [model for model in models if model not in skipped_models] + + if skipped_models: + print(f"Skipped models: {skipped_models} as the model doc or model path could not be found.") + print(f"Models to deprecate: {models}") + + # Remove model config classes from config check + print("Removing model config classes from config checks") + remove_model_config_classes_from_config_check(model_config_classes) + + tip_message = build_tip_message(get_last_stable_minor_release()) + + for model, model_info in models_info.items(): + print(f"Processing model: {model}") + # Add the tip message to the model doc page directly underneath the title + print("Adding tip message to model doc page") + insert_tip_to_model_doc(model_info["model_doc_path"], tip_message) + + # Remove #Copied from statements from model's files + print("Removing #Copied from statements from model's files") + remove_copied_from_statements(model) + + # Move the model file to deprecated: src/transformers/models/model -> src/transformers/models/deprecated/model + print("Moving model files to deprecated for model") + move_model_files_to_deprecated(model) + + # Delete the model tests: tests/models/model + print("Deleting model tests") + delete_model_tests(model) + + # # We do the following with all models passed at once to avoid having to re-write the file multiple times + print("Updating __init__.py file to point to the deprecated models") + update_main_init_file(models) + + # Remove model references from other files + print("Removing model references from other files") + remove_model_references_from_file( + "src/transformers/models/__init__.py", models, lambda line, model: model == line.strip().strip(",") + ) + remove_model_references_from_file( + "utils/slow_documentation_tests.txt", models, lambda line, model: "/" + model + "/" in line + ) + remove_model_references_from_file("utils/not_doctested.txt", models, lambda line, model: "/" + model + "/" in line) + + # Add models to DEPRECATED_MODELS in the configuration_auto.py + print("Adding models to DEPRECATED_MODELS in configuration_auto.py") + add_models_to_deprecated_models_in_config_auto(models) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--models", nargs="+", help="List of models to deprecate") + args = parser.parse_args() + deprecate_models(args.models) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/download_glue_data.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/download_glue_data.py new file mode 100644 index 0000000000000000000000000000000000000000..64cd3752024aaf11e117541ce27fcc24c521b845 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/download_glue_data.py @@ -0,0 +1,160 @@ +"""Script for downloading all GLUE data. +Original source: https://gist.github.com/W4ngatang/60c2bdb54d156a41194446737ce03e2e + +Note: for legal reasons, we are unable to host MRPC. +You can either use the version hosted by the SentEval team, which is already tokenized, +or you can download the original data from (https://download.microsoft.com/download/D/4/6/D46FF87A-F6B9-4252-AA8B-3604ED519838/MSRParaphraseCorpus.msi) and extract the data from it manually. +For Windows users, you can run the .msi file. For Mac and Linux users, consider an external library such as 'cabextract' (see below for an example). +You should then rename and place specific files in a folder (see below for an example). + +mkdir MRPC +cabextract MSRParaphraseCorpus.msi -d MRPC +cat MRPC/_2DEC3DBE877E4DB192D17C0256E90F1D | tr -d $'\r' > MRPC/msr_paraphrase_train.txt +cat MRPC/_D7B391F9EAFF4B1B8BCE8F21B20B1B61 | tr -d $'\r' > MRPC/msr_paraphrase_test.txt +rm MRPC/_* +rm MSRParaphraseCorpus.msi + +1/30/19: It looks like SentEval is no longer hosting their extracted and tokenized MRPC data, so you'll need to download the data from the original source for now. +2/11/19: It looks like SentEval actually *is* hosting the extracted data. Hooray! +""" + +import argparse +import os +import sys +import urllib.request +import zipfile + + +TASKS = ["CoLA", "SST", "MRPC", "QQP", "STS", "MNLI", "SNLI", "QNLI", "RTE", "WNLI", "diagnostic"] +TASK2PATH = { + "CoLA": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FCoLA.zip?alt=media&token=46d5e637-3411-4188-bc44-5809b5bfb5f4", + "SST": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSST-2.zip?alt=media&token=aabc5f6b-e466-44a2-b9b4-cf6337f84ac8", + "MRPC": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2Fmrpc_dev_ids.tsv?alt=media&token=ec5c0836-31d5-48f4-b431-7480817f1adc", + "QQP": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQQP.zip?alt=media&token=700c6acf-160d-4d89-81d1-de4191d02cb5", + "STS": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSTS-B.zip?alt=media&token=bddb94a7-8706-4e0d-a694-1109e12273b5", + "MNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FMNLI.zip?alt=media&token=50329ea1-e339-40e2-809c-10c40afff3ce", + "SNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSNLI.zip?alt=media&token=4afcfbb2-ff0c-4b2d-a09a-dbf07926f4df", + "QNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQNLIv2.zip?alt=media&token=6fdcf570-0fc5-4631-8456-9505272d1601", + "RTE": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FRTE.zip?alt=media&token=5efa7e85-a0bb-4f19-8ea2-9e1840f077fb", + "WNLI": "https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FWNLI.zip?alt=media&token=068ad0a0-ded7-4bd7-99a5-5e00222e0faf", + "diagnostic": "https://storage.googleapis.com/mtl-sentence-representations.appspot.com/tsvsWithoutLabels%2FAX.tsv?GoogleAccessId=firebase-adminsdk-0khhl@mtl-sentence-representations.iam.gserviceaccount.com&Expires=2498860800&Signature=DuQ2CSPt2Yfre0C%2BiISrVYrIFaZH1Lc7hBVZDD4ZyR7fZYOMNOUGpi8QxBmTNOrNPjR3z1cggo7WXFfrgECP6FBJSsURv8Ybrue8Ypt%2FTPxbuJ0Xc2FhDi%2BarnecCBFO77RSbfuz%2Bs95hRrYhTnByqu3U%2FYZPaj3tZt5QdfpH2IUROY8LiBXoXS46LE%2FgOQc%2FKN%2BA9SoscRDYsnxHfG0IjXGwHN%2Bf88q6hOmAxeNPx6moDulUF6XMUAaXCSFU%2BnRO2RDL9CapWxj%2BDl7syNyHhB7987hZ80B%2FwFkQ3MEs8auvt5XW1%2Bd4aCU7ytgM69r8JDCwibfhZxpaa4gd50QXQ%3D%3D", +} + +MRPC_TRAIN = "https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_train.txt" +MRPC_TEST = "https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_test.txt" + + +def download_and_extract(task, data_dir): + print(f"Downloading and extracting {task}...") + data_file = f"{task}.zip" + urllib.request.urlretrieve(TASK2PATH[task], data_file) + with zipfile.ZipFile(data_file) as zip_ref: + zip_ref.extractall(data_dir) + os.remove(data_file) + print("\tCompleted!") + + +def format_mrpc(data_dir, path_to_data): + print("Processing MRPC...") + mrpc_dir = os.path.join(data_dir, "MRPC") + if not os.path.isdir(mrpc_dir): + os.mkdir(mrpc_dir) + if path_to_data: + mrpc_train_file = os.path.join(path_to_data, "msr_paraphrase_train.txt") + mrpc_test_file = os.path.join(path_to_data, "msr_paraphrase_test.txt") + else: + print("Local MRPC data not specified, downloading data from %s" % MRPC_TRAIN) + mrpc_train_file = os.path.join(mrpc_dir, "msr_paraphrase_train.txt") + mrpc_test_file = os.path.join(mrpc_dir, "msr_paraphrase_test.txt") + urllib.request.urlretrieve(MRPC_TRAIN, mrpc_train_file) + urllib.request.urlretrieve(MRPC_TEST, mrpc_test_file) + if not os.path.isfile(mrpc_train_file): + raise ValueError(f"Train data not found at {mrpc_train_file}") + if not os.path.isfile(mrpc_test_file): + raise ValueError(f"Test data not found at {mrpc_test_file}") + urllib.request.urlretrieve(TASK2PATH["MRPC"], os.path.join(mrpc_dir, "dev_ids.tsv")) + + dev_ids = [] + with open(os.path.join(mrpc_dir, "dev_ids.tsv"), encoding="utf8") as ids_fh: + for row in ids_fh: + dev_ids.append(row.strip().split("\t")) + + with ( + open(mrpc_train_file, encoding="utf8") as data_fh, + open(os.path.join(mrpc_dir, "train.tsv"), "w", encoding="utf8") as train_fh, + open(os.path.join(mrpc_dir, "dev.tsv"), "w", encoding="utf8") as dev_fh, + ): + header = data_fh.readline() + train_fh.write(header) + dev_fh.write(header) + for row in data_fh: + label, id1, id2, s1, s2 = row.strip().split("\t") + if [id1, id2] in dev_ids: + dev_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2)) + else: + train_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2)) + + with ( + open(mrpc_test_file, encoding="utf8") as data_fh, + open(os.path.join(mrpc_dir, "test.tsv"), "w", encoding="utf8") as test_fh, + ): + header = data_fh.readline() + test_fh.write("index\t#1 ID\t#2 ID\t#1 String\t#2 String\n") + for idx, row in enumerate(data_fh): + label, id1, id2, s1, s2 = row.strip().split("\t") + test_fh.write("%d\t%s\t%s\t%s\t%s\n" % (idx, id1, id2, s1, s2)) + print("\tCompleted!") + + +def download_diagnostic(data_dir): + print("Downloading and extracting diagnostic...") + if not os.path.isdir(os.path.join(data_dir, "diagnostic")): + os.mkdir(os.path.join(data_dir, "diagnostic")) + data_file = os.path.join(data_dir, "diagnostic", "diagnostic.tsv") + urllib.request.urlretrieve(TASK2PATH["diagnostic"], data_file) + print("\tCompleted!") + return + + +def get_tasks(task_names): + task_names = task_names.split(",") + if "all" in task_names: + tasks = TASKS + else: + tasks = [] + for task_name in task_names: + if task_name not in TASKS: + raise ValueError(f"Task {task_name} not found!") + tasks.append(task_name) + return tasks + + +def main(arguments): + parser = argparse.ArgumentParser() + parser.add_argument("--data_dir", help="directory to save data to", type=str, default="glue_data") + parser.add_argument( + "--tasks", help="tasks to download data for as a comma separated string", type=str, default="all" + ) + parser.add_argument( + "--path_to_mrpc", + help="path to directory containing extracted MRPC data, msr_paraphrase_train.txt and msr_paraphrase_text.txt", + type=str, + default="", + ) + args = parser.parse_args(arguments) + + if not os.path.isdir(args.data_dir): + os.mkdir(args.data_dir) + tasks = get_tasks(args.tasks) + + for task in tasks: + if task == "MRPC": + format_mrpc(args.data_dir, args.path_to_mrpc) + elif task == "diagnostic": + download_diagnostic(args.data_dir) + else: + download_and_extract(task, args.data_dir) + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/extract_pr_number_from_circleci.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/extract_pr_number_from_circleci.py new file mode 100644 index 0000000000000000000000000000000000000000..8dbfcb60a53284a7f739452cd7a8a7aaf3119fc2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/extract_pr_number_from_circleci.py @@ -0,0 +1,31 @@ +# coding=utf-8 +# Copyright 2025 The HuggingFace Inc. team. +# +# 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. +"""Used by `.github/workflows/trigger_circleci.yml` to get the pull request number in CircleCI job runs.""" + +import os + + +if __name__ == "__main__": + pr_number = "" + + pr = os.environ.get("CIRCLE_PULL_REQUEST", "") + if len(pr) > 0: + pr_number = pr.split("/")[-1] + if pr_number == "": + pr = os.environ.get("CIRCLE_BRANCH", "") + if pr.startswith("pull/"): + pr_number = "".join(pr.split("/")[1:2]) + + print(pr_number) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/extract_warnings.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/extract_warnings.py new file mode 100644 index 0000000000000000000000000000000000000000..5f49b1b456de01e24ec4c0b6fde182a431444e7f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/extract_warnings.py @@ -0,0 +1,134 @@ +import argparse +import json +import os +import time +import zipfile + +from get_ci_error_statistics import download_artifact, get_artifacts_links + +from transformers import logging + + +logger = logging.get_logger(__name__) + + +def extract_warnings_from_single_artifact(artifact_path, targets): + """Extract warnings from a downloaded artifact (in .zip format)""" + selected_warnings = set() + buffer = [] + + def parse_line(fp): + for line in fp: + if isinstance(line, bytes): + line = line.decode("UTF-8") + if "warnings summary (final)" in line: + continue + # This means we are outside the body of a warning + elif not line.startswith(" "): + # process a single warning and move it to `selected_warnings`. + if len(buffer) > 0: + warning = "\n".join(buffer) + # Only keep the warnings specified in `targets` + if any(f": {x}: " in warning for x in targets): + selected_warnings.add(warning) + buffer.clear() + continue + else: + line = line.strip() + buffer.append(line) + + if from_gh: + for filename in os.listdir(artifact_path): + file_path = os.path.join(artifact_path, filename) + if not os.path.isdir(file_path): + # read the file + if filename != "warnings.txt": + continue + with open(file_path) as fp: + parse_line(fp) + else: + try: + with zipfile.ZipFile(artifact_path) as z: + for filename in z.namelist(): + if not os.path.isdir(filename): + # read the file + if filename != "warnings.txt": + continue + with z.open(filename) as fp: + parse_line(fp) + except Exception: + logger.warning( + f"{artifact_path} is either an invalid zip file or something else wrong. This file is skipped." + ) + + return selected_warnings + + +def extract_warnings(artifact_dir, targets): + """Extract warnings from all artifact files""" + + selected_warnings = set() + + paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if (p.endswith(".zip") or from_gh)] + for p in paths: + selected_warnings.update(extract_warnings_from_single_artifact(p, targets)) + + return selected_warnings + + +if __name__ == "__main__": + + def list_str(values): + return values.split(",") + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + parser.add_argument( + "--output_dir", + type=str, + required=True, + help="Where to store the downloaded artifacts and other result files.", + ) + parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") + # optional parameters + parser.add_argument( + "--targets", + default="DeprecationWarning,UserWarning,FutureWarning", + type=list_str, + help="Comma-separated list of target warning(s) which we want to extract.", + ) + parser.add_argument( + "--from_gh", + action="store_true", + help="If running from a GitHub action workflow and collecting warnings from its artifacts.", + ) + + args = parser.parse_args() + + from_gh = args.from_gh + if from_gh: + # The artifacts have to be downloaded using `actions/download-artifact@v4` + pass + else: + os.makedirs(args.output_dir, exist_ok=True) + + # get download links + artifacts = get_artifacts_links(args.workflow_run_id, token=args.token) + with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: + json.dump(artifacts, fp, ensure_ascii=False, indent=4) + + # download artifacts + for idx, (name, url) in enumerate(artifacts.items()): + print(name) + print(url) + print("=" * 80) + download_artifact(name, url, args.output_dir, args.token) + # Be gentle to GitHub + time.sleep(1) + + # extract warnings from artifacts + selected_warnings = extract_warnings(args.output_dir, args.targets) + selected_warnings = sorted(selected_warnings) + with open(os.path.join(args.output_dir, "selected_warnings.json"), "w", encoding="UTF-8") as fp: + json.dump(selected_warnings, fp, ensure_ascii=False, indent=4) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/fetch_hub_objects_for_ci.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/fetch_hub_objects_for_ci.py new file mode 100644 index 0000000000000000000000000000000000000000..b7f2f06bebda3d2bfd8ddf2f5052227e6e4e966a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/fetch_hub_objects_for_ci.py @@ -0,0 +1,12 @@ +from huggingface_hub import hf_hub_download + +from transformers.testing_utils import _run_pipeline_tests + + +if __name__ == "__main__": + if _run_pipeline_tests: + import datasets + + _ = datasets.load_dataset("hf-internal-testing/librispeech_asr_dummy", "clean", split="validation") + _ = datasets.load_dataset("hf-internal-testing/fixtures_image_utils", split="test", revision="refs/pr/1") + _ = hf_hub_download(repo_id="nateraw/video-demo", filename="archery.mp4", repo_type="dataset") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_ci_error_statistics.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_ci_error_statistics.py new file mode 100644 index 0000000000000000000000000000000000000000..eb8ffa37b803352fde707867ce070589bcf3fe5d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_ci_error_statistics.py @@ -0,0 +1,303 @@ +import argparse +import json +import math +import os +import time +import traceback +import zipfile +from collections import Counter + +import requests + + +def get_jobs(workflow_run_id, token=None): + """Extract jobs in a GitHub Actions workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" + result = requests.get(url, headers=headers).json() + jobs = [] + + try: + jobs.extend(result["jobs"]) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + jobs.extend(result["jobs"]) + + return jobs + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return [] + + +def get_job_links(workflow_run_id, token=None): + """Extract job names and their job links in a GitHub Actions workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" + result = requests.get(url, headers=headers).json() + job_links = {} + + try: + job_links.update({job["name"]: job["html_url"] for job in result["jobs"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + job_links.update({job["name"]: job["html_url"] for job in result["jobs"]}) + + return job_links + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +def get_artifacts_links(worflow_run_id, token=None): + """Get all artifact links from a workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{worflow_run_id}/artifacts?per_page=100" + result = requests.get(url, headers=headers).json() + artifacts = {} + + try: + artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + artifacts.update({artifact["name"]: artifact["archive_download_url"] for artifact in result["artifacts"]}) + + return artifacts + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +def download_artifact(artifact_name, artifact_url, output_dir, token): + """Download a GitHub Action artifact from a URL. + + The URL is of the form `https://api.github.com/repos/huggingface/transformers/actions/artifacts/{ARTIFACT_ID}/zip`, + but it can't be used to download directly. We need to get a redirect URL first. + See https://docs.github.com/en/rest/actions/artifacts#download-an-artifact + """ + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + result = requests.get(artifact_url, headers=headers, allow_redirects=False) + download_url = result.headers["Location"] + response = requests.get(download_url, allow_redirects=True) + file_path = os.path.join(output_dir, f"{artifact_name}.zip") + with open(file_path, "wb") as fp: + fp.write(response.content) + + +def get_errors_from_single_artifact(artifact_zip_path, job_links=None): + """Extract errors from a downloaded artifact (in .zip format)""" + errors = [] + failed_tests = [] + job_name = None + + with zipfile.ZipFile(artifact_zip_path) as z: + for filename in z.namelist(): + if not os.path.isdir(filename): + # read the file + if filename in ["failures_line.txt", "summary_short.txt", "job_name.txt"]: + with z.open(filename) as f: + for line in f: + line = line.decode("UTF-8").strip() + if filename == "failures_line.txt": + try: + # `error_line` is the place where `error` occurs + error_line = line[: line.index(": ")] + error = line[line.index(": ") + len(": ") :] + errors.append([error_line, error]) + except Exception: + # skip un-related lines + pass + elif filename == "summary_short.txt" and line.startswith("FAILED "): + # `test` is the test method that failed + test = line[len("FAILED ") :] + failed_tests.append(test) + elif filename == "job_name.txt": + job_name = line + + if len(errors) != len(failed_tests): + raise ValueError( + f"`errors` and `failed_tests` should have the same number of elements. Got {len(errors)} for `errors` " + f"and {len(failed_tests)} for `failed_tests` instead. The test reports in {artifact_zip_path} have some" + " problem." + ) + + job_link = None + if job_name and job_links: + job_link = job_links.get(job_name, None) + + # A list with elements of the form (line of error, error, failed test) + result = [x + [y] + [job_link] for x, y in zip(errors, failed_tests)] + + return result + + +def get_all_errors(artifact_dir, job_links=None): + """Extract errors from all artifact files""" + + errors = [] + + paths = [os.path.join(artifact_dir, p) for p in os.listdir(artifact_dir) if p.endswith(".zip")] + for p in paths: + errors.extend(get_errors_from_single_artifact(p, job_links=job_links)) + + return errors + + +def reduce_by_error(logs, error_filter=None): + """count each error""" + + counter = Counter() + counter.update([x[1] for x in logs]) + counts = counter.most_common() + r = {} + for error, count in counts: + if error_filter is None or error not in error_filter: + r[error] = {"count": count, "failed_tests": [(x[2], x[0]) for x in logs if x[1] == error]} + + r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True)) + return r + + +def get_model(test): + """Get the model name from a test method""" + test = test.split("::")[0] + if test.startswith("tests/models/"): + test = test.split("/")[2] + else: + test = None + + return test + + +def reduce_by_model(logs, error_filter=None): + """count each error per model""" + + logs = [(x[0], x[1], get_model(x[2])) for x in logs] + logs = [x for x in logs if x[2] is not None] + tests = {x[2] for x in logs} + + r = {} + for test in tests: + counter = Counter() + # count by errors in `test` + counter.update([x[1] for x in logs if x[2] == test]) + counts = counter.most_common() + error_counts = {error: count for error, count in counts if (error_filter is None or error not in error_filter)} + n_errors = sum(error_counts.values()) + if n_errors > 0: + r[test] = {"count": n_errors, "errors": error_counts} + + r = dict(sorted(r.items(), key=lambda item: item[1]["count"], reverse=True)) + return r + + +def make_github_table(reduced_by_error): + header = "| no. | error | status |" + sep = "|-:|:-|:-|" + lines = [header, sep] + for error in reduced_by_error: + count = reduced_by_error[error]["count"] + line = f"| {count} | {error[:100]} | |" + lines.append(line) + + return "\n".join(lines) + + +def make_github_table_per_model(reduced_by_model): + header = "| model | no. of errors | major error | count |" + sep = "|-:|-:|-:|-:|" + lines = [header, sep] + for model in reduced_by_model: + count = reduced_by_model[model]["count"] + error, _count = list(reduced_by_model[model]["errors"].items())[0] + line = f"| {model} | {count} | {error[:60]} | {_count} |" + lines.append(line) + + return "\n".join(lines) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + parser.add_argument( + "--output_dir", + type=str, + required=True, + help="Where to store the downloaded artifacts and other result files.", + ) + parser.add_argument("--token", default=None, type=str, help="A token that has actions:read permission.") + args = parser.parse_args() + + os.makedirs(args.output_dir, exist_ok=True) + + _job_links = get_job_links(args.workflow_run_id, token=args.token) + job_links = {} + # To deal with `workflow_call` event, where a job name is the combination of the job names in the caller and callee. + # For example, `PyTorch 1.11 / Model tests (models/albert, single-gpu)`. + if _job_links: + for k, v in _job_links.items(): + # This is how GitHub actions combine job names. + if " / " in k: + index = k.find(" / ") + k = k[index + len(" / ") :] + job_links[k] = v + with open(os.path.join(args.output_dir, "job_links.json"), "w", encoding="UTF-8") as fp: + json.dump(job_links, fp, ensure_ascii=False, indent=4) + + artifacts = get_artifacts_links(args.workflow_run_id, token=args.token) + with open(os.path.join(args.output_dir, "artifacts.json"), "w", encoding="UTF-8") as fp: + json.dump(artifacts, fp, ensure_ascii=False, indent=4) + + for idx, (name, url) in enumerate(artifacts.items()): + download_artifact(name, url, args.output_dir, args.token) + # Be gentle to GitHub + time.sleep(1) + + errors = get_all_errors(args.output_dir, job_links=job_links) + + # `e[1]` is the error + counter = Counter() + counter.update([e[1] for e in errors]) + + # print the top 30 most common test errors + most_common = counter.most_common(30) + for item in most_common: + print(item) + + with open(os.path.join(args.output_dir, "errors.json"), "w", encoding="UTF-8") as fp: + json.dump(errors, fp, ensure_ascii=False, indent=4) + + reduced_by_error = reduce_by_error(errors) + reduced_by_model = reduce_by_model(errors) + + s1 = make_github_table(reduced_by_error) + s2 = make_github_table_per_model(reduced_by_model) + + with open(os.path.join(args.output_dir, "reduced_by_error.txt"), "w", encoding="UTF-8") as fp: + fp.write(s1) + with open(os.path.join(args.output_dir, "reduced_by_model.txt"), "w", encoding="UTF-8") as fp: + fp.write(s2) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_github_job_time.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_github_job_time.py new file mode 100644 index 0000000000000000000000000000000000000000..155d859bba65dbee0863eae5a5c379adb7193161 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_github_job_time.py @@ -0,0 +1,71 @@ +import argparse +import math +import traceback + +import dateutil.parser as date_parser +import requests + + +def extract_time_from_single_job(job): + """Extract time info from a single job in a GitHub Actions workflow run""" + + job_info = {} + + start = job["started_at"] + end = job["completed_at"] + + start_datetime = date_parser.parse(start) + end_datetime = date_parser.parse(end) + + duration_in_min = round((end_datetime - start_datetime).total_seconds() / 60.0) + + job_info["started_at"] = start + job_info["completed_at"] = end + job_info["duration"] = duration_in_min + + return job_info + + +def get_job_time(workflow_run_id, token=None): + """Extract time info for all jobs in a GitHub Actions workflow run""" + + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + url = f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}/jobs?per_page=100" + result = requests.get(url, headers=headers).json() + job_time = {} + + try: + job_time.update({job["name"]: extract_time_from_single_job(job) for job in result["jobs"]}) + pages_to_iterate_over = math.ceil((result["total_count"] - 100) / 100) + + for i in range(pages_to_iterate_over): + result = requests.get(url + f"&page={i + 2}", headers=headers).json() + job_time.update({job["name"]: extract_time_from_single_job(job) for job in result["jobs"]}) + + return job_time + except Exception: + print(f"Unknown error, could not fetch links:\n{traceback.format_exc()}") + + return {} + + +if __name__ == "__main__": + r""" + Example: + + python get_github_job_time.py --workflow_run_id 2945609517 + """ + + parser = argparse.ArgumentParser() + # Required parameters + parser.add_argument("--workflow_run_id", type=str, required=True, help="A GitHub Actions workflow run id.") + args = parser.parse_args() + + job_time = get_job_time(args.workflow_run_id) + job_time = dict(sorted(job_time.items(), key=lambda item: item[1]["duration"], reverse=True)) + + for k, v in job_time.items(): + print(f"{k}: {v['duration']}") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_modified_files.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_modified_files.py new file mode 100644 index 0000000000000000000000000000000000000000..6c8bdfcdf00c835b68ed9b0eddeaf4d9d517d9cd --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_modified_files.py @@ -0,0 +1,36 @@ +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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 script reports modified .py files under the desired list of top-level sub-dirs passed as a list of arguments, e.g.: +# python ./utils/get_modified_files.py utils src tests examples +# +# it uses git to find the forking point and which files were modified - i.e. files not under git won't be considered +# since the output of this script is fed into Makefile commands it doesn't print a newline after the results + +import re +import subprocess +import sys + + +fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8") +modified_files = ( + subprocess.check_output(f"git diff --diff-filter=d --name-only {fork_point_sha}".split()).decode("utf-8").split() +) + +joined_dirs = "|".join(sys.argv[1:]) +regex = re.compile(rf"^({joined_dirs}).*?\.py$") + +relevant_modified_files = [x for x in modified_files if regex.match(x)] +print(" ".join(relevant_modified_files), end="") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_pr_run_slow_jobs.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_pr_run_slow_jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..fa56a6c305e113061e3582c9e1b85781ddbb092b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_pr_run_slow_jobs.py @@ -0,0 +1,133 @@ +import argparse +import json +import re +import string + + +MAX_NUM_JOBS_TO_SUGGEST = 16 + + +def get_jobs_to_run(): + # The file `pr_files.txt` contains the information about the files changed in a pull request, and it is prepared by + # the caller (using GitHub api). + # We can also use the following api to get the information if we don't have them before calling this script. + # url = f"https://api.github.com/repos/huggingface/transformers/pulls/PULL_NUMBER/files?ref={pr_sha}" + with open("pr_files.txt") as fp: + pr_files = json.load(fp) + pr_files = [{k: v for k, v in item.items() if k in ["filename", "status"]} for item in pr_files] + pr_files = [item["filename"] for item in pr_files if item["status"] in ["added", "modified"]] + + # models or quantizers + re_1 = re.compile(r"src/transformers/(models/.*)/modeling_.*\.py") + re_2 = re.compile(r"src/transformers/(quantizers/quantizer_.*)\.py") + + # tests for models or quantizers + re_3 = re.compile(r"tests/(models/.*)/test_.*\.py") + re_4 = re.compile(r"tests/(quantization/.*)/test_.*\.py") + + # files in a model directory but not necessary a modeling file + re_5 = re.compile(r"src/transformers/(models/.*)/.*\.py") + + regexes = [re_1, re_2, re_3, re_4, re_5] + + jobs_to_run = [] + for pr_file in pr_files: + for regex in regexes: + matched = regex.findall(pr_file) + if len(matched) > 0: + item = matched[0] + item = item.replace("quantizers/quantizer_", "quantization/") + # TODO: for files in `quantizers`, the processed item above may not exist. Try using a fuzzy matching + if item in repo_content: + jobs_to_run.append(item) + break + jobs_to_run = sorted(set(jobs_to_run)) + + return jobs_to_run + + +def parse_message(message: str) -> str: + """ + Parses a GitHub pull request's comment to find the models specified in it to run slow CI. + + Args: + message (`str`): The body of a GitHub pull request's comment. + + Returns: + `str`: The substring in `message` after `run-slow`, run_slow` or run slow`. If no such prefix is found, the + empty string is returned. + """ + if message is None: + return "" + + message = message.strip().lower() + + # run-slow: model_1, model_2, quantization_1, quantization_2 + if not message.startswith(("run-slow", "run_slow", "run slow")): + return "" + message = message[len("run slow") :] + # remove leading `:` + while message.strip().startswith(":"): + message = message.strip()[1:] + + return message + + +def get_jobs(message: str): + models = parse_message(message) + return models.replace(",", " ").split() + + +def check_name(model_name: str): + allowed = string.ascii_letters + string.digits + "_" + return not (model_name.startswith("_") or model_name.endswith("_")) and all(c in allowed for c in model_name) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--message", type=str, default="", help="The content of a comment.") + parser.add_argument("--quantization", action="store_true", help="If we collect quantization tests") + args = parser.parse_args() + + # The files are prepared by the caller (using GitHub api). + # We can also use the following api to get the information if we don't have them before calling this script. + # url = f"https://api.github.com/repos/OWNER/REPO/contents/PATH?ref={pr_sha}" + # (we avoid to checkout the repository using `actions/checkout` to reduce the run time, but mostly to avoid the potential security issue as much as possible) + repo_content = [] + for filename in ["tests_dir.txt", "tests_models_dir.txt", "tests_quantization_dir.txt"]: + with open(filename) as fp: + data = json.load(fp) + data = [item["path"][len("tests/") :] for item in data if item["type"] == "dir"] + repo_content.extend(data) + + # These don't have the prefix `models/` or `quantization/`, so we need to add them. + if args.message: + specified_jobs = get_jobs(args.message) + specified_jobs = [job for job in specified_jobs if check_name(job)] + + # Add prefix (`models/` or `quantization`) + jobs_to_run = [] + for job in specified_jobs: + if not args.quantization: + if f"models/{job}" in repo_content: + jobs_to_run.append(f"models/{job}") + elif job in repo_content and job != "quantization": + jobs_to_run.append(job) + elif f"quantization/{job}" in repo_content: + jobs_to_run.append(f"quantization/{job}") + + print(sorted(set(jobs_to_run))) + + else: + # Compute (from the added/modified files) the directories under `tests/`, `tests/models/` and `tests/quantization`to run tests. + # These are already with the prefix `models/` or `quantization/`, so we don't need to add them. + jobs_to_run = get_jobs_to_run() + jobs_to_run = [x.replace("models/", "").replace("quantization/", "") for x in jobs_to_run] + jobs_to_run = [job for job in jobs_to_run if check_name(job)] + + if len(jobs_to_run) > MAX_NUM_JOBS_TO_SUGGEST: + jobs_to_run = jobs_to_run[:MAX_NUM_JOBS_TO_SUGGEST] + + suggestion = f"{', '.join(jobs_to_run)}" + + print(suggestion) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_previous_daily_ci.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_previous_daily_ci.py new file mode 100644 index 0000000000000000000000000000000000000000..97d3696465cf19fec0dbc154e9f124c3e6425d66 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_previous_daily_ci.py @@ -0,0 +1,159 @@ +import os +import zipfile + +import requests +from get_ci_error_statistics import download_artifact, get_artifacts_links + + +def get_daily_ci_runs(token, num_runs=7, workflow_id=None): + """Get the workflow runs of the scheduled (daily) CI. + + This only selects the runs triggered by the `schedule` event on the `main` branch. + """ + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + # The id of a workflow (not of a workflow run). + # From a given workflow run (where we have workflow run id), we can get the workflow id by going to + # https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id} + # and check the `workflow_id` key. + + if not workflow_id: + workflow_run_id = os.environ["GITHUB_RUN_ID"] + workflow_run = requests.get( + f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}", headers=headers + ).json() + workflow_id = workflow_run["workflow_id"] + + url = f"https://api.github.com/repos/huggingface/transformers/actions/workflows/{workflow_id}/runs" + # On `main` branch + event being `schedule` + not returning PRs + only `num_runs` results + url += f"?branch=main&exclude_pull_requests=true&per_page={num_runs}" + + result = requests.get(f"{url}&event=schedule", headers=headers).json() + workflow_runs = result["workflow_runs"] + if len(workflow_runs) == 0: + result = requests.get(f"{url}&event=workflow_run", headers=headers).json() + workflow_runs = result["workflow_runs"] + + return workflow_runs + + +def get_last_daily_ci_run(token, workflow_run_id=None, workflow_id=None, commit_sha=None): + """Get the last completed workflow run id of the scheduled (daily) CI.""" + headers = None + if token is not None: + headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"} + + workflow_run = None + if workflow_run_id is not None and workflow_run_id != "": + workflow_run = requests.get( + f"https://api.github.com/repos/huggingface/transformers/actions/runs/{workflow_run_id}", headers=headers + ).json() + return workflow_run + + workflow_runs = get_daily_ci_runs(token, workflow_id=workflow_id) + for run in workflow_runs: + if commit_sha in [None, ""] and run["status"] == "completed": + workflow_run = run + break + # if `commit_sha` is specified, return the latest completed run with `workflow_run["head_sha"]` matching the specified sha. + elif commit_sha not in [None, ""] and run["head_sha"] == commit_sha and run["status"] == "completed": + workflow_run = run + break + + return workflow_run + + +def get_last_daily_ci_workflow_run_id(token, workflow_run_id=None, workflow_id=None, commit_sha=None): + """Get the last completed workflow run id of the scheduled (daily) CI.""" + if workflow_run_id is not None and workflow_run_id != "": + return workflow_run_id + + workflow_run = get_last_daily_ci_run(token, workflow_id=workflow_id, commit_sha=commit_sha) + workflow_run_id = None + if workflow_run is not None: + workflow_run_id = workflow_run["id"] + + return workflow_run_id + + +def get_last_daily_ci_run_commit(token, workflow_run_id=None, workflow_id=None, commit_sha=None): + """Get the commit sha of the last completed scheduled daily CI workflow run.""" + workflow_run = get_last_daily_ci_run( + token, workflow_run_id=workflow_run_id, workflow_id=workflow_id, commit_sha=commit_sha + ) + workflow_run_head_sha = None + if workflow_run is not None: + workflow_run_head_sha = workflow_run["head_sha"] + + return workflow_run_head_sha + + +def get_last_daily_ci_artifacts( + output_dir, + token, + workflow_run_id=None, + workflow_id=None, + commit_sha=None, + artifact_names=None, +): + """Get the artifacts of last completed workflow run id of the scheduled (daily) CI.""" + workflow_run_id = get_last_daily_ci_workflow_run_id( + token, workflow_run_id=workflow_run_id, workflow_id=workflow_id, commit_sha=commit_sha + ) + if workflow_run_id is not None: + artifacts_links = get_artifacts_links(worflow_run_id=workflow_run_id, token=token) + + if artifact_names is None: + artifact_names = artifacts_links.keys() + + downloaded_artifact_names = [] + for artifact_name in artifact_names: + if artifact_name in artifacts_links: + artifact_url = artifacts_links[artifact_name] + download_artifact( + artifact_name=artifact_name, artifact_url=artifact_url, output_dir=output_dir, token=token + ) + downloaded_artifact_names.append(artifact_name) + + return downloaded_artifact_names + + +def get_last_daily_ci_reports( + output_dir, + token, + workflow_run_id=None, + workflow_id=None, + commit_sha=None, + artifact_names=None, +): + """Get the artifacts' content of the last completed workflow run id of the scheduled (daily) CI.""" + downloaded_artifact_names = get_last_daily_ci_artifacts( + output_dir, + token, + workflow_run_id=workflow_run_id, + workflow_id=workflow_id, + commit_sha=commit_sha, + artifact_names=artifact_names, + ) + + results = {} + for artifact_name in downloaded_artifact_names: + artifact_zip_path = os.path.join(output_dir, f"{artifact_name}.zip") + if os.path.isfile(artifact_zip_path): + target_dir = os.path.join(output_dir, artifact_name) + with zipfile.ZipFile(artifact_zip_path) as z: + z.extractall(target_dir) + + results[artifact_name] = {} + filename = os.listdir(target_dir) + for filename in filename: + file_path = os.path.join(target_dir, filename) + if not os.path.isdir(file_path): + # read the file + with open(file_path) as fp: + content = fp.read() + results[artifact_name][filename] = content + + return results diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_runner_map.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_runner_map.py new file mode 100644 index 0000000000000000000000000000000000000000..7b36651165bc40b0bc96a7126068f0766d8fc421 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_runner_map.py @@ -0,0 +1,65 @@ +# Copyright 2025 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 script is used to get a map containing the information of runners to use in GitHub Actions workflow files. +This is meant to be a temporary file that helps us to switch progressively from T4 to A10 runners. + +The data is stored in a Hub repository [hf-internal-testing/transformers_daily_ci](https://huggingface.co/datasets/hf-internal-testing/transformers_daily_ci/blob/main/runner_map.json). +Currently, in that file, we specify the models for which we want to run the tests with T4 runners to avoid many test failures showing on the CI reports. +We will work on the tests toward to use A10 for all CI jobs. +""" + +import os + +import requests + + +if __name__ == "__main__": + # T4 + t4_runners = { + "single-gpu": "aws-g4dn-4xlarge-cache", + "multi-gpu": "aws-g4dn-12xlarge-cache", + } + + # A10 + a10_runners = { + "single-gpu": "aws-g5-4xlarge-cache", + "multi-gpu": "aws-g5-12xlarge-cache", + } + + tests = os.getcwd() + model_tests = os.listdir(os.path.join(tests, "models")) + d1 = sorted(filter(os.path.isdir, os.listdir(tests))) + d2 = sorted(filter(os.path.isdir, [f"models/{x}" for x in model_tests])) + d1.remove("models") + d = d2 + d1 + + response = requests.get( + "https://huggingface.co/datasets/hf-internal-testing/transformers_daily_ci/resolve/main/runner_map.json" + ) + # The models that we want to run with T4 runners + jobs_using_t4 = response.json() + + runner_map = {} + for key in d: + modified_key = key + if modified_key.startswith("models/"): + modified_key = key[len("models/") :] + if modified_key in jobs_using_t4: + runner_map[key] = t4_runners + else: + runner_map[key] = a10_runners + + print(runner_map) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_test_info.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_test_info.py new file mode 100644 index 0000000000000000000000000000000000000000..3c376bdbdaaf45fe9d9623ac4cd292421fbcb0ef --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/get_test_info.py @@ -0,0 +1,198 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. + +import importlib +import os +import sys + + +# This is required to make the module import works (when the python process is running from the root of the repo) +sys.path.append(".") + + +r""" +The argument `test_file` in this file refers to a model test file. This should be a string of the from +`tests/models/*/test_modeling_*.py`. +""" + + +def get_module_path(test_file): + """Return the module path of a model test file.""" + components = test_file.split(os.path.sep) + if components[0:2] != ["tests", "models"]: + raise ValueError( + "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got " + f"{test_file} instead." + ) + test_fn = components[-1] + if not test_fn.endswith("py"): + raise ValueError(f"`test_file` should be a python file. Got {test_fn} instead.") + if not test_fn.startswith("test_modeling_"): + raise ValueError( + f"`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead." + ) + + components = components[:-1] + [test_fn.replace(".py", "")] + test_module_path = ".".join(components) + + return test_module_path + + +def get_test_module(test_file): + """Get the module of a model test file.""" + test_module_path = get_module_path(test_file) + try: + test_module = importlib.import_module(test_module_path) + except AttributeError as exc: + # e.g. if you have a `tests` folder in `site-packages`, created by another package, when trying to import + # `tests.models...` + raise ValueError( + f"Could not import module {test_module_path}. Confirm that you don't have a package with the same root " + "name installed or in your environment's `site-packages`." + ) from exc + + return test_module + + +def get_tester_classes(test_file): + """Get all classes in a model test file whose names ends with `ModelTester`.""" + tester_classes = [] + test_module = get_test_module(test_file) + for attr in dir(test_module): + if attr.endswith("ModelTester"): + tester_classes.append(getattr(test_module, attr)) + + # sort with class names + return sorted(tester_classes, key=lambda x: x.__name__) + + +def get_test_classes(test_file): + """Get all [test] classes in a model test file with attribute `all_model_classes` that are non-empty. + + These are usually the (model) test classes containing the (non-slow) tests to run and are subclasses of one of the + classes `ModelTesterMixin`, `TFModelTesterMixin` or `FlaxModelTesterMixin`, as well as a subclass of + `unittest.TestCase`. Exceptions include `RagTestMixin` (and its subclasses). + """ + test_classes = [] + test_module = get_test_module(test_file) + for attr in dir(test_module): + attr_value = getattr(test_module, attr) + # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking + # `all_model_classes` is not empty (which also excludes other special classes). + model_classes = getattr(attr_value, "all_model_classes", []) + if len(model_classes) > 0: + test_classes.append(attr_value) + + # sort with class names + return sorted(test_classes, key=lambda x: x.__name__) + + +def get_model_classes(test_file): + """Get all model classes that appear in `all_model_classes` attributes in a model test file.""" + test_classes = get_test_classes(test_file) + model_classes = set() + for test_class in test_classes: + model_classes.update(test_class.all_model_classes) + + # sort with class names + return sorted(model_classes, key=lambda x: x.__name__) + + +def get_model_tester_from_test_class(test_class): + """Get the model tester class of a model test class.""" + test = test_class() + if hasattr(test, "setUp"): + test.setUp() + + model_tester = None + if hasattr(test, "model_tester"): + # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case. + if test.model_tester is not None: + model_tester = test.model_tester.__class__ + + return model_tester + + +def get_test_classes_for_model(test_file, model_class): + """Get all [test] classes in `test_file` that have `model_class` in their `all_model_classes`.""" + test_classes = get_test_classes(test_file) + + target_test_classes = [] + for test_class in test_classes: + if model_class in test_class.all_model_classes: + target_test_classes.append(test_class) + + # sort with class names + return sorted(target_test_classes, key=lambda x: x.__name__) + + +def get_tester_classes_for_model(test_file, model_class): + """Get all model tester classes in `test_file` that are associated to `model_class`.""" + test_classes = get_test_classes_for_model(test_file, model_class) + + tester_classes = [] + for test_class in test_classes: + tester_class = get_model_tester_from_test_class(test_class) + if tester_class is not None: + tester_classes.append(tester_class) + + # sort with class names + return sorted(tester_classes, key=lambda x: x.__name__) + + +def get_test_to_tester_mapping(test_file): + """Get a mapping from [test] classes to model tester classes in `test_file`. + + This uses `get_test_classes` which may return classes that are NOT subclasses of `unittest.TestCase`. + """ + test_classes = get_test_classes(test_file) + test_tester_mapping = {test_class: get_model_tester_from_test_class(test_class) for test_class in test_classes} + return test_tester_mapping + + +def get_model_to_test_mapping(test_file): + """Get a mapping from model classes to test classes in `test_file`.""" + model_classes = get_model_classes(test_file) + model_test_mapping = { + model_class: get_test_classes_for_model(test_file, model_class) for model_class in model_classes + } + return model_test_mapping + + +def get_model_to_tester_mapping(test_file): + """Get a mapping from model classes to model tester classes in `test_file`.""" + model_classes = get_model_classes(test_file) + model_to_tester_mapping = { + model_class: get_tester_classes_for_model(test_file, model_class) for model_class in model_classes + } + return model_to_tester_mapping + + +def to_json(o): + """Make the information succinct and easy to read. + + Avoid the full class representation like `` when + displaying the results. Instead, we use class name (`BertForMaskedLM`) for the readability. + """ + if isinstance(o, str): + return o + elif isinstance(o, type): + return o.__name__ + elif isinstance(o, (list, tuple)): + return [to_json(x) for x in o] + elif isinstance(o, dict): + return {to_json(k): to_json(v) for k, v in o.items()} + else: + return o diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/important_models.txt b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/important_models.txt new file mode 100644 index 0000000000000000000000000000000000000000..6bf6f7119437586a2ff2753d9b1d81dd30c2cdfe --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/important_models.txt @@ -0,0 +1,4 @@ +models/llama +models/mistral +models/mixtral +models/gemma diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/models_to_deprecate.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/models_to_deprecate.py new file mode 100644 index 0000000000000000000000000000000000000000..17ea1fd28ec8c6ef6fc10ba6828c90539d9865f8 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/models_to_deprecate.py @@ -0,0 +1,200 @@ +# 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. +""" +Script to find a candidate list of models to deprecate based on the number of downloads and the date of the last commit. +""" + +import argparse +import glob +import json +import os +from collections import defaultdict +from datetime import datetime, timezone +from pathlib import Path + +from git import Repo +from huggingface_hub import HfApi + + +api = HfApi() + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() +repo = Repo(PATH_TO_REPO) + + +class HubModelLister: + """ + Utility for getting models from the hub based on tags. Handles errors without crashing the script. + """ + + def __init__(self, tags): + self.tags = tags + self.model_list = api.list_models(tags=tags) + + def __iter__(self): + try: + yield from self.model_list + except Exception as e: + print(f"Error: {e}") + return + + +def _extract_commit_hash(commits): + for commit in commits: + if commit.startswith("commit "): + return commit.split(" ")[1] + return "" + + +def get_list_of_repo_model_paths(models_dir): + # Get list of all models in the library + models = glob.glob(os.path.join(models_dir, "*/modeling_*.py")) + + # Remove flax and tf models + models = [model for model in models if "_flax_" not in model] + models = [model for model in models if "_tf_" not in model] + + # Get list of all deprecated models in the library + deprecated_models = glob.glob(os.path.join(models_dir, "deprecated", "*")) + # For each deprecated model, remove the deprecated models from the list of all models as well as the symlink path + for deprecated_model in deprecated_models: + deprecated_model_name = "/" + deprecated_model.split("/")[-1] + "/" + models = [model for model in models if deprecated_model_name not in model] + # Remove deprecated models + models = [model for model in models if "/deprecated" not in model] + # Remove auto + models = [model for model in models if "/auto/" not in model] + return models + + +def get_list_of_models_to_deprecate( + thresh_num_downloads=5_000, + thresh_date=None, + use_cache=False, + save_model_info=False, + max_num_models=-1, +): + if thresh_date is None: + thresh_date = datetime.now(timezone.utc).replace(year=datetime.now(timezone.utc).year - 1) + else: + thresh_date = datetime.strptime(thresh_date, "%Y-%m-%d").replace(tzinfo=timezone.utc) + + models_dir = PATH_TO_REPO / "src/transformers/models" + model_paths = get_list_of_repo_model_paths(models_dir=models_dir) + + if use_cache and os.path.exists("models_info.json"): + with open("models_info.json", "r") as f: + models_info = json.load(f) + # Convert datetimes back to datetime objects + for model, info in models_info.items(): + info["first_commit_datetime"] = datetime.fromisoformat(info["first_commit_datetime"]) + + else: + # Build a dictionary of model info: first commit datetime, commit hash, model path + models_info = defaultdict(dict) + for model_path in model_paths: + model = model_path.split("/")[-2] + if model in models_info: + continue + commits = repo.git.log("--diff-filter=A", "--", model_path).split("\n") + commit_hash = _extract_commit_hash(commits) + commit_obj = repo.commit(commit_hash) + committed_datetime = commit_obj.committed_datetime + models_info[model]["commit_hash"] = commit_hash + models_info[model]["first_commit_datetime"] = committed_datetime + models_info[model]["model_path"] = model_path + models_info[model]["downloads"] = 0 + + # Some tags on the hub are formatted differently than in the library + tags = [model] + if "_" in model: + tags.append(model.replace("_", "-")) + models_info[model]["tags"] = tags + + # Filter out models which were added less than a year ago + models_info = { + model: info for model, info in models_info.items() if info["first_commit_datetime"] < thresh_date + } + + # We make successive calls to the hub, filtering based on the model tags + n_seen = 0 + for model, model_info in models_info.items(): + for model_tag in model_info["tags"]: + model_list = HubModelLister(tags=model_tag) + for i, hub_model in enumerate(model_list): + n_seen += 1 + if i % 100 == 0: + print(f"Processing model {i} for tag {model_tag}") + if max_num_models != -1 and i > n_seen: + break + if hub_model.private: + continue + model_info["downloads"] += hub_model.downloads + + if save_model_info and not (use_cache and os.path.exists("models_info.json")): + # Make datetimes serializable + for model, info in models_info.items(): + info["first_commit_datetime"] = info["first_commit_datetime"].isoformat() + with open("models_info.json", "w") as f: + json.dump(models_info, f, indent=4) + + print("\nFinding models to deprecate:") + n_models_to_deprecate = 0 + models_to_deprecate = {} + for model, info in models_info.items(): + n_downloads = info["downloads"] + if n_downloads < thresh_num_downloads: + n_models_to_deprecate += 1 + models_to_deprecate[model] = info + print(f"\nModel: {model}") + print(f"Downloads: {n_downloads}") + print(f"Date: {info['first_commit_datetime']}") + print("\nModels to deprecate: ", "\n" + "\n".join(models_to_deprecate.keys())) + print(f"\nNumber of models to deprecate: {n_models_to_deprecate}") + print("Before deprecating make sure to verify the models, including if they're used as a module in other models.") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--save_model_info", action="store_true", help="Save the retrieved model info to a json file.") + parser.add_argument( + "--use_cache", action="store_true", help="Use the cached model info instead of calling the hub." + ) + parser.add_argument( + "--thresh_num_downloads", + type=int, + default=5_000, + help="Threshold number of downloads below which a model should be deprecated. Default is 5,000.", + ) + parser.add_argument( + "--thresh_date", + type=str, + default=None, + help="Date to consider the first commit from. Format: YYYY-MM-DD. If unset, defaults to one year ago from today.", + ) + parser.add_argument( + "--max_num_models", + type=int, + default=-1, + help="Maximum number of models to consider from the hub. -1 means all models. Useful for testing.", + ) + args = parser.parse_args() + + models_to_deprecate = get_list_of_models_to_deprecate( + thresh_num_downloads=args.thresh_num_downloads, + thresh_date=args.thresh_date, + use_cache=args.use_cache, + save_model_info=args.save_model_info, + max_num_models=args.max_num_models, + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/modular_model_converter.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/modular_model_converter.py new file mode 100644 index 0000000000000000000000000000000000000000..86eecc83a5ab72d64d77e261eb63b7c6e875c7fd --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/modular_model_converter.py @@ -0,0 +1,1790 @@ +# coding=utf-8 +# Copyright 2024 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. +import argparse +import glob +import importlib +import os +import re +import subprocess +from abc import ABC, abstractmethod +from collections import Counter, defaultdict, deque +from typing import Optional, Union + +import libcst as cst +from create_dependency_mapping import find_priority_list +from libcst import ClassDef, CSTVisitor +from libcst import matchers as m +from libcst.metadata import MetadataWrapper, ParentNodeProvider, PositionProvider, ScopeProvider + +from transformers import logging +from transformers.models.auto.configuration_auto import CONFIG_MAPPING_NAMES + + +logger = logging.get_logger(__name__) + + +AUTO_GENERATED_MESSAGE = """# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +# This file was automatically generated from {relative_path}. +# Do NOT edit this file manually as any edits will be overwritten by the generation of +# the file from the modular. If any change should be done, please apply the change to the +# {short_name} file directly. One of our CI enforces this. +# 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨 +""" + + +def get_module_source_from_name(module_name: str) -> str: + # Extract the source code from the module name + spec = importlib.util.find_spec(module_name) + if spec is None or spec.origin is None: + raise ValueError(f"Cannot open file associated with {module_name} module.") + + with open(spec.origin, "r", encoding="utf-8") as file: + source_code = file.read() + return source_code + + +def preserve_case_replace(text, patterns: dict, default_name: str): + # Create a regex pattern to match all variations + regex_pattern = "|".join(re.escape(key) for key in patterns) + compiled_regex = re.compile(f"(? str: + """From a model name in lowercase in the format `my_model`, return the cased name in the format `MyModel`.""" + alt_lowercase_name = lowercase_name.replace("_", "-") + if lowercase_name in CONFIG_MAPPING_NAMES: + return CONFIG_MAPPING_NAMES[lowercase_name].replace("Config", "") + elif alt_lowercase_name in CONFIG_MAPPING_NAMES: + return CONFIG_MAPPING_NAMES[alt_lowercase_name].replace("Config", "") + else: + return "".join(x.title() for x in lowercase_name.split("_")) + + +def get_lowercase_name(cased_name: str) -> str: + """From a model name in Camelcase in the format `MyModel`, return the lowercase name in the format `my_model`.""" + inverse_mapping = {value: key for key, value in CONFIG_MAPPING_NAMES.items()} + if cased_name + "Config" in inverse_mapping: + return inverse_mapping[cased_name + "Config"] + else: + return "_".join([s.lower() for s in re.findall(r"[A-Z][^A-Z]*", cased_name)]) + + +class ReplaceNameTransformer(m.MatcherDecoratableTransformer): + """A transformer that replaces `old_name` with `new_name` in comments, string and any references. + It should take into account name like `MyNewModel`, or `my_new_model`. Without using the AUTO_MAPPING. + Supported renaming patterns: + - llama -> my_new_model and my_new_model -> llama + - Llama -> MyNewModel and MyNewModel -> Llama + - LLAMA -> MY_NEW_MODEL and MY_NEW_MODEL -> LLAMA + - LLaMa -> MyNewModel abd MyNewModel -> Llama + """ + + def __init__(self, old_name: str, new_name: str, original_new_model_name: str = "", only_doc: bool = False): + super().__init__() + old_name = old_name.replace("-", "_") + new_name = new_name.replace("-", "_") + self.old_name = old_name + self.new_name = new_name + self.cased_new_name = get_cased_name(self.new_name) + self.cased_old_name = get_cased_name(self.old_name) + self.patterns = { + old_name: new_name, + old_name.upper(): new_name.upper(), + # For some old models, `self.cased_old_name` == `old_name.upper()` in which case this overwrite previous entry + self.cased_old_name: self.cased_new_name, + } + # In case new_name is a prefix alias, and not the original new model name + self.original_new_model_name = original_new_model_name + self.only_doc = only_doc + + def _replace_name(self, original_node, updated_node): + if re.findall(r"# Copied from", updated_node.value): + return cst.RemoveFromParent() + update = preserve_case_replace(updated_node.value, self.patterns, self.cased_new_name) + return updated_node.with_changes(value=update) + + @m.leave(m.SimpleString() | m.Comment()) + def replace_name(self, original_node, updated_node): + return self._replace_name(original_node, updated_node) + + def leave_Name(self, original_node, updated_node): + if not self.only_doc: + return self._replace_name(original_node, updated_node) + return updated_node + + def leave_ImportFrom(self, original_node, updated_node): + """ + The imports from other file types (configuration, processing etc) should use original model name. + Also, no replaces on absolute imports (e.g. `from mamba_ssm import ...`) + """ + if len(original_node.relative) == 0: # no replaces on absolute imports + return original_node + if self.original_new_model_name != self.new_name and m.matches(updated_node.module, m.Name()): + patterns = "|".join(ALL_FILE_TYPES) + regex = rf"({patterns})_{self.new_name}" + new_source = re.sub( + regex, lambda m: f"{m.group(1)}_{self.original_new_model_name}", updated_node.module.value + ) + updated_node = updated_node.with_changes(module=updated_node.module.with_changes(value=new_source)) + return updated_node + + +DOCSTRING_NODE = m.SimpleStatementLine( + body=[ + m.Expr( + value=m.SimpleString( + # match anything between """ """ + value=m.MatchIfTrue(lambda value: re.search(r"\"\"\"[\s\S]*\"\"\"", value) is not None) + ) + ) + ] +) + + +def SUPER_CALL_NODE(func_name): + return m.Call(func=m.Attribute(value=m.Call(func=m.Name("super")), attr=m.Name(func_name))) + + +def is_call_to_super(node, func_name): + return m.matches( + node, m.SimpleStatementLine(body=[m.Return(SUPER_CALL_NODE(func_name)) | m.Expr(SUPER_CALL_NODE(func_name))]) + ) + + +def get_full_attribute_name(node: Union[cst.Attribute, cst.Name]) -> Optional[str]: + """Get the full name of an Attribute or Name node (e.g. `"nn.Module"` for an Attribute representing it). If the + successive value of an Attribute are not Name nodes, return `None`.""" + if m.matches(node, m.Name()): + return node.value + elif m.matches(node, m.Attribute()): + if not m.matches(node.attr, m.Name()): + return None + name = node.attr.value + new_node = node.value + while m.matches(new_node, m.Attribute()): + if not m.matches(new_node.attr, m.Name()): + return None + name = new_node.attr.value + "." + name + new_node = new_node.value + if not m.matches(new_node, m.Name()): + return None + return new_node.value + "." + name + return None + + +# Transformer class to replace ClassB.call_to_method and ClassB().call_to_method with super().call_to_method +class ReplaceMethodCallTransformer(cst.CSTTransformer): + def __init__(self, all_bases: set[str]): + self.all_bases = all_bases + + def leave_Attribute(self, original_node: cst.Attribute, updated_node: cst.Attribute) -> cst.CSTNode: + # Handle ClassB.call_to_method or module.classB.call_to_method + if ( + m.matches(original_node.value, m.Name() | m.Attribute()) + and get_full_attribute_name(original_node.value) in self.all_bases + and m.matches(original_node.attr, m.Name()) + ): + # Replace with super().call_to_method + return updated_node.with_changes( + value=cst.Call(cst.Name("super")), + ) + # Handle ClassB().call_to_method or module.ClassB().call_to_method + elif ( + m.matches(original_node.value, m.Call()) + and m.matches(original_node.value.func, m.Name() | m.Attribute()) + and get_full_attribute_name(original_node.value.func) in self.all_bases + and m.matches(original_node.attr, m.Name()) + ): + # Replace with super().call_to_method + return updated_node.with_changes(value=cst.Call(cst.Name("super"))) + return updated_node + + def leave_Call(self, original_node: cst.Call, updated_node: cst.Call) -> cst.CSTNode: + # Check if the function being called is of the form ClassB().func_a or ClassB.func_a + if m.matches(original_node.func, m.Attribute()) and ( + # Match ClassB().func_a(...) or module + ( + m.matches(original_node.func.value, m.Call()) + and m.matches(original_node.func.value.func, m.Name() | m.Attribute()) + and get_full_attribute_name(original_node.func.value.func) in self.all_bases + ) + or + # Match ClassB.func_a(...) + ( + m.matches(original_node.func.value, m.Name() | m.Attribute()) + and get_full_attribute_name(original_node.func.value) in self.all_bases + ) + ): + # Check if the first argument is 'self', and remove it + if len(original_node.args) > 0 and m.matches(original_node.args[0].value, m.Name("self")): + # Create the new argument list without 'self' + new_args = updated_node.args[1:] + else: + new_args = updated_node.args + + return updated_node.with_changes(args=new_args) + return updated_node + + +class SuperTransformer(cst.CSTTransformer): + METADATA_DEPENDENCIES = (ParentNodeProvider,) + + def __init__(self, python_module: cst.Module, original_modeling_methods, modular_methods, all_bases=None): + self.python_module = python_module + self.original_modeling_methods = original_modeling_methods + self.modular_methods = modular_methods + self.all_assign_target = {} + self.deleted_targets = {} # child node can delete some arguments + self.all_bases = all_bases or [] + self.transformer = ReplaceMethodCallTransformer(set(self.all_bases)) + + def update_body(self, existing_body, new_statements): + """ + Helper method to update the body by removing duplicates before adding new statements. + `existing_body` is the body of the original method, the parent class + `new_statements` are the additional statements + """ + deduplicated_new_body = [] + existing_nodes = set() + for node in new_statements: + if m.matches(node, m.SimpleStatementLine(body=[m.Assign()])): + target = self.python_module.code_for_node(node.body[0].targets[0].target) + self.all_assign_target[target] = node + if m.matches(node, m.SimpleStatementLine(body=[m.Del()])): + target = self.python_module.code_for_node(node.body[0].target) + self.deleted_targets[target] = node + + for stmt in existing_body: + if m.matches(stmt, m.SimpleStatementLine(body=[m.Assign()])): + target = self.python_module.code_for_node(stmt.body[0].targets[0].target) + if target in self.deleted_targets: + continue + if target in self.all_assign_target: + stmt = self.all_assign_target[target] + # Skip the docstring (will be added later on, at the beginning) + elif m.matches(stmt, DOCSTRING_NODE): + continue + comment_less_code = re.sub(r"#.*", "", self.python_module.code_for_node(stmt)).strip() + comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() + deduplicated_new_body.append(stmt) + existing_nodes.add(comment_less_code) + + for node in new_statements: + code = self.python_module.code_for_node(node) + comment_less_code = re.sub(r"#.*", "", code).strip() + comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() + if node not in deduplicated_new_body and comment_less_code not in existing_nodes: + if not m.matches(node, m.SimpleStatementLine(body=[m.Del()])): + deduplicated_new_body.append(node) + existing_nodes.add(comment_less_code) + + deduplicated_new_body = self._fix_post_init_location(deduplicated_new_body) + + return deduplicated_new_body + + def _fix_post_init_location(self, new_body: list[cst.CSTNode]): + """Fix the location of the `post_init()` in the new body, if we added statements after the call to + `super()` (it needs to be the very last statement called)""" + # Fix the post_init() that has to be last + for i, node in enumerate(new_body): + code = self.python_module.code_for_node(node) + comment_less_code = re.sub(r"#.*", "", code).strip() + comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() + if "self.post_init(" in comment_less_code and i < len(new_body) - 1: + # Remove it and add it again at the end + new_body.pop(i) + new_body.append(node) + break + return new_body + + def _fix_init_location(self, new_body): + """Fix the location of the `super().__init__()` in the new body, if we had new statements before it.""" + start_index = 0 + for i, node in enumerate(new_body): + if m.matches(node, DOCSTRING_NODE) and i == start_index: + start_index += 1 + continue + code = self.python_module.code_for_node(node) + comment_less_code = re.sub(r"#.*", "", code).strip() + comment_less_code = re.sub(r"\ *\n", "\n", comment_less_code).strip() + if "super().__init__" in comment_less_code and i > start_index: + # Remove it and add it again at the top after the docstrings + node = new_body.pop(i) + new_body = new_body[:start_index] + [node] + new_body[start_index:] + break + return new_body + + def replace_super_calls(self, node: cst.BaseSuite, func_name: str) -> cst.BaseSuite: + """Updates the body of the input `node`'s `func_name` function by replacing calls + to super().func_name() with the source code of the parent class' `func_name`. + It keeps everything that is defined before `super().func_name()`. + """ + new_body = [] + modular_node_body = node.body + + for i, expr in enumerate(modular_node_body): + if is_call_to_super(expr, func_name): + original_modeling_method_body = self.original_modeling_methods[func_name].body.body + new_body.extend(self.update_body(original_modeling_method_body, modular_node_body[i + 1 :])) + new_body = self._fix_init_location(new_body) + return node.with_changes(body=new_body) + else: + expr = expr.visit(self.transformer) + if not m.matches(expr, m.SimpleStatementLine(body=[m.Del()])): + new_body.append(expr) + + return node.with_changes(body=new_body) + + def leave_FunctionDef(self, original_node: cst.FunctionDef, updated_node: cst.FunctionDef) -> cst.FunctionDef: + name = updated_node.name.value + if name in self.modular_methods: + new_body = self.replace_super_calls(updated_node.body, name) + return updated_node.with_changes(body=new_body, params=updated_node.params) + return updated_node + + +def find_all_dependencies( + dependency_mapping: dict[str, set], + start_entity: Optional[str] = None, + initial_dependencies: Optional[set] = None, + initial_checked_dependencies: Optional[set] = None, + return_parent: bool = False, +) -> Union[list, set]: + """Return all the dependencies of the given `start_entity` or `initial_dependencies`. This is basically some kind of + BFS traversal algorithm. It can either start from `start_entity`, or `initial_dependencies`. + + Args: + dependency_mapping (`Dict[str, set]`): + A mapping from entities (usually function/assignment names), to immediate dependencies. That is, for function names, + a mapping {"foo": {"bar", "test"}} would indicate that functions `bar` and `test` are immediately called + in `foo`'s definition. + start_entity (str | None, *optional*): + A key of `dependency_mapping`, indicating from which entity to start the search. + initial_dependencies (set | None, *optional*): + If `start_entity` is not provided, this can be used as an alternative. In this case, the search will continue + from all the entities in `initial_dependencies`, if they are in `dependency_mapping`. + initial_checked_dependencies (set | None, *optional*): + If provided, entities already present in `initial_checked_dependencies` will not be part of the returned dependencies. + return_parent (bool, *optional*): + If `True`, will return a list consisting of tuples (dependency, parent) instead of a simple set of dependencies. Note + that the order of the items in the list reflects the traversal order. Thus, no parent can ever appear before childs. + Returns: + A set of all the dependencies, or a list of tuples `(dependency, parent)` if `return_parent=True`. + + Example: + Given the following structure in the `modular_xxx.py` file: + ``` + def foo1(): + pass + + def foo2(): + pass + + def bar(): + foo1() + + def foobar(): + bar() + foo2() + + class MyLayer(SomeOtherModelLayer): + def forward(...): + foobar() + ``` + and the `dependency_mapping` created when visiting the `modular_xxx.py` file, we get: + ``` + dependency_mapping = {'bar': {'foo1'}, 'foobar': {'bar', 'foo2'}} + find_all_dependencies(dependency_mapping, start_entity='foobar', return_parent=True) + >>> [('bar', 'foobar'), ('foo2', 'foobar'), ('foo1', 'bar')] + ``` + That is, all the functions needed (and potentially their immediate parent) so that the function to be added + in MyLayer (`foobar`) can work correctly. + """ + if initial_dependencies is None and start_entity is not None: + initial_dependencies = dependency_mapping[start_entity] + if initial_checked_dependencies is None: + initial_checked_dependencies = set() + + dependency_queue = deque(initial_dependencies) + all_dependencies = set() + all_dependencies_with_parent = [] + checked_dependencies = set(initial_checked_dependencies) + parents = dict.fromkeys(initial_dependencies, start_entity) + while len(dependency_queue) > 0: + # Pick element to visit + current = dependency_queue.popleft() + if current not in checked_dependencies: + # Add the dependencies + all_dependencies.add(current) + all_dependencies_with_parent += [(current, parents[current])] + if current in dependency_mapping: + # Update dependency queue + dependency_queue.extend(dependency_mapping[current]) + parents.update(dict.fromkeys(dependency_mapping[current], current)) + # add visited node to the list + checked_dependencies.add(current) + + if not return_parent: + return all_dependencies + # no child can ever appear before its parent thanks to the queue (needed to add them at the correct location in the body later) + return all_dependencies_with_parent + + +# Top-level variables that match the following patterns will always use the value in the `modular_xxx.py` file +ASSIGNMENTS_REGEX_TO_KEEP = [r"_CHECKPOINT", r"_EXPECTED", r"_FOR_DOC", r"_HIDDEN_STATES_START_POSITION"] + +# Top-level variables that match the following patterns will use the value in the `modular_xxx.py` file only if they are not None +ASSIGNMENTS_REGEX_TO_KEEP_IF_NOT_NONE = [r"_DOCSTRING"] + + +class ClassDependencyMapper(CSTVisitor): + """A visitor which is designed to analyze a single class node to get all its dependencies that are shared with the set of + `global_names`. + """ + + def __init__( + self, class_name: str, global_names: set[str], objects_imported_from_modeling: Optional[set[str]] = None + ): + super().__init__() + self.class_name = class_name + self.dependencies = set() + self.global_names = global_names + self.objects_imported_from_modeling = ( + set() if objects_imported_from_modeling is None else objects_imported_from_modeling + ) + + def visit_Name(self, node): + if ( + node.value != self.class_name + and node.value in self.global_names + and node.value not in self.objects_imported_from_modeling + ): + self.dependencies.add(node.value) + + +def dependencies_for_class_node(node: cst.ClassDef, global_names: set[str]) -> set: + """Create immediate dependencies for a class node based on the `global_names`.""" + temp_module = cst.Module(body=[node]) + visitor = ClassDependencyMapper(node.name.value, global_names) + temp_module.visit(visitor) + return visitor.dependencies + + +def augmented_dependencies_for_class_node( + node: cst.ClassDef, mapper: "ModuleMapper", objects_imported_from_modeling: Optional[set[str]] = None +) -> set: + """Create augmented dependencies for a class node based on a `mapper`. + Augmented dependencies means immediate dependencies + recursive function and assignments dependencies. + """ + temp_module = cst.Module(body=[node]) + visitor = ClassDependencyMapper(node.name.value, set(mapper.global_nodes.keys()), objects_imported_from_modeling) + temp_module.visit(visitor) + return mapper.augment_dependencies(visitor.dependencies) + + +# All the potential file types to create +ALL_FILE_TYPES = ( + "modeling", + "configuration", + "tokenization", + "processing", + "image_processing", + "video_processing", + "feature_extraction", +) + + +class ModuleMapper(CSTVisitor, ABC): + """An abstract visitor class which analyses a module, creating a mapping of dependencies for classes, functions and assignments. + Class dependencies are computed with `compute_class_dependencies()`, while function and assignment dependencies are stored in + `self.object_recursive_dependency_mapping` (can be computed by `_compute_recursive_object_dependencies()`). + It defines common visiting patterns (i.e. common visit_xxx/leave_xxx functions) between the modular file and the + modeling files that will be visited. + """ + + METADATA_DEPENDENCIES = (ParentNodeProvider, PositionProvider) + + def __init__(self, python_module: cst.Module): + # fmt: off + self.python_module: cst.Module = python_module # original cst.Module being visited + self.classes: dict[str, cst.ClassDef] = {} # mapping from class names to Nodes (it will be ordered by default!!) + self.imports = [] # stores all import statements + self.functions: dict[str, cst.FunctionDef] = {} # mapping of global scope function names to Nodes + self.object_dependency_mapping = defaultdict(set) # immediate function/assignment dependency mapping (i.e. dependencies immediately in the function/assignment definition) + self.assignments: dict[str, cst.SimpleStatementLine] = {} # mapping of global assignments names to Nodes + self.current_function = None # this keeps track of the current module-scope function + self.current_class = None # this keeps track of the current module-scope class + self.current_assignment = None # this keeps track of the current module-scope assignment + # this keeps track of objects imported from modeling files (`from .configuration import Config`) -> `Config` should not be a dependency + self.objects_imported_from_modeling = set() + # regex pattern joining every possible file type + self.match_patterns = "|".join(ALL_FILE_TYPES) + # fmt: on + + def visit_ImportFrom(self, node): + """This keeps track of objects imported from neighbor modeling files (e.g. in `modeling_xxx.py, we have + `from .configuration_xxx import Config`, then `Config` should be recorded as it is not a dependency that needs + to be added (because it will be part of the imports)""" + import_module = self.python_module.code_for_node(node.module) + import_statement = "." * len(node.relative) + import_module + if re.search(rf"^\.({self.match_patterns})_.*", import_statement): + for imported_object in node.names: + # If an alias is present, we record it and not the original name + if imported_object.evaluated_alias is not None: + self.objects_imported_from_modeling.add(imported_object.evaluated_alias) + else: + self.objects_imported_from_modeling.add(imported_object.evaluated_name) + + def visit_SimpleStatementLine(self, node): + """ + Global Assigns like `GEMMA_INPUT_DOCSTRING = 'THIS IS THE INPUT'` and all import statements + are extracted and saved in their corresponding dict. They are then used when updating dependency mappings. + """ + parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) + simple_top_level_assign_structure = m.SimpleStatementLine( + body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])] + ) + simple_top_level_variable_indexing = m.SimpleStatementLine( + body=[m.Assign(targets=[m.AssignTarget(target=m.Subscript(value=m.Name()) | m.Attribute(value=m.Name()))])] + ) + + if m.matches(parent_node, m.Module()): + if m.matches(node, simple_top_level_assign_structure): + left_hand_side = node.body[0].targets[0].target.value + self.current_assignment = left_hand_side + self.assignments[left_hand_side] = node + # This corresponds to a global variable being indexed or having an attribute look-up + elif m.matches(node, simple_top_level_variable_indexing): + indexed_variable = node.body[0].targets[0].target.value.value + # We should follow any dependencies relative to the variable being indexed + self.current_assignment = indexed_variable + # The indexing node should be directly added as a dependency of the indexed variable (register the node with a "fake" name) + node_name = self.python_module.code_for_node(node) + self.assignments[node_name] = node + self.object_dependency_mapping[indexed_variable].add(node_name) + elif m.matches(node, m.SimpleStatementLine(body=[m.Import() | m.ImportFrom()])): + self.imports.append(node) + + def leave_SimpleStatementLine(self, node): + # No need to check for the parent here -> everytime we exit one, it should be None anyway independently of where the + # SimpleStatement is located + self.current_assignment = None + + def visit_FunctionDef(self, node): + parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) + if m.matches(parent_node, m.Module()): + self.current_function = node.name.value + self.functions[node.name.value] = node + + def leave_FunctionDef(self, node): + parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) + if m.matches(parent_node, m.Module()): + self.current_function = None + + def visit_If(self, node): + # If we are inside a function, do not add the import to the list of imports + if self.current_function is None and self.current_class is None: + for stmt in node.body.body: + if m.matches(stmt, m.SimpleStatementLine(body=[m.ImportFrom() | m.Import()])): + self.imports.append(node) + + def visit_ClassDef(self, node: ClassDef) -> None: + """Record class nodes to create their dependencies at the end.""" + self.classes[node.name.value] = node + self.current_class = node.name.value + + def leave_ClassDef(self, node): + self.current_class = None + + def visit_Name(self, node: cst.Call): + """This is used to create a mapping from module-scope functions and assignments to objects used inside them.""" + if self.current_function is not None: + self.object_dependency_mapping[self.current_function].add(node.value) + if self.current_assignment is not None: + self.object_dependency_mapping[self.current_assignment].add(node.value) + + def leave_Module(self, node): + """When leaving the module, we store the position of each global scoped node to allow sorting the dependencies + based on their position in the code later. We use the PositionProvider metadata wrapper for this. + We also make sure to update `self.object_dependency_mapping` so that it contains only names recorded in + `self.global_nodes`. + """ + # assign all nodes + self.global_nodes = {**self.assignments, **self.classes, **self.functions} + # now sort the class dependency_mapping based on the position of the nodes + self.start_lines = {} + for id, node in self.global_nodes.items(): + self.start_lines[id] = self.get_metadata(cst.metadata.PositionProvider, node).start.line + + def _restrict_dependencies_to_known_entities(self): + """Since we added every Name as part of `self.object_dependency_mapping`, we need to remove those that + are not part of the recorded objects in `self.global_nodes` (i.e. built-in variables, imports, etc). + This should be called only after all merging operations have been finalized!!""" + global_objects = set(self.global_nodes.keys()) + for object_name, dependencies in self.object_dependency_mapping.items(): + self.object_dependency_mapping[object_name] = {dep for dep in dependencies if dep in global_objects} + + def _compute_recursive_object_dependencies(self) -> dict[str, set]: + """Based on immediate dependency mapping, create the recursive dependency mapping. For example, given the + following file: + ``` + def foo(): + pass + + def bar(): + foo() + + def test(): + bar() + ``` + this visitor can only record immediate dependencies, i.e. it will record the following + `self.object_dependency_mapping = {"test": {"bar"}, "bar": {"foo}}`. This function is used to create + the recursive mapping, i.e. `recursive_dependencies = {"test": {"bar", "foo"}, "bar": {"foo}}`. + """ + recursive_dependencies = {} + for object_name in self.object_dependency_mapping: + all_dependencies = find_all_dependencies(self.object_dependency_mapping, start_entity=object_name) + recursive_dependencies[object_name] = all_dependencies + return recursive_dependencies + + def augment_dependencies(self, dependencies: set[str]) -> set[str]: + """For a set of `dependencies`, augment them by adding all potential dependencies of the **functions** and + **assignments** present in the `dependencies`. + """ + new_dependencies = dependencies.copy() + # Go through the set of dependencies + for dep in tuple(dependencies): + if dep in self.object_recursive_dependency_mapping: + new_dependencies.update(self.object_recursive_dependency_mapping[dep]) + return new_dependencies + + def compute_class_dependencies(self): + """For each visited class, find its dependencies based on visiting the current file + potential merged dependencies.""" + self.class_dependency_mapping = {} + for class_name, class_node in self.classes.items(): + dependencies = dependencies_for_class_node(class_node, set(self.global_nodes.keys())) + # Correctly augment class dependencies with all needed objects + self.class_dependency_mapping[class_name] = self.augment_dependencies(dependencies) + + @abstractmethod + def compute_relative_order(self, missing_dependencies: set) -> dict[str, int]: + raise NotImplementedError + + +class ModelFileMapper(ModuleMapper): + """A mapper designed to parse modeling files (like `modeling_llama.py`). When encountering such a file + in the `modular_xxx.py` file, we need to correctly visit it and merge the dependencies of the modular and current file. + For this reason, this class should only be instantiated from the class method `visit_and_merge_dependencies`, which takes + care of correctly merging dependencies, then finalizes all dependency graph computations. + Note that we only merge functions and assignments here, as classes will be treated later on as they may be modified. + For example, if you redefine `apply_rotary_pos_emb()` in the modular, the new node should be used in the dependencies + of the modeling files as well. + """ + + def __init__(self, python_module: cst.Module): + super().__init__(python_module) + + def compute_relative_order(self, missing_dependencies: set[str]) -> dict[str, int]: + """Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that + will be created based on the modular. + """ + relative_order = {} + idx = 0 + classes = sorted( + [dep for dep in tuple(missing_dependencies) if dep in self.classes], key=lambda x: self.start_lines[x] + ) + # This is because for merged dependencies, we only have relative order in the other visited file, so we need + # to track dependency order relative to a given class + if len(classes) > 0 and not hasattr(self, "class_dependency_mapping"): + raise ValueError("Cannot correctly find the relative order of the dependencies.") + + remaining_dependencies = missing_dependencies.copy() + + # Start by tracking relative order class by class + for class_name in classes: + class_dependencies = tuple(self.class_dependency_mapping[class_name] & remaining_dependencies) + original_dependencies = [] + merged_dependencies = [] + # We need to differentiate between nodes that were already present (we can get relative order globally) and + # nodes that were merged (we can get relative order only relative to the class the dependencies relate to) + for class_dep in class_dependencies: + if class_dep in self.start_lines: + original_dependencies.append(class_dep) + else: + merged_dependencies.append(class_dep) + # We need to sort deterministically before actual sorting, so that entries missing (i.e. with value 1e10) + # will always get the same order independently of the system (they come from a set, which has no deterministic order) + original_dependencies = sorted(original_dependencies, reverse=True) + # Sort both list according to the order in their respective file + original_dependencies = sorted(original_dependencies, key=lambda x: self.start_lines.get(x, 1e10)) + merged_dependencies = sorted(merged_dependencies, key=lambda x: self.modular_file_start_lines[x]) + + # Add all original node first, then merged ones + for dep in original_dependencies + merged_dependencies: + remaining_dependencies.remove(dep) + relative_order[dep] = idx + idx += 1 + # Add the class itself (it can sometimes already be present if the order of classes in the source file + # does not make sense, i.e. a class is used somewhere before being defined like in `rt_detr`...) + if class_name in remaining_dependencies: + remaining_dependencies.remove(class_name) + relative_order[class_name] = idx + idx += 1 + + # Now add what still remains + remaining_dependencies = tuple(remaining_dependencies) + original_dependencies = [] + merged_dependencies = [] + for dep in remaining_dependencies: + if dep in self.modular_file_start_lines: + merged_dependencies.append(dep) + else: + original_dependencies.append(dep) + # We need to sort deterministically before actual sorting, so that entries missing (i.e. with value 1e10) + # will always get the same order independently of the system (they come from a set, which has no deterministic order) + original_dependencies = sorted(original_dependencies, reverse=True) + # Sort both list according to the order in their respective file + original_dependencies = sorted(original_dependencies, key=lambda x: self.start_lines.get(x, 1e10)) + merged_dependencies = sorted(merged_dependencies, key=lambda x: self.modular_file_start_lines[x]) + + # Add all original node first, then merged ones + for dep in original_dependencies + merged_dependencies: + relative_order[dep] = idx + idx += 1 + + return relative_order + + def _merge_functions(self, functions: dict[str, cst.CSTNode], object_mapping: dict[str, set]): + """Update the global nodes and function dependency mapping with those from the modular file. + + Merging rule: if any function with the same name was redefined in the modular, use it and its dependencies + instead of the original ones (this may mean to add new functions as well, if any redefined function uses a new one). + """ + # Add/overwrite all needed function nodes and dependencies + self.functions.update(functions) + self.object_dependency_mapping.update({obj: dep for obj, dep in object_mapping.items() if obj in functions}) + # Add them to global nodes + self.global_nodes.update(self.functions) + + def _merge_assignments(self, assignments: dict[str, cst.CSTNode], object_mapping: dict[str, set]): + """Update the global nodes with the assignment from the modular file. + + Merging rule: if any assignment with the same name was redefined in the modular, we use it and its dependencies ONLY if it matches + a pattern in `ASSIGNMENTS_REGEX_TO_KEEP_IF_NOT_NONE` and its value is not None, or if it matches a pattern in `ASSIGNMENTS_REGEX_TO_KEEP. + Otherwise, we use the original value and dependencies. This rule was chosen to avoid having to rewrite the big docstrings. + """ + for assignment, node in assignments.items(): + should_keep = any(re.search(pattern, assignment) for pattern in ASSIGNMENTS_REGEX_TO_KEEP) + + should_keep_if_not_none = any( + re.search(pattern, assignment) for pattern in ASSIGNMENTS_REGEX_TO_KEEP_IF_NOT_NONE + ) and not (hasattr(node.body[0].value, "value") and node.body[0].value.value == "None") + + if should_keep or should_keep_if_not_none or assignment not in self.assignments: + self.assignments[assignment] = node + if assignment in object_mapping: + self.object_dependency_mapping[assignment] = object_mapping[assignment] + # Add them to global nodes + self.global_nodes.update(self.assignments) + + def _merge_classes(self, classes: dict[str, cst.CSTNode]): + """Update the global nodes with the new classes from the modular (i.e. classes which do not exist in current file, and + are not imported). We do NOT update any dependency mapping here. This is because we only need the names of newly defined + classes in the modular to be discoverable when computing dependencies for new nodes later on. For this reason, we + do not add the new classes to `self.classes`, but only to `global_nodes`. + """ + # Add/overwrite all needed function nodes and dependencies + self.global_nodes.update( + { + name: node + for name, node in classes.items() + if name not in self.classes and name not in self.objects_imported_from_modeling + } + ) + + def merge_modular_dependencies(self, classes, functions, assignments, object_mapping, start_lines): + """Merge classes, functions and assignments from the modular definitions into the current module file, + then record the relative order of all nodes. + Note: This function takes care of updating `global_nodes` and `object_recursive_dependency_mapping` as well after the + merge with other files dependencies. + """ + self._merge_functions(functions, object_mapping) + self._merge_assignments(assignments, object_mapping) + self._merge_classes(classes) + self.modular_file_start_lines = start_lines + + # Restrict the dependency mappings to the known entities to avoid Python's built-ins and imports + self._restrict_dependencies_to_known_entities() + # Create the global mapping of recursive dependencies for functions and assignments + self.object_recursive_dependency_mapping = self._compute_recursive_object_dependencies() + + @classmethod + def visit_and_merge_dependencies( + cls, module: cst.Module, classes, functions, assignments, object_mapping, start_lines + ) -> "ModelFileMapper": + wrapper = MetadataWrapper(module) + mapper = cls(module) + wrapper.visit(mapper) + # Merge dependencies + mapper.merge_modular_dependencies(classes, functions, assignments, object_mapping, start_lines) + # Create the class dependencies graph + mapper.compute_class_dependencies() + return mapper + + +def common_partial_suffix(str1: str, str2: str) -> str: + """Return the biggest common suffix between 2 strings. If one string is a full suffix of the other string, + we do not consider it a common suffix and return `""`""" + common_suffix = "" + for i in range(1, min(len(str1), len(str2)) + 1): + if str1[-i] == str2[-i]: + common_suffix = str1[-i] + common_suffix + else: + break + # We do not allow full string suffix + if common_suffix == str1 or common_suffix == str2: + common_suffix = "" + return common_suffix + + +def replace_class_node( + mapper: ModelFileMapper, modular_class_node: cst.ClassDef, renamed_super_class: str, original_super_class: str +) -> cst.ClassDef: + """ + Replace a class node which inherits from another modeling class. This function works in the following way: + - start from the methods and class attributes of the original modeling code node, and replace their definition + if overriden in the modular + - append all new methods and class attributes defined in the child class + - all potential method/class docstrings and decorators use the ones found in modular if any, else in original modeling + - replace all calls to super() with the unravelled code + + Args: + mapper (`ModelFileMapper`): + The mapper corresponding to the visited file from which the modular class node inherits. + modular_class_node (`cst.ClassDef`): + The class node as found in the modular file. + renamed_super_class (`str`): + The name of the class from which `modular_class_node` inherits after automatic renaming. + original_super_class (`str`): + The name of the class from which `modular_class_node` inherits before automatic renaming. + + Returns: + A new class node corresponding to the modular definition. + """ + all_bases = [get_full_attribute_name(k.value) for k in modular_class_node.bases] + if any(base is None for base in all_bases): + raise ValueError(f"Could not parse the name of the bases for {modular_class_node.name.value}") + + original_modeling_node = mapper.classes[renamed_super_class] + # Always use the new name of the class (in case we use e.g. `ColPaliForRetrieval` inheriting from `PaliGemmaForConditionalGeneration`) + new_class_name = modular_class_node.name + + # If the new class name is different from the renamed super class name, we need to update the docstrings/comments accordingly + if new_class_name.value != renamed_super_class: + common_suffix = common_partial_suffix(new_class_name.value, renamed_super_class) + # Note that this works even without common prefix, in which case it does not replace anything + old, new = renamed_super_class.replace(common_suffix, ""), new_class_name.value.replace(common_suffix, "") + temp_module = cst.Module(body=[original_modeling_node]) + original_modeling_node = temp_module.visit( + ReplaceNameTransformer(get_lowercase_name(old), get_lowercase_name(new), only_doc=True) + ).body[0] + + # If we explicitly passed a new base with common suffix to an old base, it is for switching the prefix + # e.g. if the "natural" parent class is `PreTrainedModel` but we wanted to rename it to `PreTrainedVisionModel` + additional_bases = [base for base in all_bases if base != original_super_class] + new_class_bases = [] + for original_base in original_modeling_node.bases: + new_base = original_base + # we only potentially switch base for Name-based bases, not Attribute + if m.matches(original_base.value, m.Name()): + original_base_name = original_base.value.value + for additional_base_name in additional_bases: + suffix = common_partial_suffix(original_base_name, additional_base_name) + if len(suffix) > 0 and suffix[0].isupper(): + new_name_node = original_base.value.with_changes(value=additional_base_name) + new_base = original_base.with_changes(value=new_name_node) + break + new_class_bases.append(new_base) + + # Use class decorators redefined in modular file if any + new_class_decorators = ( + modular_class_node.decorators if len(modular_class_node.decorators) > 0 else original_modeling_node.decorators + ) + + # Compute new class docstring + original_modeling_docstring = [ + node for node in original_modeling_node.body.body if m.matches(node, DOCSTRING_NODE) + ] + modular_docstring = [node for node in modular_class_node.body.body if m.matches(node, DOCSTRING_NODE)] + # Use class docstring in modular if any, else original modeling code docstring + new_class_docstring = modular_docstring if len(modular_docstring) > 0 else original_modeling_docstring + + # Compute new class attributes + original_modeling_class_attributes = {} + for node in original_modeling_node.body.body: + if m.matches(node, m.SimpleStatementLine(body=[m.Assign()])): + original_modeling_class_attributes[node.body[0].targets[0].target.value] = node + elif m.matches(node, m.SimpleStatementLine(body=[m.AnnAssign()])): + original_modeling_class_attributes[node.body[0].target.value] = node + + modular_class_attributes = {} + for node in modular_class_node.body.body: + if m.matches(node, m.SimpleStatementLine(body=[m.Assign()])): + modular_class_attributes[node.body[0].targets[0].target.value] = node + elif m.matches(node, m.SimpleStatementLine(body=[m.AnnAssign()])): + modular_class_attributes[node.body[0].target.value] = node + + # Use all original modeling attributes, and potentially override some with values in the modular + new_class_attributes = list({**original_modeling_class_attributes, **modular_class_attributes}.values()) + + # Check class methods defined in the modular and associated modeling + original_modeling_methods = {} + for node in original_modeling_node.body.body: + if m.matches(node, m.FunctionDef()): + # Due to the @property and @name.setter decorators, methods can sometimes have the same name, so we need a way + # to separate them + if node.name.value in original_modeling_methods: + # If it's already present, and the decorator is @property, it means the node already added was the setter + if node.decorators[0].decorator.value == "property": + original_modeling_methods[f"{node.name.value}_setter"] = original_modeling_methods[node.name.value] + original_modeling_methods[node.name.value] = node + # In this case current node is the setter + else: + original_modeling_methods[f"{node.name.value}_setter"] = node + else: + original_modeling_methods[node.name.value] = node + modular_methods = {} + for node in modular_class_node.body.body: + if m.matches(node, m.FunctionDef()): + # Due to the @property and @name.setter decorators, methods can sometimes have the same name, so we need a way + # to separate them + if node.name.value in modular_methods: + # If it's already present, and the decorator is @property, it means the node already added was the setter + if node.decorators[0].decorator.value == "property": + modular_methods[f"{node.name.value}_setter"] = modular_methods[node.name.value] + modular_methods[node.name.value] = node + # In this case current node is the setter + else: + modular_methods[f"{node.name.value}_setter"] = node + else: + modular_methods[node.name.value] = node + + new_class_methods = [] + # Iterate over the methods of the original modeling code, and add them to the list of methods to add + for name, node in original_modeling_methods.items(): + # If the method was redefined in modular, make appropriate changes to the node + if name in modular_methods: + # Get the corresponding method node in modular + modular_node = modular_methods[name] + + # If we match the pattern, we should avoid inheriting the method + if re.match(r"\ndef .*\(.*\):\n raise.*Error\(.*", mapper.python_module.code_for_node(modular_node)): + continue + + # Compute new method docstring + modeling_docstring = [node_ for node_ in node.body.body if m.matches(node_, DOCSTRING_NODE)] + modular_docstring = [node_ for node_ in modular_node.body.body if m.matches(node_, DOCSTRING_NODE)] + # Use method docstring in modular if any, else original modeling code docstring + new_body = ( + modular_node.body.body + if len(modular_docstring) > 0 + else modeling_docstring + list(modular_node.body.body) + ) + new_body = modular_node.body.with_changes(body=new_body) + + # Use arguments as defined in the modular + new_params = modular_node.params + + # If using the `**super_kwargs` syntax in modular, merge any existing modular arg with all the original modeling ones + kwarg_name = getattr(modular_node.params, "star_kwarg", None) + if kwarg_name and kwarg_name.name.value == "super_kwargs": + original_modeling_params = {k.name.value: k for k in node.params.params} + modular_params = {k.name.value: k for k in new_params.params[1:]} + new_param_list = list({**original_modeling_params, **modular_params}.values()) + new_params = new_params.with_changes(params=new_param_list, star_kwarg=node.params.star_kwarg) + + # Keep decorators in modular if any, else original decorators + new_decorators = modular_node.decorators if len(modular_node.decorators) > 0 else node.decorators + + # Keep return annotation in modular if any, else original return annotation + new_return_annotation = modular_node.returns if modular_node.returns else node.returns + + # Update the method node + node = node.with_changes( + body=new_body, + params=new_params, + decorators=new_decorators, + returns=new_return_annotation, + ) + + new_class_methods.append(node) + + # Port new methods that are defined only in modular-file and append at the end + for name, node in modular_methods.items(): + if name not in original_modeling_methods: + new_class_methods.append(node) + + # Recreate the whole new class body + new_class_body = new_class_docstring + new_class_attributes + new_class_methods + + # Replace the calls to `super()` of the redefined modular methods with the unrolled code + result_node = original_modeling_node.with_changes(body=cst.IndentedBlock(body=new_class_body)) + temp_module = cst.Module(body=[result_node]) + new_module = MetadataWrapper(temp_module) + new_replacement_class = new_module.visit( + SuperTransformer(temp_module, original_modeling_methods, modular_methods, all_bases) + ) + new_class_body = new_replacement_class.body[0].body # get the indented block + + return original_modeling_node.with_changes( + body=new_class_body, decorators=new_class_decorators, bases=new_class_bases, name=new_class_name + ) + + +TYPE_TO_FILE_TYPE = { + "Config": "configuration", + "Tokenizer": "tokenization", + "Processor": "processing", + "ImageProcessor": "image_processing", + "ImageProcessorFast": "image_processing*_fast", # "*" indicates where to insert the model name before the "_fast" suffix + "VideoProcessor": "video_processing", + "VideoProcessorInitKwargs": "video_processing", + "FastImageProcessorKwargs": "image_processing*_fast", + "FeatureExtractor": "feature_extraction", + "ProcessorKwargs": "processing", + "VideosKwargs": "processing", + "ImagesKwargs": "processing", + "TextKwargs": "processing", +} + + +def find_file_type(class_name: str, model_name: str) -> str: + """Based on a class name, find the file type corresponding to the class. + If the class name is `LlamaConfig` it will return `configuration`. + The list of suffixes is in `TYPE_TO_FILE_TYPE`. If there are no match, we match by default to `modeling` + """ + match_pattern = "|".join(TYPE_TO_FILE_TYPE.keys()) + # We remove the model name to avoid ambiguity, e.g. for `Sam2VideoProcessor`, + # removing `Sam2Video` ensures we match `Processor` instead of `VideoProcessor`. + match = re.search(rf"({match_pattern})$", class_name.replace(get_cased_name(model_name), "")) + if match: + file_type = TYPE_TO_FILE_TYPE[match.group(1)] + else: + file_type = "modeling" + return file_type + + +# These top-level variables will always appear at the very beginning of the file, in the order they are defined in +# this list (this is to avoid having variables at weird places, even if they are not used before) +VARIABLES_AT_THE_BEGINNING = ( + "logger", + "_CHECKPOINT_FOR_DOC", + "_CONFIG_FOR_DOC", +) + +# These specific modeling imports should not be visited as other modeling files +IMPORTS_TO_SKIP_IN_MODULAR = ("auto.modeling_auto",) + + +def append_new_import_node( + node: cst.CSTNode, unused_imports: set[str], added_names: set, imports_to_keep: list[cst.CSTNode] +): + """Insert the new `node` to the list of `imports_to_keep` in-place, if it is not part of the `unused_imports` or `added_names`. + Also modifies `added_names` in-place accordingly.""" + import_node = node.body[0] + names_to_keep = [] + for name in import_node.names: + name_value = name.evaluated_alias or name.evaluated_name + if name_value not in unused_imports and name_value not in added_names: + names_to_keep.append(name.with_changes(comma=cst.MaybeSentinel.DEFAULT)) + added_names.add(name_value) + if len(names_to_keep) > 0: + new_node = node.with_changes(body=[import_node.with_changes(names=names_to_keep)]) + imports_to_keep.append(new_node) + + +def get_needed_imports(body: dict[str, dict], all_imports: list[cst.CSTNode]) -> list[cst.CSTNode]: + """Get all the imports needed in the `body`, from the list of `all_imports`. + `body` is a dict with the following structure `{str: {"insert_idx": int, "node": cst.CSTNode}}`. + Note: we need to use `isinstance` on scope assignments, m.matches apparently does not work here yet! + """ + new_body = [k[1]["node"] for k in sorted(body.items(), key=lambda x: x[1]["insert_idx"])] + wrapper = MetadataWrapper(cst.Module(body=all_imports + new_body)) + scopes = set(wrapper.resolve(ScopeProvider).values()) + unused_imports = set() + import_ref_count = defaultdict(lambda: 0) + for scope in scopes: + for assignment in scope.assignments: + node = assignment.node + if isinstance(assignment, cst.metadata.Assignment) and isinstance(node, (cst.Import, cst.ImportFrom)): + ref_count = len(assignment.references) + name = assignment.name + import_ref_count[name] = max(ref_count, import_ref_count[name]) + # Similar imports may be redefined, and only used between their 1st and 2nd definition so if we already have + # a ref count > 0 at any point, the imports is actually used + unused_imports = {name for name, count in import_ref_count.items() if count <= 0 or name in body} + + imports_to_keep = [] + # We need to keep track of which names were already imported, because some import may be duplicated from multiple sources + # or be both protected and unprotected due to inconsistency between models + added_names = set() + existing_protected_statements = set() # str repr of the import nodes - does not work with the nodes directly + for node in all_imports: + if m.matches(node, m.If()): # handle safe imports + new_statements = [] + for stmt_node in node.body.body: + append_new_import_node(stmt_node, unused_imports, added_names, new_statements) + new_statements = [stmt for stmt in new_statements if str(stmt) not in existing_protected_statements] + if len(new_statements) > 0: + new_node = node.with_changes(body=node.body.with_changes(body=new_statements)) + imports_to_keep.append(new_node) + existing_protected_statements.update({str(stmt) for stmt in new_statements}) + else: + append_new_import_node(node, unused_imports, added_names, imports_to_keep) + + protected_import_nodes = [node for node in imports_to_keep if m.matches(node, m.If())] + usual_import_nodes = [node for node in imports_to_keep if not m.matches(node, m.If())] + + # Protected imports always appear at the end of all imports + return usual_import_nodes + protected_import_nodes + + +def split_all_assignment(node: cst.CSTNode, model_name: str) -> dict[str, cst.CSTNode]: + """Split the `__all__` assignment found in the modular between each corresponding files.""" + all_all_per_file = {} + assign_node = node.body[0] + if isinstance(assign_node.value, cst.List): + # Extract the elements from the list + all_all_to_add = defaultdict(list) + for element in assign_node.value.elements: + if isinstance(element.value, cst.SimpleString): + # Remove quotes and add the string to the elements list + class_name = element.value.value + file = find_file_type(element.value.evaluated_value, model_name) + all_all_to_add[file] += [class_name] + for file, new_alls in all_all_to_add.items(): + new_node = assign_node.with_changes( + value=cst.List(elements=[cst.Element(value=cst.SimpleString(value=k)) for k in new_alls]) + ) + all_all_per_file[file] = node.with_changes(body=[new_node]) + return all_all_per_file + + +class ModularFileMapper(ModuleMapper): + """This is a Mapper to visit a modular file (like `modular_llama.py`). It visits the whole file, recording dependency, + then visits all imported modeling files (like `modeling_llama.py`), and manages their mutual dependencies. + Calling the method `create_modules()` after visit will create all modules based on this modular file. + """ + + def __init__(self, python_module, new_name): + super().__init__(python_module) + # fmt: off + self.model_name = new_name # name of the model being defined. Should be in the format of `llama` or `layout_xlm` or `phi3` + + self.model_specific_imported_objects: dict[str, str] = {} # e.g. {"LlamaModel": "transformers.models.llama.modeling_llama"} + self.model_specific_modules: dict[str, cst.Module] = {} # e.g. {"transformers.models.llama.modeling_llama": cst.Module} + + self.all_all_to_add = {} + # fmt: on + + def visit_ImportFrom(self, node: cst.ImportFrom) -> None: + """When visiting imports from modeling files (i.e. `transformers.models.xxx`) we get the code, parse it, + and save it in `self.model_specific_modules` to later visit. The imported objects are saved in `self.model_specific_imported_objects`. + """ + import_module = self.python_module.code_for_node(node.module) + import_statement = "." * len(node.relative) + import_module + if any(import_to_skip in import_statement for import_to_skip in IMPORTS_TO_SKIP_IN_MODULAR): + return + if m.matches(node.module, m.Attribute()): + for imported_ in node.names: + _import = re.search( + rf"(?:transformers\.models\.)|(?:\.\.)\w+\.({self.match_patterns})_.*", import_statement + ) + if _import: + source = _import.group(1) + if source == "modeling" and "Config" in self.python_module.code_for_node(imported_): + raise ValueError( + f"You are importing {self.python_module.code_for_node(imported_)} from the modeling file. Import from the `configuration_xxxx.py` file instead" + ) + if import_module not in self.model_specific_modules: + if "models" not in import_module: + import_module = "models." + import_module + if "transformers" not in import_module: + import_module = "transformers." + import_module + source_code = get_module_source_from_name(import_module) + tree = cst.parse_module(source_code) + self.model_specific_modules[import_module] = tree + imported_object = self.python_module.code_for_node(imported_.name) + self.model_specific_imported_objects[imported_object] = import_module + if m.matches(node.module, m.Name()): + if "transformers" == import_module: + raise ValueError( + f"You are importing from {import_module} directly using global imports. Import from the correct local path" + ) + + def visit_SimpleStatementLine(self, node): + """If we visit an import statement not previously visited, record it. If we visit a module-scope assignment, + simply record it or, if it is `__all__`, split it between files where we should dispatch it. + """ + parent_node = self.get_metadata(cst.metadata.ParentNodeProvider, node) + simple_top_level_assign_structure = m.SimpleStatementLine( + body=[m.Assign(targets=[m.AssignTarget(target=m.Name())])] + ) + simple_top_level_variable_indexing = m.SimpleStatementLine( + body=[m.Assign(targets=[m.AssignTarget(target=m.Subscript(value=m.Name()) | m.Attribute(value=m.Name()))])] + ) + + if m.matches(parent_node, m.Module()): + if m.matches(node, m.SimpleStatementLine(body=[m.Import()])): + self.imports.append(node) + elif m.matches(node, m.SimpleStatementLine(body=[m.ImportFrom()])): + import_module = self.python_module.code_for_node(node.body[0].module) + import_statement = "." * len(node.body[0].relative) + import_module + if not ( + re.search(rf"(?:transformers\.models\.)|(?:\.\.)\w+\.({self.match_patterns})_.*", import_statement) + and not any(import_to_skip in import_statement for import_to_skip in IMPORTS_TO_SKIP_IN_MODULAR) + ): + self.imports.append(node) + elif m.matches(node, simple_top_level_assign_structure): + assigned_variable = node.body[0].targets[0].target.value + # __all__ is treated differently and not added to general assignments + if assigned_variable == "__all__": + self.all_all_to_add = split_all_assignment(node, self.model_name) + else: + self.current_assignment = assigned_variable + self.assignments[assigned_variable] = node + # This corresponds to a global variable being indexed or having an attribute look-up + elif m.matches(node, simple_top_level_variable_indexing): + indexed_variable = node.body[0].targets[0].target.value.value + # We should follow any dependencies relative to the variable being indexed + self.current_assignment = indexed_variable + # The indexing node should be directly added as a dependency of the indexed variable (register the node with a "fake" name) + node_name = self.python_module.code_for_node(node) + self.assignments[node_name] = node + self.object_dependency_mapping[indexed_variable].add(node_name) + + def leave_Module(self, node): + """When we leave the modular file, we do the following in order: + 1. for each modeling file found in the imports, rename it with the new model name, visit it, and update + its dependency graph with the new function and assignment definitions found in the modular + 2. update the modular dependency graph with the imported functions and assignments (found when visiting the matching files) + 3. compute the nested (recursive) function and assignment dependencies + """ + # Takes care of finalizing our visit + super().leave_Module(node) + + # 1. for each modeling file found in the imports, rename it with the new model name, visit it, and update dependencies + self.visited_modules = {} + self.renamers = {} + name_prefixes = self.infer_new_model_name() + for file, module in self.model_specific_modules.items(): + file_model_name = file.split(".")[-2] + new_name = name_prefixes[file] + renamer = ReplaceNameTransformer(file_model_name, new_name, self.model_name) + renamed_module = module.visit(renamer) + self.visited_modules[file] = ModelFileMapper.visit_and_merge_dependencies( + renamed_module, + self.classes, + self.functions, + self.assignments, + self.object_dependency_mapping, + self.start_lines, + ) + # We record it so that we can rename classes later the exact same way + self.renamers[file] = renamer + + # 2. in turn, we need to add the imported functions/assignments to the dependencies of the modular mapper, using the + # definitions found in the visited files + self.merge_model_specific_imports(self.visited_modules) + + # 3. compute the nested (recursive) function and assignment dependencies + self.object_recursive_dependency_mapping = self._compute_recursive_object_dependencies() + + # We need to keep track of which objects were imported directly into which modeling file to not add them wrongly later + # Note that we may visit several of the same file types, thus we save them per file type, not file + self.imported_objects_per_file = defaultdict(set) + for file, mapper in self.visited_modules.items(): + file_type = re.search(rf"^transformers\.models\.\w+\.({self.match_patterns})_.*", file).group(1) + self.imported_objects_per_file[file_type].update(mapper.objects_imported_from_modeling) + + def merge_model_specific_imports(self, visited_modules): + """Merge the functions and assignments imported from the modeling files to the modular nodes and dependency graph, + based on the visited files.""" + self.start_lines_file_mapping = {} + self.added_objects_file_mapping = {} + for object_name, file in self.model_specific_imported_objects.items(): + visited_module = visited_modules[file] + self.start_lines_file_mapping[file] = visited_module.start_lines + # Add functions and their dependencies + if object_name in visited_module.functions and object_name not in self.functions: + self.functions[object_name] = visited_module.functions[object_name] + self.added_objects_file_mapping[object_name] = file + dependencies = visited_module.object_dependency_mapping.get(object_name, None) + if dependencies is not None: + self.object_dependency_mapping[object_name] = dependencies + for dep in dependencies: + if dep not in self.global_nodes: + self.added_objects_file_mapping[dep] = file + self.functions[dep] = visited_module.global_nodes[dep] + + # Add/overwrite the imported functions to other visited modules as well, in case it is absent/different + # in he modeling source file of the inherited class. See `examples/modular-tranformers/modular_switch_function.py` + # and `examples/modular-tranformers/modular_add_function.py` for examples + recursive_dependencies = visited_module.object_recursive_dependency_mapping.get(object_name, set()) + node_recursive_dependencies_mapping = { + dep: visited_module.global_nodes[dep] for dep in recursive_dependencies + } + for filename, module_mapper in self.visited_modules.items(): + if filename != file: + module_mapper.global_nodes[object_name] = visited_module.functions[object_name] + if len(recursive_dependencies) > 0: + module_mapper.object_recursive_dependency_mapping[object_name] = recursive_dependencies + module_mapper.global_nodes.update(node_recursive_dependencies_mapping) + + # Add assignments and their dependencies + elif object_name in visited_module.assignments and object_name not in self.assignments: + self.assignments[object_name] = visited_module.assignments[object_name] + self.added_objects_file_mapping[object_name] = file + dependencies = visited_module.object_dependency_mapping.get(object_name, None) + if dependencies is not None: + self.object_dependency_mapping[object_name] = dependencies + for dep in dependencies: + if dep not in self.global_nodes: + self.added_objects_file_mapping[dep] = file + self.assignments[dep] = visited_module.global_nodes[dep] + + # Do not forget to re-assign all nodes after the merge + self.global_nodes = {**self.assignments, **self.classes, **self.functions} + # And restric dependencies to those nodes only + self._restrict_dependencies_to_known_entities() + + def compute_relative_order(self, missing_dependencies: set) -> dict[str, int]: + """Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that + will be created based on the modular. + """ + relative_order = {} + idx = 0 + + original_dependencies = [] + other_files_dependencies = defaultdict(list) + for dep in sorted(missing_dependencies): + if dep in self.added_objects_file_mapping: + file = self.added_objects_file_mapping[dep] + other_files_dependencies[file].append(dep) + else: + original_dependencies.append(dep) + # Sort all lists according to the order in their respective file + all_dependencies = [] + for file, dependencies in other_files_dependencies.items(): + sorted_dependencies = sorted(dependencies, key=lambda x: self.start_lines_file_mapping[file][x]) + all_dependencies += sorted_dependencies + all_dependencies += sorted(original_dependencies, key=lambda x: self.start_lines[x]) + + # Add all original node first, then merged ones (one file at a time) + for dep in all_dependencies: + relative_order[dep] = idx + idx += 1 + + return relative_order + + def infer_new_model_name(self) -> dict: + """Infer whether we are using a model name prefix different from the usual model name as defined from the filename. + This is useful e.g. when we define a new multi-modal model, and only the text part inherits from `LlamaModel`, + so we have something like: + ```python + class NewModelNameTextDecoderLayer(LlamaDecoderLayer): + pass + ``` + with the `Text` prefix added to the model name. + However, in case of multiple prefix used, we raise a warning and use the most frequent prefix, to avoid parsing + the same file multiple times and inconsistencies in the objects added from dependencies. + If the new prefix collides with a prefix of another class in the file where we are importing from, then we also + raise a warning, and use the default prefix (model name) to avoid collisions in dependencies. + """ + prefix_model_name_mapping = defaultdict(Counter) + cased_default_name = get_cased_name(self.model_name) + # Iterate over all new classes to get modeling super classes + for class_name, class_node in self.classes.items(): + modeling_bases = [ + k.value.value for k in class_node.bases if k.value.value in self.model_specific_imported_objects + ] + if len(modeling_bases) > 1: + raise ValueError( + f"{class_name} was defined with more than 1 model-specific super class. This is unsupported. We found {(*modeling_bases,)}." + ) + if len(modeling_bases) == 1: + filename = self.model_specific_imported_objects[modeling_bases[0]] + cased_model_name = cased_default_name # the default name prefix + suffix = common_partial_suffix(class_name, modeling_bases[0]) + if len(suffix) > 0 and suffix[0].isupper(): + cased_model_name = class_name.replace(suffix, "") + # If both the old model and new model share the last part of their name, is detected as a common + # suffix, but it should not be the case -> use the full name in this case + if len(cased_model_name) < len(cased_default_name) and cased_default_name in class_name: + cased_model_name = cased_default_name + prefix_model_name_mapping[filename].update([cased_model_name]) + + # Check if we found multiple prefixes for some modeling files + final_name_mapping = {} + for file, prefixes_counter in prefix_model_name_mapping.items(): + if len(prefixes_counter) > 1: + _, total = prefixes_counter.most_common(1)[0] + most_used_entities = [name for name, count in prefixes_counter.most_common() if count == total] + # if the default name is in the pool of equally used prefixes, use it, otherwise last encountered + final_name = cased_default_name if cased_default_name in most_used_entities else most_used_entities[-1] + else: + final_name = list(prefixes_counter)[0] + # Check if the prefix can be used without collisions in the names + old_cased_model_name = get_cased_name(file.split(".")[-2]) + old_model_name_prefix = final_name.replace(cased_default_name, old_cased_model_name) + # Raise adequate warning depending on the situation + has_prefix_collision = f"\nclass {old_model_name_prefix}" in get_module_source_from_name(file) + if final_name != cased_default_name and has_prefix_collision: + if len(prefixes_counter) > 1: + logger.warning( + f"We detected multiple prefix names when inheriting from {file}: {(*set(prefixes_counter),)}. However, the " + f"most used one, '{final_name}', is already present in the source file and will likely cause consistency " + f"issues. For this reason we fallback to the default prefix '{cased_default_name}' when grabbing args " + "and dependencies. Make sure to subclass the intermediate classes with the prefix you want (if different " + f"from '{cased_default_name}') or use a single prefix in all the modular (best)." + ) + else: + logger.warning( + f"We detected the use of the new default prefix {final_name} when inheriting from {file}. However, it is " + "already present in the source file and will likely cause consistency issues. For this reason we fallback " + f"to the default prefix '{cased_default_name}' when grabbing args and dependencies. Make sure to subclass " + f"the intermediate classes with the prefix you want (if different from '{cased_default_name}')" + ) + final_name = cased_default_name + elif len(prefixes_counter) > 1: + logger.warning( + f"We detected multiple prefix names when inheriting from {file}: {(*set(prefixes_counter),)}. We will only " + f"use the most used '{final_name}' prefix when grabbing args and dependencies. Make sure to subclass the " + f"intermediate classes with the prefix you want (if different from '{final_name}') or use a single prefix " + "in all the modular (best)." + ) + final_name_mapping[file] = get_lowercase_name(final_name) + + # Check we are not missing imported files + for file in self.model_specific_modules: + if file not in final_name_mapping: + final_name_mapping[file] = self.model_name + + return final_name_mapping + + +def check_dependencies_and_create_import_node( + file_type: str, new_dependencies: set[str], mapper: ModuleMapper, new_name: str +) -> tuple[set[str], dict[str, cst.CSTNode]]: + """Check that all class nodes in the `new_dependencies` belong to the correct `file_type`. If this is not the case, + we need to remove it from the dependencies, and create a new import to it instead. + This scenario may appear in the following case: + If a new class in the `modular_xxx.py` file does not belong to `type_xxx.py`, but is used somewhere in `other_type_xxx.py` + (e.g. as a type hint), but none of the visited files had a similar class, then it would be imported in `type_xxx.py` as + part of the standard dependency graph (because we never encountered an import towards this new class in any file). + For example imagine the following `modular.py`: + ``` + from ..llama.modeling_llama import LlamaModel + + class NewNameTextConfig(PretrainedConfig): + ... + + class NewNameConfig(PretrainedConfig): + ... + + class NewNameModel(LlamaModel): + config = NewNameConfig() + text_config = NewNameTextConfig() + ... + ``` + then without the help of this function, `NewNameTextConfig` would be imported in the `modeling_newname.py` as well as + `configuration_newname.py`, because `modeling_llama.py` tells us to not import `NewNameConfig`, but has no + knowledge of `NewNameTextConfig`. + """ + class_dependencies = {dep for dep in new_dependencies if m.matches(mapper.global_nodes[dep], m.ClassDef())} + corrected_dependencies = new_dependencies.copy() + new_imports = {} + for class_name in class_dependencies: + class_file_type = find_file_type(class_name, new_name) + # In this case, we need to remove it from the dependencies and create a new import instead + if class_file_type != file_type: + corrected_dependencies.remove(class_name) + import_statement = f"from .{class_file_type}_{new_name} import {class_name}" + new_imports[class_name] = cst.parse_statement(import_statement) + + return corrected_dependencies, new_imports + + +def get_class_node_and_dependencies( + modular_mapper: ModularFileMapper, class_name: str, node: cst.CSTNode, files: dict[str, dict] +) -> tuple[dict, str, dict]: + """Return a single class node (and all its dependency nodes), to be added to the `files`. It creates the new + class node based on the inherited classes if needed. Also returns any new imports of a new class defined in + the modular that we nay need. + """ + # An exception was already raised if this has len > 1 + model_specific_bases = [ + k.value.value for k in node.bases if k.value.value in modular_mapper.model_specific_imported_objects + ] + super_class = model_specific_bases[0] if len(model_specific_bases) == 1 else None + + file_type = find_file_type(class_name, modular_mapper.model_name) + file_to_update = files[file_type] + model_name = modular_mapper.model_name + + # This is used to avoid adding objects to the dependencies graph if they will be imported already + imported_objects = modular_mapper.imported_objects_per_file[file_type] + + # We need to replace the class node with the transformers (modeling file) super class node + if super_class is not None: + super_file_name = modular_mapper.model_specific_imported_objects[super_class] + + # Get the mapper corresponding to the inherited class + mapper = modular_mapper.visited_modules[super_file_name] + # Rename the super class according to the exact same rule we used when renaming the whole module + renamer = modular_mapper.renamers[super_file_name] + renamed_super_class = preserve_case_replace(super_class, renamer.patterns, renamer.cased_new_name) + + # Create the new class node + updated_node = replace_class_node(mapper, node, renamed_super_class, super_class) + + # Grab all immediate dependencies of the new node + new_node_dependencies = augmented_dependencies_for_class_node(updated_node, mapper, imported_objects) + + # At this point, if any class dependency is found, but belongs to another file, it means that we need to remove + # it from the dependencies, and add a new import of it instead + new_node_dependencies, new_imports = check_dependencies_and_create_import_node( + file_type, new_node_dependencies, mapper, model_name + ) + + # The node was modified -> look for all recursive dependencies of the new node + all_dependencies_to_add = find_all_dependencies( + dependency_mapping=mapper.class_dependency_mapping, + initial_dependencies=new_node_dependencies, + initial_checked_dependencies=set(file_to_update.keys()), + ) + + relative_dependency_order = mapper.compute_relative_order(all_dependencies_to_add) + nodes_to_add = { + dep: (relative_dependency_order[dep], mapper.global_nodes[dep]) for dep in all_dependencies_to_add + } + + # No transformers (modeling file) super class, just check functions and assignments dependencies + else: + updated_node = node + # The node was NOT modified -> no need to look recursively for other class dependencies. Indeed, even if they are not + # already defined (which would mean a weird order of the code in the modular...), they will be in the future + all_dependencies_to_add = augmented_dependencies_for_class_node(updated_node, modular_mapper, imported_objects) + + # At this point, if any class dependency is found, but belongs to another file, it means that we need to remove + # it from the dependencies, and add a new import of it instead + all_dependencies_to_add, new_imports = check_dependencies_and_create_import_node( + file_type, all_dependencies_to_add, modular_mapper, model_name + ) + + relative_dependency_order = modular_mapper.compute_relative_order(all_dependencies_to_add) + nodes_to_add = { + dep: (relative_dependency_order[dep], modular_mapper.global_nodes[dep]) + for dep in all_dependencies_to_add + if dep not in file_to_update + } + + # Add the class node itself to the nodes to add + class_idx = max(relative_dependency_order.values()) + 1 if len(relative_dependency_order) > 0 else 0 + nodes_to_add[class_name] = (class_idx, updated_node) + + return nodes_to_add, file_type, new_imports + + +def create_modules(modular_mapper: ModularFileMapper) -> dict[str, cst.Module]: + """Create all the new modules based on visiting the modular file. It replaces all classes as necessary.""" + files = defaultdict(dict) + current_file_indices = defaultdict(lambda: 0) + + # For each class defined in modular, potentially replace the node and add it with its dependencies + for class_name, node in modular_mapper.classes.items(): + nodes_to_add, file_type, new_imports = get_class_node_and_dependencies(modular_mapper, class_name, node, files) + + # Add the new potential new imports that we may need to the `modular_mapper` variable + modular_mapper.imported_objects_per_file[file_type].update(new_imports.keys()) + modular_mapper.imports.extend(list(new_imports.values())) + + # Sort the nodes according to their relative order + nodes_to_add = sorted(nodes_to_add.items(), key=lambda x: x[1][0]) + # Write all nodes to file + for dependency, (_, node) in nodes_to_add: + # This is used to keep certain variables at the beginning of the file + try: + # The -1000 is arbitrary -> just keep it bigger than the list + idx = -1000 + VARIABLES_AT_THE_BEGINNING.index(dependency) + except ValueError: + idx = current_file_indices[file_type] + current_file_indices[file_type] += 1 + files[file_type][dependency] = {"insert_idx": idx, "node": node} + + # Add the __all__ statement to files at the end + for file_type, node in modular_mapper.all_all_to_add.items(): + idx = current_file_indices[file_type] + files[file_type]["__all__"] = {"insert_idx": idx, "node": node} + + # Aggregate all the imports statements (we look for duplicates with the code_for_node, not the nodes themselves because + # they are wrapped in SimpleStatementLine or If which could have different newlines, blanks etc) + all_imports = modular_mapper.imports.copy() + all_imports_code = {modular_mapper.python_module.code_for_node(node).strip() for node in all_imports} + for file, mapper in modular_mapper.visited_modules.items(): + new_imports = [ + node for node in mapper.imports if mapper.python_module.code_for_node(node).strip() not in all_imports_code + ] + new_imports_code = {mapper.python_module.code_for_node(node).strip() for node in new_imports} + all_imports.extend(new_imports) + all_imports_code.update(new_imports_code) + + # Find the correct imports, and write the new modules + for file, body in files.items(): + new_body = [k[1]["node"] for k in sorted(body.items(), key=lambda x: x[1]["insert_idx"])] + needed_imports = get_needed_imports(body, all_imports) + full_module = needed_imports + new_body + new_module = cst.Module(body=full_module, header=modular_mapper.python_module.header) + files[file] = new_module + + return files + + +def run_ruff(code, check=False): + if check: + command = ["ruff", "check", "-", "--fix", "--exit-zero"] + else: + command = ["ruff", "format", "-", "--config", "pyproject.toml", "--silent"] + process = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) + stdout, _ = process.communicate(input=code.encode()) + return stdout.decode() + + +def convert_modular_file(modular_file): + pattern = re.search(r"modular_(.*)(?=\.py$)", modular_file) + output = {} + if pattern is not None: + model_name = pattern.groups()[0] + # Parse the Python file + with open(modular_file, "r", encoding="utf-8") as file: + code = file.read() + module = cst.parse_module(code) + wrapper = MetadataWrapper(module) + cst_transformers = ModularFileMapper(module, model_name) + wrapper.visit(cst_transformers) + for file, module in create_modules(cst_transformers).items(): + if module != {}: + # Get relative path starting from src/transformers/ + relative_path = re.search( + r"(src/transformers/.*|examples/.*)", os.path.abspath(modular_file).replace("\\", "/") + ).group(1) + + header = AUTO_GENERATED_MESSAGE.format( + relative_path=relative_path, short_name=os.path.basename(relative_path) + ) + ruffed_code = run_ruff(header + module.code, True) + formatted_code = run_ruff(ruffed_code, False) + output[file] = [formatted_code, ruffed_code] + return output + else: + print(f"modular pattern not found in {modular_file}, exiting") + return {} + + +def save_modeling_file(modular_file, converted_file): + for file_type in converted_file: + file_name_prefix = file_type.split("*")[0] + file_name_suffix = file_type.split("*")[-1] if "*" in file_type else "" + new_file_name = modular_file.replace("modular_", f"{file_name_prefix}_").replace( + ".py", f"{file_name_suffix}.py" + ) + non_comment_lines = len( + [line for line in converted_file[file_type][0].strip().split("\n") if not line.strip().startswith("#")] + ) + if len(converted_file[file_type][0].strip()) > 0 and non_comment_lines > 0: + with open(new_file_name, "w", encoding="utf-8") as f: + f.write(converted_file[file_type][0]) + else: + non_comment_lines = len( + [line for line in converted_file[file_type][0].strip().split("\n") if not line.strip().startswith("#")] + ) + if len(converted_file[file_type][1].strip()) > 0 and non_comment_lines > 0: + logger.warning("The modeling code contains errors, it's written without formatting") + with open(new_file_name, "w", encoding="utf-8") as f: + f.write(converted_file[file_type][1]) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + # Same arg as both positional and optional, just for convenience + parser.add_argument( + "files", + nargs="*", + help="A list of `modular_xxxx` files that should be converted to single model file", + ) + parser.add_argument( + "--files-to-parse", + "--files_to_parse", + "--files", + "-f", + default=["all"], + nargs="+", + help="A list of `modular_xxxx` files that should be converted to single model file", + ) + args = parser.parse_args() + # Both arg represent the same data, but as positional and optional + files_to_parse = args.files if len(args.files) > 0 else args.files_to_parse + + if files_to_parse == ["all"]: + files_to_parse = glob.glob("src/transformers/models/**/modular_*.py", recursive=True) + if files_to_parse == ["examples"]: + files_to_parse = glob.glob("examples/**/modular_*.py", recursive=True) + else: + for i, model_name in enumerate(files_to_parse): + if os.sep not in model_name: + full_path = os.path.join("src", "transformers", "models", model_name, f"modular_{model_name}.py") + # If it does not exist, try in the examples section + if not os.path.isfile(full_path): + full_path = os.path.join("examples", "modular-transformers", f"modular_{model_name}.py") + # We did not find it anywhere + if not os.path.isfile(full_path): + raise ValueError(f"Cannot find a modular file for {model_name}. Please provide the full path.") + files_to_parse[i] = full_path + + priority_list, _ = find_priority_list(files_to_parse) + priority_list = [item for sublist in priority_list for item in sublist] # flatten the list of lists + assert len(priority_list) == len(files_to_parse), "Some files will not be converted" + + for file_name in priority_list: + print(f"Converting {file_name} to a single model single file format") + module_path = file_name.replace("/", ".").replace(".py", "").replace("src.", "") + converted_files = convert_modular_file(file_name) + converter = save_modeling_file(file_name, converted_files) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/not_doctested.txt b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/not_doctested.txt new file mode 100644 index 0000000000000000000000000000000000000000..b35127b9167fa45423063d464927939c90f31aa6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/not_doctested.txt @@ -0,0 +1,959 @@ +docs/source/en/_config.py +docs/source/en/accelerate.md +docs/source/en/add_new_model.md +docs/source/en/add_new_pipeline.md +docs/source/en/community.md +docs/source/en/contributing.md +docs/source/en/custom_models.md +docs/source/en/debugging.md +docs/source/en/fast_tokenizers.md +docs/source/en/glossary.md +docs/source/en/hpo_train.md +docs/source/en/index.md +docs/source/en/installation.md +docs/source/en/internal/audio_utils.md +docs/source/en/internal/file_utils.md +docs/source/en/internal/image_processing_utils.md +docs/source/en/internal/modeling_utils.md +docs/source/en/internal/pipelines_utils.md +docs/source/en/internal/time_series_utils.md +docs/source/en/internal/tokenization_utils.md +docs/source/en/internal/trainer_utils.md +docs/source/en/llm_tutorial.md +docs/source/en/main_classes/callback.md +docs/source/en/main_classes/configuration.md +docs/source/en/main_classes/data_collator.md +docs/source/en/main_classes/deepspeed.md +docs/source/en/main_classes/feature_extractor.md +docs/source/en/main_classes/image_processor.md +docs/source/en/main_classes/keras_callbacks.md +docs/source/en/main_classes/logging.md +docs/source/en/main_classes/model.md +docs/source/en/main_classes/onnx.md +docs/source/en/main_classes/optimizer_schedules.md +docs/source/en/main_classes/output.md +docs/source/en/main_classes/pipelines.md +docs/source/en/main_classes/processors.md +docs/source/en/main_classes/quantization.md +docs/source/en/main_classes/tokenizer.md +docs/source/en/main_classes/trainer.md +docs/source/en/model_doc/albert.md +docs/source/en/model_doc/align.md +docs/source/en/model_doc/altclip.md +docs/source/en/model_doc/audio-spectrogram-transformer.md +docs/source/en/model_doc/auto.md +docs/source/en/model_doc/autoformer.md +docs/source/en/model_doc/bark.md +docs/source/en/model_doc/bart.md +docs/source/en/model_doc/barthez.md +docs/source/en/model_doc/bartpho.md +docs/source/en/model_doc/beit.md +docs/source/en/model_doc/bert-generation.md +docs/source/en/model_doc/bert-japanese.md +docs/source/en/model_doc/bert.md +docs/source/en/model_doc/bertweet.md +docs/source/en/model_doc/big_bird.md +docs/source/en/model_doc/bigbird_pegasus.md +docs/source/en/model_doc/biogpt.md +docs/source/en/model_doc/bit.md +docs/source/en/model_doc/blenderbot-small.md +docs/source/en/model_doc/blenderbot.md +docs/source/en/model_doc/blip-2.md +docs/source/en/model_doc/blip.md +docs/source/en/model_doc/bloom.md +docs/source/en/model_doc/bort.md +docs/source/en/model_doc/bridgetower.md +docs/source/en/model_doc/camembert.md +docs/source/en/model_doc/canine.md +docs/source/en/model_doc/chinese_clip.md +docs/source/en/model_doc/clap.md +docs/source/en/model_doc/clip.md +docs/source/en/model_doc/clipseg.md +docs/source/en/model_doc/codegen.md +docs/source/en/model_doc/conditional_detr.md +docs/source/en/model_doc/convbert.md +docs/source/en/model_doc/convnext.md +docs/source/en/model_doc/convnextv2.md +docs/source/en/model_doc/cpm.md +docs/source/en/model_doc/cpmant.md +docs/source/en/model_doc/ctrl.md +docs/source/en/model_doc/cvt.md +docs/source/en/model_doc/data2vec.md +docs/source/en/model_doc/deberta-v2.md +docs/source/en/model_doc/deberta.md +docs/source/en/model_doc/decision_transformer.md +docs/source/en/model_doc/deformable_detr.md +docs/source/en/model_doc/deit.md +docs/source/en/model_doc/deplot.md +docs/source/en/model_doc/deta.md +docs/source/en/model_doc/detr.md +docs/source/en/model_doc/dialogpt.md +docs/source/en/model_doc/dinat.md +docs/source/en/model_doc/dinov2.md +docs/source/en/model_doc/distilbert.md +docs/source/en/model_doc/dit.md +docs/source/en/model_doc/dpr.md +docs/source/en/model_doc/dpt.md +docs/source/en/model_doc/efficientformer.md +docs/source/en/model_doc/efficientnet.md +docs/source/en/model_doc/electra.md +docs/source/en/model_doc/encodec.md +docs/source/en/model_doc/ernie.md +docs/source/en/model_doc/ernie_m.md +docs/source/en/model_doc/esm.md +docs/source/en/model_doc/flan-t5.md +docs/source/en/model_doc/flan-ul2.md +docs/source/en/model_doc/flaubert.md +docs/source/en/model_doc/flava.md +docs/source/en/model_doc/fnet.md +docs/source/en/model_doc/focalnet.md +docs/source/en/model_doc/fsmt.md +docs/source/en/model_doc/funnel.md +docs/source/en/model_doc/git.md +docs/source/en/model_doc/glpn.md +docs/source/en/model_doc/gpt-sw3.md +docs/source/en/model_doc/gpt2.md +docs/source/en/model_doc/gpt_bigcode.md +docs/source/en/model_doc/gpt_neo.md +docs/source/en/model_doc/gpt_neox.md +docs/source/en/model_doc/gpt_neox_japanese.md +docs/source/en/model_doc/gptj.md +docs/source/en/model_doc/gptsan-japanese.md +docs/source/en/model_doc/graphormer.md +docs/source/en/model_doc/groupvit.md +docs/source/en/model_doc/herbert.md +docs/source/en/model_doc/hubert.md +docs/source/en/model_doc/ibert.md +docs/source/en/model_doc/idefics.md +docs/source/en/model_doc/imagegpt.md +docs/source/en/model_doc/informer.md +docs/source/en/model_doc/instructblip.md +docs/source/en/model_doc/jukebox.md +docs/source/en/model_doc/layoutlm.md +docs/source/en/model_doc/layoutlmv2.md +docs/source/en/model_doc/layoutlmv3.md +docs/source/en/model_doc/layoutxlm.md +docs/source/en/model_doc/led.md +docs/source/en/model_doc/levit.md +docs/source/en/model_doc/lilt.md +docs/source/en/model_doc/llama.md +docs/source/en/model_doc/llama2.md +docs/source/en/model_doc/llava.md +docs/source/en/model_doc/llava_next.md +docs/source/en/model_doc/longformer.md +docs/source/en/model_doc/longt5.md +docs/source/en/model_doc/luke.md +docs/source/en/model_doc/lxmert.md +docs/source/en/model_doc/m2m_100.md +docs/source/en/model_doc/madlad-400.md +docs/source/en/model_doc/marian.md +docs/source/en/model_doc/mask2former.md +docs/source/en/model_doc/maskformer.md +docs/source/en/model_doc/matcha.md +docs/source/en/model_doc/mbart.md +docs/source/en/model_doc/mctct.md +docs/source/en/model_doc/mega.md +docs/source/en/model_doc/megatron-bert.md +docs/source/en/model_doc/megatron_gpt2.md +docs/source/en/model_doc/mgp-str.md +docs/source/en/model_doc/mistral.md +docs/source/en/model_doc/mixtral.md +docs/source/en/model_doc/mluke.md +docs/source/en/model_doc/mms.md +docs/source/en/model_doc/mobilebert.md +docs/source/en/model_doc/mobilenet_v1.md +docs/source/en/model_doc/mobilenet_v2.md +docs/source/en/model_doc/mobilevit.md +docs/source/en/model_doc/mobilevitv2.md +docs/source/en/model_doc/mpnet.md +docs/source/en/model_doc/mpt.md +docs/source/en/model_doc/mra.md +docs/source/en/model_doc/mt5.md +docs/source/en/model_doc/musicgen.md +docs/source/en/model_doc/musicgen_melody.md +docs/source/en/model_doc/mvp.md +docs/source/en/model_doc/nat.md +docs/source/en/model_doc/nezha.md +docs/source/en/model_doc/nllb-moe.md +docs/source/en/model_doc/nllb.md +docs/source/en/model_doc/nystromformer.md +docs/source/en/model_doc/oneformer.md +docs/source/en/model_doc/open-llama.md +docs/source/en/model_doc/openai-gpt.md +docs/source/en/model_doc/opt.md +docs/source/en/model_doc/owlvit.md +docs/source/en/model_doc/pegasus.md +docs/source/en/model_doc/pegasus_x.md +docs/source/en/model_doc/perceiver.md +docs/source/en/model_doc/phobert.md +docs/source/en/model_doc/pix2struct.md +docs/source/en/model_doc/plbart.md +docs/source/en/model_doc/poolformer.md +docs/source/en/model_doc/pop2piano.md +docs/source/en/model_doc/prophetnet.md +docs/source/en/model_doc/pvt.md +docs/source/en/model_doc/qdqbert.md +docs/source/en/model_doc/qwen2.md +docs/source/en/model_doc/qwen2_moe.md +docs/source/en/model_doc/rag.md +docs/source/en/model_doc/realm.md +docs/source/en/model_doc/reformer.md +docs/source/en/model_doc/regnet.md +docs/source/en/model_doc/rembert.md +docs/source/en/model_doc/resnet.md +docs/source/en/model_doc/retribert.md +docs/source/en/model_doc/roberta-prelayernorm.md +docs/source/en/model_doc/roberta.md +docs/source/en/model_doc/roc_bert.md +docs/source/en/model_doc/roformer.md +docs/source/en/model_doc/rwkv.md +docs/source/en/model_doc/sam.md +docs/source/en/model_doc/sam_hq.md +docs/source/en/model_doc/segformer.md +docs/source/en/model_doc/sew-d.md +docs/source/en/model_doc/sew.md +docs/source/en/model_doc/speech-encoder-decoder.md +docs/source/en/model_doc/speech_to_text_2.md +docs/source/en/model_doc/speecht5.md +docs/source/en/model_doc/splinter.md +docs/source/en/model_doc/squeezebert.md +docs/source/en/model_doc/swiftformer.md +docs/source/en/model_doc/swin.md +docs/source/en/model_doc/swin2sr.md +docs/source/en/model_doc/swinv2.md +docs/source/en/model_doc/table-transformer.md +docs/source/en/model_doc/tapas.md +docs/source/en/model_doc/time_series_transformer.md +docs/source/en/model_doc/timesformer.md +docs/source/en/model_doc/trajectory_transformer.md +docs/source/en/model_doc/transfo-xl.md +docs/source/en/model_doc/trocr.md +docs/source/en/model_doc/tvlt.md +docs/source/en/model_doc/ul2.md +docs/source/en/model_doc/umt5.md +docs/source/en/model_doc/unispeech-sat.md +docs/source/en/model_doc/unispeech.md +docs/source/en/model_doc/upernet.md +docs/source/en/model_doc/van.md +docs/source/en/model_doc/videomae.md +docs/source/en/model_doc/vilt.md +docs/source/en/model_doc/vipllava.md +docs/source/en/model_doc/vision-encoder-decoder.md +docs/source/en/model_doc/vision-text-dual-encoder.md +docs/source/en/model_doc/visual_bert.md +docs/source/en/model_doc/vit.md +docs/source/en/model_doc/vit_hybrid.md +docs/source/en/model_doc/vit_mae.md +docs/source/en/model_doc/vit_msn.md +docs/source/en/model_doc/vivit.md +docs/source/en/model_doc/wav2vec2-conformer.md +docs/source/en/model_doc/wav2vec2.md +docs/source/en/model_doc/wav2vec2_phoneme.md +docs/source/en/model_doc/wavlm.md +docs/source/en/model_doc/whisper.md +docs/source/en/model_doc/xclip.md +docs/source/en/model_doc/xglm.md +docs/source/en/model_doc/xlm-prophetnet.md +docs/source/en/model_doc/xlm-roberta-xl.md +docs/source/en/model_doc/xlm-roberta.md +docs/source/en/model_doc/xlm-v.md +docs/source/en/model_doc/xlm.md +docs/source/en/model_doc/xlnet.md +docs/source/en/model_doc/xls_r.md +docs/source/en/model_doc/xlsr_wav2vec2.md +docs/source/en/model_doc/xmod.md +docs/source/en/model_doc/yolos.md +docs/source/en/model_doc/yoso.md +docs/source/en/model_memory_anatomy.md +docs/source/en/model_sharing.md +docs/source/en/notebooks.md +docs/source/en/pad_truncation.md +docs/source/en/peft.md +docs/source/en/perf_hardware.md +docs/source/en/perf_infer_cpu.md +docs/source/en/perf_infer_gpu_one.md +docs/source/en/perf_torch_compile.md +docs/source/en/perf_train_cpu.md +docs/source/en/perf_train_cpu_many.md +docs/source/en/perf_train_gpu_many.md +docs/source/en/perf_train_gpu_one.md +docs/source/en/perf_train_special.md +docs/source/en/perplexity.md +docs/source/en/philosophy.md +docs/source/en/pipeline_webserver.md +docs/source/en/pr_checks.md +docs/source/en/run_scripts.md +docs/source/en/serialization.md +docs/source/en/tasks/asr.md +docs/source/en/tasks/audio_classification.md +docs/source/en/tasks/document_question_answering.md +docs/source/en/tasks/idefics.md +docs/source/en/tasks/image_captioning.md +docs/source/en/tasks/image_classification.md +docs/source/en/tasks/language_modeling.md +docs/source/en/tasks/masked_language_modeling.md +docs/source/en/tasks/monocular_depth_estimation.md +docs/source/en/tasks/multiple_choice.md +docs/source/en/tasks/object_detection.md +docs/source/en/tasks/question_answering.md +docs/source/en/tasks/semantic_segmentation.md +docs/source/en/tasks/sequence_classification.md +docs/source/en/tasks/summarization.md +docs/source/en/tasks/text-to-speech.md +docs/source/en/tasks/token_classification.md +docs/source/en/tasks/translation.md +docs/source/en/tasks/video_classification.md +docs/source/en/tasks/visual_question_answering.md +docs/source/en/tasks/zero_shot_image_classification.md +docs/source/en/tasks/zero_shot_object_detection.md +docs/source/en/tflite.md +docs/source/en/tokenizer_summary.md +docs/source/en/torchscript.md +docs/source/en/training.md +docs/source/en/troubleshooting.md +src/transformers/activations.py +src/transformers/activations_tf.py +src/transformers/audio_utils.py +src/transformers/commands/add_new_model_like.py +src/transformers/commands/convert.py +src/transformers/commands/download.py +src/transformers/commands/env.py +src/transformers/commands/run.py +src/transformers/commands/serving.py +src/transformers/commands/train.py +src/transformers/commands/transformers_cli.py +src/transformers/configuration_utils.py +src/transformers/convert_graph_to_onnx.py +src/transformers/convert_pytorch_checkpoint_to_tf2.py +src/transformers/convert_slow_tokenizer.py +src/transformers/convert_slow_tokenizers_checkpoints_to_fast.py +src/transformers/convert_tf_hub_seq_to_seq_bert_to_pytorch.py +src/transformers/data/data_collator.py +src/transformers/data/datasets/glue.py +src/transformers/data/datasets/language_modeling.py +src/transformers/data/datasets/squad.py +src/transformers/data/metrics/squad_metrics.py +src/transformers/data/processors/glue.py +src/transformers/data/processors/squad.py +src/transformers/data/processors/utils.py +src/transformers/data/processors/xnli.py +src/transformers/debug_utils.py +src/transformers/dependency_versions_check.py +src/transformers/dependency_versions_table.py +src/transformers/dynamic_module_utils.py +src/transformers/feature_extraction_sequence_utils.py +src/transformers/feature_extraction_utils.py +src/transformers/file_utils.py +src/transformers/hf_argparser.py +src/transformers/hyperparameter_search.py +src/transformers/image_processing_utils.py +src/transformers/image_transforms.py +src/transformers/image_utils.py +src/transformers/integrations/bitsandbytes.py +src/transformers/integrations/deepspeed.py +src/transformers/integrations/integration_utils.py +src/transformers/integrations/peft.py +src/transformers/keras_callbacks.py +src/transformers/modelcard.py +src/transformers/modeling_flax_outputs.py +src/transformers/modeling_flax_pytorch_utils.py +src/transformers/modeling_flax_utils.py +src/transformers/modeling_outputs.py +src/transformers/modeling_tf_outputs.py +src/transformers/modeling_tf_pytorch_utils.py +src/transformers/modeling_tf_utils.py +src/transformers/modeling_utils.py +src/transformers/models/albert/convert_albert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/albert/modeling_flax_albert.py +src/transformers/models/align/configuration_align.py +src/transformers/models/align/convert_align_tf_to_hf.py +src/transformers/models/align/modeling_align.py +src/transformers/models/altclip/configuration_altclip.py +src/transformers/models/altclip/modeling_altclip.py +src/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py +src/transformers/models/audio_spectrogram_transformer/convert_audio_spectrogram_transformer_original_to_pytorch.py +src/transformers/models/auto/auto_factory.py +src/transformers/models/auto/configuration_auto.py +src/transformers/models/auto/modeling_auto.py +src/transformers/models/auto/modeling_flax_auto.py +src/transformers/models/auto/modeling_tf_auto.py +src/transformers/models/autoformer/configuration_autoformer.py +src/transformers/models/autoformer/modeling_autoformer.py +src/transformers/models/bark/convert_suno_to_hf.py +src/transformers/models/bart/convert_bart_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/bart/modeling_flax_bart.py +src/transformers/models/bart/modeling_tf_bart.py +src/transformers/models/beit/convert_beit_unilm_to_pytorch.py +src/transformers/models/beit/modeling_flax_beit.py +src/transformers/models/bert/convert_bert_original_tf2_checkpoint_to_pytorch.py +src/transformers/models/bert/convert_bert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py +src/transformers/models/bert/convert_bert_token_dropping_original_tf2_checkpoint_to_pytorch.py +src/transformers/models/bert/modeling_flax_bert.py +src/transformers/models/bert_generation/modeling_bert_generation.py +src/transformers/models/big_bird/convert_bigbird_original_tf_checkpoint_to_pytorch.py +src/transformers/models/big_bird/modeling_flax_big_bird.py +src/transformers/models/bigbird_pegasus/convert_bigbird_pegasus_tf_to_pytorch.py +src/transformers/models/biogpt/configuration_biogpt.py +src/transformers/models/biogpt/convert_biogpt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/biogpt/modeling_biogpt.py +src/transformers/models/bit/configuration_bit.py +src/transformers/models/bit/convert_bit_to_pytorch.py +src/transformers/models/bit/modeling_bit.py +src/transformers/models/blenderbot/convert_blenderbot_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/blenderbot/modeling_flax_blenderbot.py +src/transformers/models/blenderbot/modeling_tf_blenderbot.py +src/transformers/models/blenderbot_small/modeling_flax_blenderbot_small.py +src/transformers/models/blenderbot_small/modeling_tf_blenderbot_small.py +src/transformers/models/blip/configuration_blip.py +src/transformers/models/blip/convert_blip_original_pytorch_to_hf.py +src/transformers/models/blip/modeling_blip_text.py +src/transformers/models/blip/modeling_tf_blip_text.py +src/transformers/models/blip_2/configuration_blip_2.py +src/transformers/models/blip_2/convert_blip_2_original_to_pytorch.py +src/transformers/models/blip_2/modeling_blip_2.py +src/transformers/models/bloom/convert_bloom_original_checkpoint_to_pytorch.py +src/transformers/models/bloom/modeling_bloom.py +src/transformers/models/bloom/modeling_flax_bloom.py +src/transformers/models/bridgetower/configuration_bridgetower.py +src/transformers/models/bridgetower/modeling_bridgetower.py +src/transformers/models/bros/convert_bros_to_pytorch.py +src/transformers/models/byt5/convert_byt5_original_tf_checkpoint_to_pytorch.py +src/transformers/models/camembert/modeling_camembert.py +src/transformers/models/camembert/modeling_tf_camembert.py +src/transformers/models/canine/convert_canine_original_tf_checkpoint_to_pytorch.py +src/transformers/models/chinese_clip/configuration_chinese_clip.py +src/transformers/models/chinese_clip/convert_chinese_clip_original_pytorch_to_hf.py +src/transformers/models/chinese_clip/modeling_chinese_clip.py +src/transformers/models/clap/convert_clap_original_pytorch_to_hf.py +src/transformers/models/clip/convert_clip_original_pytorch_to_hf.py +src/transformers/models/clip/modeling_clip.py +src/transformers/models/clip/modeling_flax_clip.py +src/transformers/models/clip/modeling_tf_clip.py +src/transformers/models/clipseg/configuration_clipseg.py +src/transformers/models/clipseg/convert_clipseg_original_pytorch_to_hf.py +src/transformers/models/codegen/modeling_codegen.py +src/transformers/models/conditional_detr/convert_conditional_detr_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/convbert/convert_convbert_original_tf1_checkpoint_to_pytorch_and_tf2.py +src/transformers/models/convbert/modeling_convbert.py +src/transformers/models/convbert/modeling_tf_convbert.py +src/transformers/models/convnext/convert_convnext_to_pytorch.py +src/transformers/models/convnext/modeling_tf_convnext.py +src/transformers/models/convnextv2/configuration_convnextv2.py +src/transformers/models/convnextv2/convert_convnextv2_to_pytorch.py +src/transformers/models/convnextv2/modeling_convnextv2.py +src/transformers/models/cpmant/configuration_cpmant.py +src/transformers/models/cpmant/modeling_cpmant.py +src/transformers/models/cpmant/tokenization_cpmant.py +src/transformers/models/ctrl/modeling_tf_ctrl.py +src/transformers/models/cvt/convert_cvt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/cvt/modeling_tf_cvt.py +src/transformers/models/data2vec/convert_data2vec_audio_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/convert_data2vec_text_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/convert_data2vec_vision_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/data2vec/modeling_data2vec_text.py +src/transformers/models/data2vec/modeling_tf_data2vec_vision.py +src/transformers/models/deberta/modeling_tf_deberta.py +src/transformers/models/deberta_v2/modeling_tf_deberta_v2.py +src/transformers/models/decision_transformer/modeling_decision_transformer.py +src/transformers/models/deformable_detr/convert_deformable_detr_to_pytorch.py +src/transformers/models/deit/convert_deit_timm_to_pytorch.py +src/transformers/models/deprecated/bort/convert_bort_original_gluonnlp_checkpoint_to_pytorch.py +src/transformers/models/deprecated/mctct/configuration_mctct.py +src/transformers/models/deprecated/mctct/feature_extraction_mctct.py +src/transformers/models/deprecated/mctct/modeling_mctct.py +src/transformers/models/deprecated/mctct/processing_mctct.py +src/transformers/models/deprecated/mmbt/configuration_mmbt.py +src/transformers/models/deprecated/mmbt/modeling_mmbt.py +src/transformers/models/deprecated/open_llama/configuration_open_llama.py +src/transformers/models/deprecated/open_llama/modeling_open_llama.py +src/transformers/models/deprecated/retribert/configuration_retribert.py +src/transformers/models/deprecated/retribert/modeling_retribert.py +src/transformers/models/deprecated/retribert/tokenization_retribert.py +src/transformers/models/deprecated/retribert/tokenization_retribert_fast.py +src/transformers/models/deprecated/tapex/tokenization_tapex.py +src/transformers/models/deprecated/trajectory_transformer/configuration_trajectory_transformer.py +src/transformers/models/deprecated/trajectory_transformer/convert_trajectory_transformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/deprecated/trajectory_transformer/modeling_trajectory_transformer.py +src/transformers/models/deprecated/transfo_xl/convert_transfo_xl_original_tf_checkpoint_to_pytorch.py +src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl.py +src/transformers/models/deprecated/transfo_xl/modeling_tf_transfo_xl_utilities.py +src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl.py +src/transformers/models/deprecated/transfo_xl/modeling_transfo_xl_utilities.py +src/transformers/models/deprecated/van/configuration_van.py +src/transformers/models/deprecated/van/convert_van_to_pytorch.py +src/transformers/models/deprecated/van/modeling_van.py +src/transformers/models/detr/convert_detr_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/detr/convert_detr_to_pytorch.py +src/transformers/models/dialogpt/convert_dialogpt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/dinov2/configuration_dinov2.py +src/transformers/models/dinov2/convert_dinov2_to_hf.py +src/transformers/models/dinov2/modeling_dinov2.py +src/transformers/models/distilbert/modeling_distilbert.py +src/transformers/models/distilbert/modeling_flax_distilbert.py +src/transformers/models/distilbert/modeling_tf_distilbert.py +src/transformers/models/dit/convert_dit_unilm_to_pytorch.py +src/transformers/models/donut/configuration_donut_swin.py +src/transformers/models/donut/convert_donut_to_pytorch.py +src/transformers/models/donut/modeling_donut_swin.py +src/transformers/models/dpr/convert_dpr_original_checkpoint_to_pytorch.py +src/transformers/models/dpr/modeling_dpr.py +src/transformers/models/dpr/modeling_tf_dpr.py +src/transformers/models/dpt/configuration_dpt.py +src/transformers/models/dpt/convert_dpt_hybrid_to_pytorch.py +src/transformers/models/dpt/convert_dpt_to_pytorch.py +src/transformers/models/efficientnet/configuration_efficientnet.py +src/transformers/models/efficientnet/convert_efficientnet_to_pytorch.py +src/transformers/models/efficientnet/modeling_efficientnet.py +src/transformers/models/electra/convert_electra_original_tf_checkpoint_to_pytorch.py +src/transformers/models/electra/modeling_flax_electra.py +src/transformers/models/encodec/configuration_encodec.py +src/transformers/models/encodec/convert_encodec_checkpoint_to_pytorch.py +src/transformers/models/encoder_decoder/modeling_encoder_decoder.py +src/transformers/models/encoder_decoder/modeling_flax_encoder_decoder.py +src/transformers/models/encoder_decoder/modeling_tf_encoder_decoder.py +src/transformers/models/ernie/modeling_ernie.py +src/transformers/models/esm/configuration_esm.py +src/transformers/models/esm/convert_esm.py +src/transformers/models/esm/modeling_esm.py +src/transformers/models/esm/modeling_esmfold.py +src/transformers/models/esm/modeling_tf_esm.py +src/transformers/models/esm/openfold_utils/chunk_utils.py +src/transformers/models/esm/openfold_utils/data_transforms.py +src/transformers/models/esm/openfold_utils/feats.py +src/transformers/models/esm/openfold_utils/loss.py +src/transformers/models/esm/openfold_utils/protein.py +src/transformers/models/esm/openfold_utils/residue_constants.py +src/transformers/models/esm/openfold_utils/rigid_utils.py +src/transformers/models/esm/openfold_utils/tensor_utils.py +src/transformers/models/falcon/configuration_falcon.py +src/transformers/models/falcon/modeling_falcon.py +src/transformers/models/flaubert/configuration_flaubert.py +src/transformers/models/flaubert/modeling_flaubert.py +src/transformers/models/flaubert/modeling_tf_flaubert.py +src/transformers/models/flava/convert_dalle_to_flava_codebook.py +src/transformers/models/flava/convert_flava_original_pytorch_to_hf.py +src/transformers/models/flava/modeling_flava.py +src/transformers/models/fnet/convert_fnet_original_flax_checkpoint_to_pytorch.py +src/transformers/models/fnet/modeling_fnet.py +src/transformers/models/focalnet/configuration_focalnet.py +src/transformers/models/focalnet/convert_focalnet_to_hf_format.py +src/transformers/models/focalnet/modeling_focalnet.py +src/transformers/models/fsmt/convert_fsmt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/fsmt/modeling_fsmt.py +src/transformers/models/funnel/configuration_funnel.py +src/transformers/models/funnel/convert_funnel_original_tf_checkpoint_to_pytorch.py +src/transformers/models/funnel/modeling_funnel.py +src/transformers/models/funnel/modeling_tf_funnel.py +src/transformers/models/fuyu/convert_fuyu_model_weights_to_hf.py +src/transformers/models/gemma/configuration_gemma.py +src/transformers/models/gemma/convert_gemma_weights_to_hf.py +src/transformers/models/gemma/modeling_flax_gemma.py +src/transformers/models/gemma/modeling_gemma.py +src/transformers/models/git/configuration_git.py +src/transformers/models/git/convert_git_to_pytorch.py +src/transformers/models/glpn/configuration_glpn.py +src/transformers/models/glpn/convert_glpn_to_pytorch.py +src/transformers/models/gpt2/CONVERSION.md +src/transformers/models/gpt2/convert_gpt2_original_tf_checkpoint_to_pytorch.py +src/transformers/models/gpt2/modeling_flax_gpt2.py +src/transformers/models/gpt2/modeling_tf_gpt2.py +src/transformers/models/gpt_bigcode/configuration_gpt_bigcode.py +src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py +src/transformers/models/gpt_neo/convert_gpt_neo_mesh_tf_to_pytorch.py +src/transformers/models/gpt_neo/modeling_flax_gpt_neo.py +src/transformers/models/gpt_neo/modeling_gpt_neo.py +src/transformers/models/gpt_neox/modeling_gpt_neox.py +src/transformers/models/gpt_neox_japanese/modeling_gpt_neox_japanese.py +src/transformers/models/gpt_sw3/convert_megatron_to_pytorch.py +src/transformers/models/gptj/configuration_gptj.py +src/transformers/models/gptj/modeling_flax_gptj.py +src/transformers/models/gptj/modeling_tf_gptj.py +src/transformers/models/groupvit/configuration_groupvit.py +src/transformers/models/groupvit/convert_groupvit_nvlab_to_hf.py +src/transformers/models/hubert/configuration_hubert.py +src/transformers/models/hubert/convert_distilhubert_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/hubert/convert_hubert_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/hubert/convert_hubert_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/hubert/modeling_tf_hubert.py +src/transformers/models/ibert/configuration_ibert.py +src/transformers/models/ibert/modeling_ibert.py +src/transformers/models/ibert/quant_modules.py +src/transformers/models/idefics/configuration_idefics.py +src/transformers/models/idefics/image_processing_idefics.py +src/transformers/models/idefics/modeling_idefics.py +src/transformers/models/idefics/perceiver.py +src/transformers/models/idefics/processing_idefics.py +src/transformers/models/idefics/vision.py +src/transformers/models/imagegpt/convert_imagegpt_original_tf2_to_pytorch.py +src/transformers/models/informer/configuration_informer.py +src/transformers/models/informer/modeling_informer.py +src/transformers/models/instructblip/configuration_instructblip.py +src/transformers/models/instructblip/convert_instructblip_original_to_pytorch.py +src/transformers/models/instructblip/modeling_instructblip.py +src/transformers/models/instructblip/processing_instructblip.py +src/transformers/models/jamba/configuration_jamba.py +src/transformers/models/jamba/modeling_jamba.py +src/transformers/models/kosmos2/convert_kosmos2_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/led/configuration_led.py +src/transformers/models/led/modeling_led.py +src/transformers/models/led/modeling_tf_led.py +src/transformers/models/levit/convert_levit_timm_to_pytorch.py +src/transformers/models/levit/modeling_levit.py +src/transformers/models/lilt/configuration_lilt.py +src/transformers/models/llama/configuration_llama.py +src/transformers/models/llama/convert_llama_weights_to_hf.py +src/transformers/models/llama/modeling_llama.py +src/transformers/models/llava/configuration_llava.py +src/transformers/models/llava/modeling_llava.py +src/transformers/models/llava_next/configuration_llava_next.py +src/transformers/models/llava_next/modeling_llava_next.py +src/transformers/models/longformer/configuration_longformer.py +src/transformers/models/longformer/convert_longformer_original_pytorch_lightning_to_pytorch.py +src/transformers/models/longt5/configuration_longt5.py +src/transformers/models/longt5/convert_longt5x_checkpoint_to_flax.py +src/transformers/models/longt5/modeling_flax_longt5.py +src/transformers/models/luke/configuration_luke.py +src/transformers/models/luke/convert_luke_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/luke/modeling_luke.py +src/transformers/models/lxmert/configuration_lxmert.py +src/transformers/models/lxmert/convert_lxmert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/lxmert/modeling_lxmert.py +src/transformers/models/lxmert/modeling_tf_lxmert.py +src/transformers/models/m2m_100/convert_m2m100_original_checkpoint_to_pytorch.py +src/transformers/models/m2m_100/modeling_m2m_100.py +src/transformers/models/marian/configuration_marian.py +src/transformers/models/marian/convert_marian_tatoeba_to_pytorch.py +src/transformers/models/marian/convert_marian_to_pytorch.py +src/transformers/models/marian/modeling_flax_marian.py +src/transformers/models/marian/modeling_tf_marian.py +src/transformers/models/markuplm/configuration_markuplm.py +src/transformers/models/markuplm/feature_extraction_markuplm.py +src/transformers/models/mask2former/convert_mask2former_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/maskformer/configuration_maskformer_swin.py +src/transformers/models/maskformer/convert_maskformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/maskformer/convert_maskformer_resnet_to_pytorch.py +src/transformers/models/maskformer/convert_maskformer_swin_to_pytorch.py +src/transformers/models/maskformer/modeling_maskformer_swin.py +src/transformers/models/mbart/convert_mbart_original_checkpoint_to_pytorch.py +src/transformers/models/mbart/modeling_flax_mbart.py +src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py +src/transformers/models/megatron_bert/modeling_megatron_bert.py +src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py +src/transformers/models/megatron_gpt2/convert_megatron_gpt2_checkpoint.py +src/transformers/models/mgp_str/configuration_mgp_str.py +src/transformers/models/mgp_str/modeling_mgp_str.py +src/transformers/models/mistral/configuration_mistral.py +src/transformers/models/mistral/modeling_mistral.py +src/transformers/models/mixtral/configuration_mixtral.py +src/transformers/models/mixtral/modeling_mixtral.py +src/transformers/models/mluke/convert_mluke_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/mobilebert/convert_mobilebert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilenet_v1/configuration_mobilenet_v1.py +src/transformers/models/mobilenet_v1/convert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilenet_v2/configuration_mobilenet_v2.py +src/transformers/models/mobilenet_v2/convert_original_tf_checkpoint_to_pytorch.py +src/transformers/models/mobilevit/configuration_mobilevit.py +src/transformers/models/mobilevit/convert_mlcvnets_to_pytorch.py +src/transformers/models/mobilevitv2/convert_mlcvnets_to_pytorch.py +src/transformers/models/mpnet/configuration_mpnet.py +src/transformers/models/mpnet/modeling_mpnet.py +src/transformers/models/mpnet/modeling_tf_mpnet.py +src/transformers/models/mpt/configuration_mpt.py +src/transformers/models/mpt/modeling_mpt.py +src/transformers/models/mra/configuration_mra.py +src/transformers/models/mra/convert_mra_pytorch_to_pytorch.py +src/transformers/models/mra/modeling_mra.py +src/transformers/models/mt5/configuration_mt5.py +src/transformers/models/mt5/modeling_flax_mt5.py +src/transformers/models/mt5/modeling_mt5.py +src/transformers/models/mt5/modeling_tf_mt5.py +src/transformers/models/musicgen/convert_musicgen_transformers.py +src/transformers/models/musicgen_melody/convert_musicgen_melody_transformers.py +src/transformers/models/mvp/modeling_mvp.py +src/transformers/models/nllb_moe/configuration_nllb_moe.py +src/transformers/models/nllb_moe/convert_nllb_moe_sharded_original_checkpoint_to_pytorch.py +src/transformers/models/nllb_moe/modeling_nllb_moe.py +src/transformers/models/nougat/convert_nougat_to_hf.py +src/transformers/models/nystromformer/configuration_nystromformer.py +src/transformers/models/nystromformer/convert_nystromformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/nystromformer/modeling_nystromformer.py +src/transformers/models/oneformer/convert_to_hf_oneformer.py +src/transformers/models/openai/convert_openai_original_tf_checkpoint_to_pytorch.py +src/transformers/models/openai/modeling_openai.py +src/transformers/models/openai/modeling_tf_openai.py +src/transformers/models/opt/convert_opt_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/opt/modeling_flax_opt.py +src/transformers/models/owlvit/configuration_owlvit.py +src/transformers/models/owlvit/convert_owlvit_original_flax_to_hf.py +src/transformers/models/pegasus/convert_pegasus_tf_to_pytorch.py +src/transformers/models/pegasus/modeling_flax_pegasus.py +src/transformers/models/pegasus/modeling_tf_pegasus.py +src/transformers/models/pegasus_x/modeling_pegasus_x.py +src/transformers/models/perceiver/configuration_perceiver.py +src/transformers/models/perceiver/convert_perceiver_haiku_to_pytorch.py +src/transformers/models/persimmon/convert_persimmon_weights_to_hf.py +src/transformers/models/persimmon/modeling_persimmon.py +src/transformers/models/pix2struct/configuration_pix2struct.py +src/transformers/models/pix2struct/convert_pix2struct_original_pytorch_to_hf.py +src/transformers/models/pix2struct/image_processing_pix2struct.py +src/transformers/models/pix2struct/processing_pix2struct.py +src/transformers/models/plbart/convert_plbart_original_checkpoint_to_torch.py +src/transformers/models/poolformer/convert_poolformer_original_to_pytorch.py +src/transformers/models/pop2piano/convert_pop2piano_weights_to_hf.py +src/transformers/models/pop2piano/feature_extraction_pop2piano.py +src/transformers/models/pop2piano/processing_pop2piano.py +src/transformers/models/pop2piano/tokenization_pop2piano.py +src/transformers/models/prophetnet/configuration_prophetnet.py +src/transformers/models/prophetnet/convert_prophetnet_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/prophetnet/modeling_prophetnet.py +src/transformers/models/pvt/configuration_pvt.py +src/transformers/models/pvt/convert_pvt_to_pytorch.py +src/transformers/models/pvt/image_processing_pvt.py +src/transformers/models/pvt/modeling_pvt.py +src/transformers/models/qwen2/configuration_qwen2.py +src/transformers/models/qwen2/modeling_qwen2.py +src/transformers/models/qwen2/tokenization_qwen2.py +src/transformers/models/qwen2/tokenization_qwen2_fast.py +src/transformers/models/qwen2_moe/configuration_qwen2_moe.py +src/transformers/models/qwen2_moe/modeling_qwen2_moe.py +src/transformers/models/rag/configuration_rag.py +src/transformers/models/rag/modeling_rag.py +src/transformers/models/rag/modeling_tf_rag.py +src/transformers/models/rag/retrieval_rag.py +src/transformers/models/recurrent_gemma/modeling_recurrent_gemma.py +src/transformers/models/reformer/convert_reformer_trax_checkpoint_to_pytorch.py +src/transformers/models/regnet/configuration_regnet.py +src/transformers/models/regnet/convert_regnet_seer_10b_to_pytorch.py +src/transformers/models/regnet/convert_regnet_to_pytorch.py +src/transformers/models/regnet/modeling_flax_regnet.py +src/transformers/models/rembert/configuration_rembert.py +src/transformers/models/rembert/convert_rembert_tf_checkpoint_to_pytorch.py +src/transformers/models/rembert/modeling_rembert.py +src/transformers/models/rembert/modeling_tf_rembert.py +src/transformers/models/resnet/convert_resnet_to_pytorch.py +src/transformers/models/resnet/modeling_flax_resnet.py +src/transformers/models/roberta/convert_roberta_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/roberta/modeling_flax_roberta.py +src/transformers/models/roberta_prelayernorm/convert_roberta_prelayernorm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/roberta_prelayernorm/modeling_flax_roberta_prelayernorm.py +src/transformers/models/roc_bert/configuration_roc_bert.py +src/transformers/models/roformer/convert_roformer_original_tf_checkpoint_to_pytorch.py +src/transformers/models/roformer/modeling_flax_roformer.py +src/transformers/models/roformer/modeling_roformer.py +src/transformers/models/roformer/modeling_tf_roformer.py +src/transformers/models/rwkv/configuration_rwkv.py +src/transformers/models/rwkv/convert_rwkv_checkpoint_to_hf.py +src/transformers/models/rwkv/modeling_rwkv.py +src/transformers/models/sam/configuration_sam.py +src/transformers/models/sam/convert_sam_to_hf.py +src/transformers/models/sam/image_processing_sam.py +src/transformers/models/sam/modeling_sam.py +src/transformers/models/sam/modeling_tf_sam.py +src/transformers/models/sam/processing_sam.py +src/transformers/models/seamless_m4t/convert_fairseq2_to_hf.py +src/transformers/models/seamless_m4t_v2/convert_fairseq2_to_hf.py +src/transformers/models/segformer/configuration_segformer.py +src/transformers/models/segformer/convert_segformer_original_to_pytorch.py +src/transformers/models/sew/convert_sew_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/sew_d/convert_sew_d_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/speech_encoder_decoder/configuration_speech_encoder_decoder.py +src/transformers/models/speech_encoder_decoder/convert_mbart_wav2vec2_seq2seq_original_to_pytorch.py +src/transformers/models/speech_encoder_decoder/convert_speech_to_text_wav2vec2_seq2seq_original_to_pytorch.py +src/transformers/models/speech_encoder_decoder/modeling_flax_speech_encoder_decoder.py +src/transformers/models/speech_to_text/convert_s2t_fairseq_to_tfms.py +src/transformers/models/speech_to_text/modeling_tf_speech_to_text.py +src/transformers/models/speecht5/configuration_speecht5.py +src/transformers/models/speecht5/convert_hifigan.py +src/transformers/models/speecht5/convert_speecht5_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/speecht5/number_normalizer.py +src/transformers/models/splinter/configuration_splinter.py +src/transformers/models/splinter/modeling_splinter.py +src/transformers/models/squeezebert/modeling_squeezebert.py +src/transformers/models/stablelm/modeling_stablelm.py +src/transformers/models/starcoder2/modeling_starcoder2.py +src/transformers/models/swiftformer/configuration_swiftformer.py +src/transformers/models/swiftformer/convert_swiftformer_original_to_hf.py +src/transformers/models/swiftformer/modeling_swiftformer.py +src/transformers/models/swin/convert_swin_simmim_to_pytorch.py +src/transformers/models/swin/convert_swin_timm_to_pytorch.py +src/transformers/models/swin/modeling_tf_swin.py +src/transformers/models/swin2sr/configuration_swin2sr.py +src/transformers/models/swin2sr/convert_swin2sr_original_to_pytorch.py +src/transformers/models/swinv2/convert_swinv2_timm_to_pytorch.py +src/transformers/models/swinv2/modeling_swinv2.py +src/transformers/models/switch_transformers/configuration_switch_transformers.py +src/transformers/models/switch_transformers/convert_big_switch.py +src/transformers/models/switch_transformers/convert_switch_transformers_original_flax_checkpoint_to_pytorch.py +src/transformers/models/switch_transformers/modeling_switch_transformers.py +src/transformers/models/t5/configuration_t5.py +src/transformers/models/t5/convert_t5_original_tf_checkpoint_to_pytorch.py +src/transformers/models/t5/convert_t5x_checkpoint_to_flax.py +src/transformers/models/t5/convert_t5x_checkpoint_to_pytorch.py +src/transformers/models/t5/modeling_flax_t5.py +src/transformers/models/t5/modeling_t5.py +src/transformers/models/t5/modeling_tf_t5.py +src/transformers/models/table_transformer/configuration_table_transformer.py +src/transformers/models/table_transformer/convert_table_transformer_to_hf.py +src/transformers/models/table_transformer/convert_table_transformer_to_hf_no_timm.py +src/transformers/models/tapas/configuration_tapas.py +src/transformers/models/tapas/convert_tapas_original_tf_checkpoint_to_pytorch.py +src/transformers/models/tapas/modeling_tapas.py +src/transformers/models/tapas/modeling_tf_tapas.py +src/transformers/models/timesformer/convert_timesformer_to_pytorch.py +src/transformers/models/timm_backbone/configuration_timm_backbone.py +src/transformers/models/timm_backbone/modeling_timm_backbone.py +src/transformers/models/trocr/convert_trocr_unilm_to_pytorch.py +src/transformers/models/umt5/configuration_umt5.py +src/transformers/models/umt5/convert_umt5_checkpoint_to_pytorch.py +src/transformers/models/umt5/modeling_umt5.py +src/transformers/models/unispeech/convert_unispeech_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/unispeech_sat/configuration_unispeech_sat.py +src/transformers/models/unispeech_sat/convert_unispeech_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/unispeech_sat/convert_unispeech_sat_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/upernet/configuration_upernet.py +src/transformers/models/upernet/convert_convnext_upernet_to_pytorch.py +src/transformers/models/upernet/convert_swin_upernet_to_pytorch.py +src/transformers/models/videomae/configuration_videomae.py +src/transformers/models/videomae/convert_videomae_to_pytorch.py +src/transformers/models/vilt/configuration_vilt.py +src/transformers/models/vilt/convert_vilt_original_to_pytorch.py +src/transformers/models/vipllava/configuration_vipllava.py +src/transformers/models/vipllava/modeling_vipllava.py +src/transformers/models/vision_encoder_decoder/modeling_flax_vision_encoder_decoder.py +src/transformers/models/vision_encoder_decoder/modeling_tf_vision_encoder_decoder.py +src/transformers/models/vision_text_dual_encoder/modeling_flax_vision_text_dual_encoder.py +src/transformers/models/vision_text_dual_encoder/modeling_vision_text_dual_encoder.py +src/transformers/models/visual_bert/convert_visual_bert_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/visual_bert/modeling_visual_bert.py +src/transformers/models/vit/convert_dino_to_pytorch.py +src/transformers/models/vit/convert_vit_timm_to_pytorch.py +src/transformers/models/vit/modeling_flax_vit.py +src/transformers/models/vit_mae/convert_vit_mae_to_pytorch.py +src/transformers/models/vit_mae/modeling_tf_vit_mae.py +src/transformers/models/vit_msn/configuration_vit_msn.py +src/transformers/models/vit_msn/convert_msn_to_pytorch.py +src/transformers/models/vivit/configuration_vivit.py +src/transformers/models/vivit/convert_vivit_flax_to_pytorch.py +src/transformers/models/vivit/image_processing_vivit.py +src/transformers/models/vivit/modeling_vivit.py +src/transformers/models/wav2vec2/convert_wav2vec2_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wav2vec2/convert_wav2vec2_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/wav2vec2/modeling_flax_wav2vec2.py +src/transformers/models/wav2vec2/modeling_tf_wav2vec2.py +src/transformers/models/wav2vec2_bert/convert_wav2vec2_seamless_checkpoint.py +src/transformers/models/wav2vec2_conformer/convert_wav2vec2_conformer_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wavlm/convert_wavlm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/wavlm/convert_wavlm_original_s3prl_checkpoint_to_pytorch.py +src/transformers/models/whisper/convert_openai_to_hf.py +src/transformers/models/whisper/english_normalizer.py +src/transformers/models/whisper/modeling_flax_whisper.py +src/transformers/models/x_clip/configuration_x_clip.py +src/transformers/models/x_clip/convert_x_clip_original_pytorch_to_hf.py +src/transformers/models/xglm/configuration_xglm.py +src/transformers/models/xglm/convert_xglm_original_ckpt_to_trfms.py +src/transformers/models/xglm/modeling_flax_xglm.py +src/transformers/models/xglm/modeling_tf_xglm.py +src/transformers/models/xglm/modeling_xglm.py +src/transformers/models/xlm/convert_xlm_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/xlm/modeling_tf_xlm.py +src/transformers/models/xlm/modeling_xlm.py +src/transformers/models/xlm_roberta/modeling_flax_xlm_roberta.py +src/transformers/models/xlm_roberta/modeling_tf_xlm_roberta.py +src/transformers/models/xlm_roberta/modeling_xlm_roberta.py +src/transformers/models/xlm_roberta_xl/convert_xlm_roberta_xl_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/xlm_roberta_xl/modeling_xlm_roberta_xl.py +src/transformers/models/xlnet/convert_xlnet_original_tf_checkpoint_to_pytorch.py +src/transformers/models/xlnet/modeling_tf_xlnet.py +src/transformers/models/xlnet/modeling_xlnet.py +src/transformers/models/xmod/convert_xmod_original_pytorch_checkpoint_to_pytorch.py +src/transformers/models/yolos/convert_yolos_to_pytorch.py +src/transformers/models/yoso/convert_yoso_pytorch_to_pytorch.py +src/transformers/models/yoso/modeling_yoso.py +src/transformers/models/zamba/configuration_zamba.py +src/transformers/models/zamba/modeling_zamba.py +src/transformers/onnx/__main__.py +src/transformers/onnx/config.py +src/transformers/onnx/convert.py +src/transformers/onnx/features.py +src/transformers/onnx/utils.py +src/transformers/optimization.py +src/transformers/optimization_tf.py +src/transformers/pipelines/audio_classification.py +src/transformers/pipelines/audio_utils.py +src/transformers/pipelines/automatic_speech_recognition.py +src/transformers/pipelines/base.py +src/transformers/pipelines/depth_estimation.py +src/transformers/pipelines/document_question_answering.py +src/transformers/pipelines/feature_extraction.py +src/transformers/pipelines/fill_mask.py +src/transformers/pipelines/image_classification.py +src/transformers/pipelines/image_segmentation.py +src/transformers/pipelines/image_to_text.py +src/transformers/pipelines/mask_generation.py +src/transformers/pipelines/object_detection.py +src/transformers/pipelines/pt_utils.py +src/transformers/pipelines/question_answering.py +src/transformers/pipelines/table_question_answering.py +src/transformers/pipelines/text_classification.py +src/transformers/pipelines/token_classification.py +src/transformers/pipelines/video_classification.py +src/transformers/pipelines/visual_question_answering.py +src/transformers/pipelines/zero_shot_audio_classification.py +src/transformers/pipelines/zero_shot_classification.py +src/transformers/pipelines/zero_shot_image_classification.py +src/transformers/pipelines/zero_shot_object_detection.py +src/transformers/processing_utils.py +src/transformers/pytorch_utils.py +src/transformers/quantizers/auto.py +src/transformers/quantizers/base.py +src/transformers/quantizers/quantizer_awq.py +src/transformers/quantizers/quantizer_bnb_4bit.py +src/transformers/quantizers/quantizer_bnb_8bit.py +src/transformers/quantizers/quantizer_gptq.py +src/transformers/quantizers/quantizers_utils.py +src/transformers/sagemaker/trainer_sm.py +src/transformers/sagemaker/training_args_sm.py +src/transformers/testing_utils.py +src/transformers/tf_utils.py +src/transformers/time_series_utils.py +src/transformers/tokenization_utils.py +src/transformers/tokenization_utils_base.py +src/transformers/tokenization_utils_fast.py +src/transformers/trainer.py +src/transformers/trainer_callback.py +src/transformers/trainer_pt_utils.py +src/transformers/trainer_seq2seq.py +src/transformers/trainer_utils.py +src/transformers/training_args.py +src/transformers/training_args_seq2seq.py +src/transformers/training_args_tf.py +src/transformers/utils/backbone_utils.py +src/transformers/utils/bitsandbytes.py +src/transformers/utils/constants.py +src/transformers/utils/doc.py +src/transformers/utils/dummy_detectron2_objects.py +src/transformers/utils/dummy_essentia_and_librosa_and_pretty_midi_and_scipy_and_torch_objects.py +src/transformers/utils/dummy_flax_objects.py +src/transformers/utils/dummy_music_objects.py +src/transformers/utils/dummy_pt_objects.py +src/transformers/utils/dummy_sentencepiece_and_tokenizers_objects.py +src/transformers/utils/dummy_sentencepiece_objects.py +src/transformers/utils/dummy_speech_objects.py +src/transformers/utils/dummy_tensorflow_text_objects.py +src/transformers/utils/dummy_tf_objects.py +src/transformers/utils/dummy_tokenizers_objects.py +src/transformers/utils/dummy_vision_objects.py +src/transformers/utils/fx.py +src/transformers/utils/generic.py +src/transformers/utils/hp_naming.py +src/transformers/utils/hub.py +src/transformers/utils/import_utils.py +src/transformers/utils/logging.py +src/transformers/utils/model_parallel_utils.py +src/transformers/utils/notebook.py +src/transformers/utils/peft_utils.py +src/transformers/utils/quantization_config.py +src/transformers/utils/sentencepiece_model_pb2.py +src/transformers/utils/sentencepiece_model_pb2_new.py +src/transformers/utils/versions.py diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/notification_service.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/notification_service.py new file mode 100644 index 0000000000000000000000000000000000000000..33abd1790c71b5e8c3c717ba4a4944a4b1a31ae0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/notification_service.py @@ -0,0 +1,1579 @@ +# 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. + +import ast +import collections +import functools +import json +import operator +import os +import re +import sys +import time +from typing import Any, Optional, Union + +import requests +from compare_test_runs import compare_job_sets +from get_ci_error_statistics import get_jobs +from get_previous_daily_ci import get_last_daily_ci_reports, get_last_daily_ci_run, get_last_daily_ci_workflow_run_id +from huggingface_hub import HfApi +from slack_sdk import WebClient + + +# A map associating the job names (specified by `inputs.job` in a workflow file) with the keys of +# `additional_files`. +job_to_test_map = { + "run_models_gpu": "Models", + "run_trainer_and_fsdp_gpu": "Trainer & FSDP", + "run_pipelines_torch_gpu": "PyTorch pipelines", + "run_pipelines_tf_gpu": "TensorFlow pipelines", + "run_examples_gpu": "Examples directory", + "run_torch_cuda_extensions_gpu": "DeepSpeed", + "run_quantization_torch_gpu": "Quantization", +} + +# The values are used as the file names where to save the corresponding CI job results. +test_to_result_name = { + "Models": "model", + "Trainer & FSDP": "trainer_and_fsdp", + "PyTorch pipelines": "torch_pipeline", + "TensorFlow pipelines": "tf_pipeline", + "Examples directory": "example", + "DeepSpeed": "deepspeed", + "Quantization": "quantization", +} + +NON_MODEL_TEST_MODULES = [ + "deepspeed", + "extended", + "fixtures", + "generation", + "onnx", + "optimization", + "pipelines", + "sagemaker", + "trainer", + "utils", + "fsdp", + "quantization", +] + + +def handle_test_results(test_results): + expressions = test_results.split(" ") + + failed = 0 + success = 0 + errors = 0 + skipped = 0 + + # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" + # When it is too long, those signs are not present. + # It could be `'71.60s', '(0:01:11)', '====\n'` or `'in', '35.01s', '================\n'`. + # Let always select the one with `s`. + time_spent = expressions[-1] + if "=" in time_spent: + time_spent = expressions[-2] + if "(" in time_spent: + time_spent = expressions[-3] + + for i, expression in enumerate(expressions): + if "failed" in expression: + failed += int(expressions[i - 1]) + if "errors" in expression: + errors += int(expressions[i - 1]) + if "passed" in expression: + success += int(expressions[i - 1]) + if "skipped" in expression: + skipped += int(expressions[i - 1]) + + return failed, errors, success, skipped, time_spent + + +def handle_stacktraces(test_results): + # These files should follow the following architecture: + # === FAILURES === + # :: Error ... + # :: Error ... + # + + total_stacktraces = test_results.split("\n")[1:-1] + stacktraces = [] + for stacktrace in total_stacktraces: + try: + line = stacktrace[: stacktrace.index(" ")].split(":")[-2] + error_message = stacktrace[stacktrace.index(" ") :] + + stacktraces.append(f"(line {line}) {error_message}") + except Exception: + stacktraces.append("Cannot retrieve error message.") + + return stacktraces + + +def dicts_to_sum(objects: Union[dict[str, dict], list[dict]]): + if isinstance(objects, dict): + lists = objects.values() + else: + lists = objects + + # Convert each dictionary to counter + counters = map(collections.Counter, lists) + # Sum all the counters + return functools.reduce(operator.add, counters) + + +class Message: + def __init__( + self, + title: str, + ci_title: str, + model_results: dict, + additional_results: dict, + selected_warnings: Optional[list] = None, + prev_ci_artifacts=None, + other_ci_artifacts=None, + ): + self.title = title + self.ci_title = ci_title + + # Failures and success of the modeling tests + self.n_model_success = sum(r["success"] for r in model_results.values()) + self.n_model_single_gpu_failures = sum(dicts_to_sum(r["failed"])["single"] for r in model_results.values()) + self.n_model_multi_gpu_failures = sum(dicts_to_sum(r["failed"])["multi"] for r in model_results.values()) + + # Some suites do not have a distinction between single and multi GPU. + self.n_model_unknown_failures = sum(dicts_to_sum(r["failed"])["unclassified"] for r in model_results.values()) + self.n_model_failures = ( + self.n_model_single_gpu_failures + self.n_model_multi_gpu_failures + self.n_model_unknown_failures + ) + + # Failures and success of the additional tests + self.n_additional_success = sum(r["success"] for r in additional_results.values()) + + if len(additional_results) > 0: + # `dicts_to_sum` uses `dicts_to_sum` which requires a non empty dictionary. Let's just add an empty entry. + all_additional_failures = dicts_to_sum([r["failed"] for r in additional_results.values()]) + self.n_additional_single_gpu_failures = all_additional_failures["single"] + self.n_additional_multi_gpu_failures = all_additional_failures["multi"] + self.n_additional_unknown_gpu_failures = all_additional_failures["unclassified"] + else: + self.n_additional_single_gpu_failures = 0 + self.n_additional_multi_gpu_failures = 0 + self.n_additional_unknown_gpu_failures = 0 + + self.n_additional_failures = ( + self.n_additional_single_gpu_failures + + self.n_additional_multi_gpu_failures + + self.n_additional_unknown_gpu_failures + ) + + # Results + self.n_failures = self.n_model_failures + self.n_additional_failures + self.n_success = self.n_model_success + self.n_additional_success + self.n_tests = self.n_failures + self.n_success + + self.model_results = model_results + self.additional_results = additional_results + + self.thread_ts = None + + if selected_warnings is None: + selected_warnings = [] + self.selected_warnings = selected_warnings + + self.prev_ci_artifacts = prev_ci_artifacts + self.other_ci_artifacts = other_ci_artifacts + + @property + def time(self) -> str: + all_results = [*self.model_results.values(), *self.additional_results.values()] + + time_spent = [] + for r in all_results: + if len(r["time_spent"]): + time_spent.extend(r["time_spent"]) + total_secs = sum(time_spent) + + hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 + return f"{int(hours)}h{int(minutes)}m{int(seconds)}s" + + @property + def header(self) -> dict: + return {"type": "header", "text": {"type": "plain_text", "text": self.title}} + + @property + def ci_title_section(self) -> dict: + return {"type": "section", "text": {"type": "mrkdwn", "text": self.ci_title}} + + @property + def no_failures(self) -> dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def failures(self) -> dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": ( + f"There were {self.n_failures} failures, out of {self.n_tests} tests.\n" + f"The suite ran in {self.time}." + ), + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def warnings(self) -> dict: + # If something goes wrong, let's avoid the CI report failing to be sent. + button_text = "Check warnings (Link not found)" + # Use the workflow run link + job_link = f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}" + + for job in github_actions_jobs: + if "Extract warnings in CI artifacts" in job["name"] and job["conclusion"] == "success": + button_text = "Check warnings" + # Use the actual job link + job_link = job["html_url"] + break + + huggingface_hub_warnings = [x for x in self.selected_warnings if "huggingface_hub" in x] + text = f"There are {len(self.selected_warnings)} warnings being selected." + text += f"\n{len(huggingface_hub_warnings)} of them are from `huggingface_hub`." + + return { + "type": "section", + "text": { + "type": "plain_text", + "text": text, + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": button_text, "emoji": True}, + "url": job_link, + }, + } + + @staticmethod + def get_device_report(report, rjust=6): + if "single" in report and "multi" in report: + return f"{str(report['single']).rjust(rjust)} | {str(report['multi']).rjust(rjust)} | " + elif "single" in report: + return f"{str(report['single']).rjust(rjust)} | {'0'.rjust(rjust)} | " + elif "multi" in report: + return f"{'0'.rjust(rjust)} | {str(report['multi']).rjust(rjust)} | " + + @property + def category_failures(self) -> dict: + if job_name != "run_models_gpu": + category_failures_report = "" + return {"type": "section", "text": {"type": "mrkdwn", "text": category_failures_report}} + + model_failures = [v["failed"] for v in self.model_results.values()] + + category_failures = {} + + for model_failure in model_failures: + for key, value in model_failure.items(): + if key not in category_failures: + category_failures[key] = dict(value) + else: + category_failures[key]["unclassified"] += value["unclassified"] + category_failures[key]["single"] += value["single"] + category_failures[key]["multi"] += value["multi"] + + individual_reports = [] + for key, value in category_failures.items(): + device_report = self.get_device_report(value) + + if sum(value.values()): + if device_report: + individual_reports.append(f"{device_report}{key}") + else: + individual_reports.append(key) + + header = "Single | Multi | Category\n" + category_failures_report = prepare_reports( + title="The following categories had failures", header=header, reports=individual_reports + ) + + return {"type": "section", "text": {"type": "mrkdwn", "text": category_failures_report}} + + def compute_diff_for_failure_reports(self, curr_failure_report, prev_failure_report): # noqa + # Remove the leading and training parts that don't contain failure count information. + model_failures = curr_failure_report.split("\n")[3:-2] + prev_model_failures = prev_failure_report.split("\n")[3:-2] + entries_changed = set(model_failures).difference(prev_model_failures) + + prev_map = {} + for f in prev_model_failures: + items = [x.strip() for x in f.split("| ")] + prev_map[items[-1]] = [int(x) for x in items[:-1]] + + curr_map = {} + for f in entries_changed: + items = [x.strip() for x in f.split("| ")] + curr_map[items[-1]] = [int(x) for x in items[:-1]] + + diff_map = {} + for k, v in curr_map.items(): + if k not in prev_map: + diff_map[k] = v + else: + diff = [x - y for x, y in zip(v, prev_map[k])] + if max(diff) > 0: + diff_map[k] = diff + + entries_changed = [] + for model_name, diff_values in diff_map.items(): + diff = [str(x) for x in diff_values] + diff = [f"+{x}" if (x != "0" and not x.startswith("-")) else x for x in diff] + diff = [x.rjust(9) for x in diff] + device_report = " | ".join(diff) + " | " + report = f"{device_report}{model_name}" + entries_changed.append(report) + entries_changed = sorted(entries_changed, key=lambda s: s.split("| ")[-1]) + + return entries_changed + + @property + def model_failures(self) -> list[dict]: + # Obtain per-model failures + def per_model_sum(model_category_dict): + return dicts_to_sum(model_category_dict["failed"].values()) + + failures = {} + non_model_failures = { + k: per_model_sum(v) for k, v in self.model_results.items() if sum(per_model_sum(v).values()) + } + + for k, v in self.model_results.items(): + # The keys in `model_results` may contain things like `models_vit` or `quantization_autoawq` + # Remove the prefix to make the report cleaner. + k = k.replace("models_", "").replace("quantization_", "") + if k in NON_MODEL_TEST_MODULES: + continue + + if sum(per_model_sum(v).values()): + dict_failed = dict(v["failed"]) + + # Model job has a special form for reporting + if job_name == "run_models_gpu": + pytorch_specific_failures = dict_failed.pop("PyTorch") + tensorflow_specific_failures = dict_failed.pop("TensorFlow") + other_failures = dicts_to_sum(dict_failed.values()) + + failures[k] = { + "PyTorch": pytorch_specific_failures, + "TensorFlow": tensorflow_specific_failures, + "other": other_failures, + } + + else: + test_name = job_to_test_map[job_name] + specific_failures = dict_failed.pop(test_name) + failures[k] = { + test_name: specific_failures, + } + + model_reports = [] + other_module_reports = [] + + for key, value in non_model_failures.items(): + key = key.replace("models_", "").replace("quantization_", "") + + if key in NON_MODEL_TEST_MODULES: + device_report = self.get_device_report(value) + + if sum(value.values()): + if device_report: + report = f"{device_report}{key}" + else: + report = key + + other_module_reports.append(report) + + for key, value in failures.items(): + # Model job has a special form for reporting + if job_name == "run_models_gpu": + device_report_values = [ + value["PyTorch"]["single"], + value["PyTorch"]["multi"], + value["TensorFlow"]["single"], + value["TensorFlow"]["multi"], + sum(value["other"].values()), + ] + + else: + test_name = job_to_test_map[job_name] + device_report_values = [ + value[test_name]["single"], + value[test_name]["multi"], + ] + + if sum(device_report_values): + # This is related to `model_header` below + rjust_width = 9 if job_name == "run_models_gpu" else 6 + device_report = " | ".join([str(x).rjust(rjust_width) for x in device_report_values]) + " | " + report = f"{device_report}{key}" + + model_reports.append(report) + + # (Possibly truncated) reports for the current workflow run - to be sent to Slack channels + if job_name == "run_models_gpu": + model_header = "Single PT | Multi PT | Single TF | Multi TF | Other | Category\n" + else: + model_header = "Single | Multi | Category\n" + + # Used when calling `prepare_reports` below to prepare the `title` argument + label = test_to_result_name[job_to_test_map[job_name]] + + sorted_model_reports = sorted(model_reports, key=lambda s: s.split("| ")[-1]) + model_failures_report = prepare_reports( + title=f"These following {label} modules had failures", header=model_header, reports=sorted_model_reports + ) + + module_header = "Single | Multi | Category\n" + sorted_module_reports = sorted(other_module_reports, key=lambda s: s.split("| ")[-1]) + module_failures_report = prepare_reports( + title=f"The following {label} modules had failures", header=module_header, reports=sorted_module_reports + ) + + # To be sent to Slack channels + model_failure_sections = [{"type": "section", "text": {"type": "mrkdwn", "text": model_failures_report}}] + model_failure_sections.append({"type": "section", "text": {"type": "mrkdwn", "text": module_failures_report}}) + + # Save the complete (i.e. no truncation) failure tables (of the current workflow run) + # (to be uploaded as artifacts) + + model_failures_report = prepare_reports( + title=f"These following {label} modules had failures", + header=model_header, + reports=sorted_model_reports, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/model_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(model_failures_report) + + module_failures_report = prepare_reports( + title=f"The following {label} modules had failures", + header=module_header, + reports=sorted_module_reports, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/module_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(module_failures_report) + + if self.prev_ci_artifacts is not None: + # if the last run produces artifact named `ci_results_{job_name}` + if ( + f"ci_results_{job_name}" in self.prev_ci_artifacts + and "model_failures_report.txt" in self.prev_ci_artifacts[f"ci_results_{job_name}"] + ): + # Compute the difference of the previous/current (model failure) table + prev_model_failures = self.prev_ci_artifacts[f"ci_results_{job_name}"]["model_failures_report.txt"] + entries_changed = self.compute_diff_for_failure_reports(model_failures_report, prev_model_failures) + if len(entries_changed) > 0: + # Save the complete difference + diff_report = prepare_reports( + title="Changed model modules failures", + header=model_header, + reports=entries_changed, + to_truncate=False, + ) + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/changed_model_failures_report.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(diff_report) + + # To be sent to Slack channels + diff_report = prepare_reports( + title="*Changed model modules failures*", + header=model_header, + reports=entries_changed, + ) + model_failure_sections.append( + {"type": "section", "text": {"type": "mrkdwn", "text": diff_report}}, + ) + + return model_failure_sections + + @property + def additional_failures(self) -> dict: + failures = {k: v["failed"] for k, v in self.additional_results.items()} + errors = {k: v["error"] for k, v in self.additional_results.items()} + + individual_reports = [] + for key, value in failures.items(): + device_report = self.get_device_report(value) + + if sum(value.values()) or errors[key]: + report = f"{key}" + if errors[key]: + report = f"[Errored out] {report}" + if device_report: + report = f"{device_report}{report}" + + individual_reports.append(report) + + header = "Single | Multi | Category\n" + failures_report = prepare_reports( + title="The following non-modeling tests had failures", header=header, reports=individual_reports + ) + + return {"type": "section", "text": {"type": "mrkdwn", "text": failures_report}} + + @property + def payload(self) -> str: + blocks = [self.header] + + if self.ci_title: + blocks.append(self.ci_title_section) + + if self.n_model_failures > 0 or self.n_additional_failures > 0: + blocks.append(self.failures) + + if self.n_model_failures > 0: + block = self.category_failures + if block["text"]["text"]: + blocks.append(block) + + for block in self.model_failures: + if block["text"]["text"]: + blocks.append(block) + + if self.n_additional_failures > 0: + blocks.append(self.additional_failures) + + if self.n_model_failures == 0 and self.n_additional_failures == 0: + blocks.append(self.no_failures) + + if len(self.selected_warnings) > 0: + blocks.append(self.warnings) + + new_failure_blocks = [] + for idx, (prev_workflow_run_id, prev_ci_artifacts) in enumerate( + [self.prev_ci_artifacts] + self.other_ci_artifacts + ): + if idx == 0: + # This is the truncated version to show on slack. For now. + new_failure_blocks = self.get_new_model_failure_blocks( + prev_ci_artifacts=prev_ci_artifacts, with_header=False + ) + + # To save the list of new model failures and uploaed to hub repositories + extra_blocks = self.get_new_model_failure_blocks(prev_ci_artifacts=prev_ci_artifacts, to_truncate=False) + if extra_blocks: + filename = "new_failures" + if idx > 0: + filename = f"{filename}_against_{prev_workflow_run_id}" + + failure_text = extra_blocks[-1]["text"]["text"] + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/{filename}.txt") + with open(file_path, "w", encoding="UTF-8") as fp: + fp.write(failure_text) + + # upload results to Hub dataset + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/{filename}.txt") + _ = api.upload_file( + path_or_fileobj=file_path, + path_in_repo=f"{report_repo_folder}/ci_results_{job_name}/{filename}.txt", + repo_id=report_repo_id, + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + + # extra processing to save to json format + new_failed_tests = {} + nb_new_failed_tests = 0 + for line in failure_text.split(): + if "https://github.com/huggingface/transformers/actions/runs" in line: + pattern = r"<(https://github.com/huggingface/transformers/actions/runs/.+?/job/.+?)\|(.+?)>" + items = re.findall(pattern, line) + elif "tests/" in line: + # TODO: Improve the condition here. + if "tests/models/" in line or ( + "tests/quantization/" in line and job_name == "run_quantization_torch_gpu" + ): + model = line.split("/")[2] + else: + model = line.split("/")[1] + if model not in new_failed_tests: + new_failed_tests[model] = {"single-gpu": [], "multi-gpu": []} + for _, device in items: + new_failed_tests[model][f"{device}-gpu"].append(line) + nb_new_failed_tests += 1 + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/{filename}.json") + with open(file_path, "w", encoding="UTF-8") as fp: + json.dump(new_failed_tests, fp, ensure_ascii=False, indent=4) + + # upload results to Hub dataset + file_path = os.path.join(os.getcwd(), f"ci_results_{job_name}/{filename}.json") + commit_info = api.upload_file( + path_or_fileobj=file_path, + path_in_repo=f"{report_repo_folder}/ci_results_{job_name}/{filename}.json", + repo_id=report_repo_id, + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + new_failures_url = f"https://huggingface.co/datasets/{report_repo_id}/raw/{commit_info.oid}/{report_repo_folder}/ci_results_{job_name}/{filename}.json" + + if idx == 0: + block = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": f"*There are {nb_new_failed_tests} new failed tests*\n\n(compared to previous run: )", + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check new failures"}, + "url": new_failures_url, + }, + } + blocks.append(block) + else: + block = { + "type": "section", + "text": { + "type": "mrkdwn", + # TODO: We should NOT assume it's always Nvidia CI, but it's the case at this moment. + "text": f"*There are {nb_new_failed_tests} failed tests unique to {'this run' if not is_amd_daily_ci_workflow else 'AMD'}*\n\n(compared to Nvidia CI: )", + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check failures"}, + "url": new_failures_url, + }, + } + blocks.append(block) + + if diff_file_url is not None: + block = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": f"*Test results diff*\n\n(compared to previous run: )", + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check test result diff file"}, + "url": diff_file_url, + }, + } + blocks.append(block) + + if len(new_failure_blocks) > 0: + blocks.extend(new_failure_blocks) + + return json.dumps(blocks) + + @staticmethod + def error_out(title, ci_title="", runner_not_available=False, runner_failed=False, setup_failed=False): + blocks = [] + title_block = {"type": "header", "text": {"type": "plain_text", "text": title}} + blocks.append(title_block) + + if ci_title: + ci_title_block = {"type": "section", "text": {"type": "mrkdwn", "text": ci_title}} + blocks.append(ci_title_block) + + offline_runners = [] + if runner_not_available: + text = "💔 CI runners are not available! Tests are not run. 😭" + result = os.environ.get("OFFLINE_RUNNERS") + if result is not None: + offline_runners = json.loads(result) + elif runner_failed: + text = "💔 CI runners have problems! Tests are not run. 😭" + elif setup_failed: + text = "💔 Setup job failed. Tests are not run. 😭" + else: + text = "💔 There was an issue running the tests. 😭" + + error_block_1 = { + "type": "header", + "text": { + "type": "plain_text", + "text": text, + }, + } + + text = "" + if len(offline_runners) > 0: + text = "\n • " + "\n • ".join(offline_runners) + text = f"The following runners are offline:\n{text}\n\n" + text += "🙏 Let's fix it ASAP! 🙏" + + error_block_2 = { + "type": "section", + "text": { + "type": "plain_text", + "text": text, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + blocks.extend([error_block_1, error_block_2]) + + payload = json.dumps(blocks) + + print("Sending the following payload") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text=text, + blocks=payload, + ) + + def post(self): + payload = self.payload + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(payload)})) + + text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." + + self.thread_ts = client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + blocks=payload, + text=text, + ) + + def get_reply_blocks(self, job_name, job_result, failures, device, text): + """ + failures: A list with elements of the form {"line": full test name, "trace": error trace} + """ + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + + failure_text = "" + for idx, error in enumerate(failures): + new_text = failure_text + f"*{error['line']}*\n_{error['trace']}_\n\n" + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + title = job_name + if device is not None: + title += f" ({device}-gpu)" + + content = {"type": "section", "text": {"type": "mrkdwn", "text": text}} + + # TODO: Make sure we always have a valid job link (or at least a way not to break the report sending) + # Currently we get the device from a job's artifact name. + # If a device is found, the job name should contain the device type, for example, `XXX (single-gpu)`. + # This could be done by adding `machine_type` in a job's `strategy`. + # (If `job_result["job_link"][device]` is `None`, we get an error: `... [ERROR] must provide a string ...`) + if job_result["job_link"] is not None and job_result["job_link"][device] is not None: + content["accessory"] = { + "type": "button", + "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, + "url": job_result["job_link"][device], + } + + return [ + {"type": "header", "text": {"type": "plain_text", "text": title.upper(), "emoji": True}}, + content, + {"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}, + ] + + def get_new_model_failure_blocks(self, prev_ci_artifacts, with_header=True, to_truncate=True): + if prev_ci_artifacts is None: + return [] + + if len(self.model_results) > 0: + target_results = self.model_results + else: + target_results = self.additional_results[job_to_test_map[job_name]] + + # Make the format uniform between `model_results` and `additional_results[XXX]` + if "failures" in target_results: + target_results = {job_name: target_results} + sorted_dict = sorted(target_results.items(), key=lambda t: t[0]) + + job = job_to_test_map[job_name] + prev_model_results = {} + if ( + f"ci_results_{job_name}" in prev_ci_artifacts + and f"{test_to_result_name[job]}_results.json" in prev_ci_artifacts[f"ci_results_{job_name}"] + ): + prev_model_results = json.loads( + prev_ci_artifacts[f"ci_results_{job_name}"][f"{test_to_result_name[job]}_results.json"] + ) + # Make the format uniform between `model_results` and `additional_results[XXX]` + if "failures" in prev_model_results: + prev_model_results = {job_name: prev_model_results} + + all_failure_lines = {} + for job, job_result in sorted_dict: + if len(job_result["failures"]): + devices = sorted(job_result["failures"].keys(), reverse=True) + for device in devices: + failures = job_result["failures"][device] + prev_error_lines = {} + if job in prev_model_results and device in prev_model_results[job]["failures"]: + prev_error_lines = {error["line"] for error in prev_model_results[job]["failures"][device]} + + url = None + if job_result["job_link"] is not None and job_result["job_link"][device] is not None: + url = job_result["job_link"][device] + + for idx, error in enumerate(failures): + if error["line"] in prev_error_lines: + continue + + new_text = f"{error['line']}\n\n" + + if new_text not in all_failure_lines: + all_failure_lines[new_text] = [] + + all_failure_lines[new_text].append(f"<{url}|{device}>" if url is not None else device) + + MAX_ERROR_TEXT = 3000 - len("[Truncated]") - len("```New failures```\n\n") + if not to_truncate: + MAX_ERROR_TEXT = float("inf") + failure_text = "" + for line, devices in all_failure_lines.items(): + new_text = failure_text + f"{'|'.join(devices)} gpu\n{line}" + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + blocks = [] + if failure_text: + if with_header: + blocks.append( + {"type": "header", "text": {"type": "plain_text", "text": "New failures", "emoji": True}} + ) + else: + failure_text = f"{failure_text}" + blocks.append({"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}) + + return blocks + + def post_reply(self): + if self.thread_ts is None: + raise ValueError("Can only post reply if a post has been made.") + + sorted_dict = sorted(self.model_results.items(), key=lambda t: t[0]) + for job, job_result in sorted_dict: + if len(job_result["failures"]): + for device, failures in job_result["failures"].items(): + text = "\n".join( + sorted([f"*{k}*: {v[device]}" for k, v in job_result["failed"].items() if v[device]]) + ) + + blocks = self.get_reply_blocks(job, job_result, failures, device, text=text) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text=f"Results for {job}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + for job, job_result in self.additional_results.items(): + if len(job_result["failures"]): + for device, failures in job_result["failures"].items(): + blocks = self.get_reply_blocks( + job, + job_result, + failures, + device, + text=f"Number of failures: {job_result['failed'][device]}", + ) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text=f"Results for {job}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + +def retrieve_artifact(artifact_path: str, gpu: Optional[str]): + if gpu not in [None, "single", "multi"]: + raise ValueError(f"Invalid GPU for artifact. Passed GPU: `{gpu}`.") + + _artifact = {} + + if os.path.exists(artifact_path): + files = os.listdir(artifact_path) + for file in files: + try: + with open(os.path.join(artifact_path, file)) as f: + _artifact[file.split(".")[0]] = f.read() + except UnicodeDecodeError as e: + raise ValueError(f"Could not open {os.path.join(artifact_path, file)}.") from e + + return _artifact + + +def retrieve_available_artifacts(): + class Artifact: + def __init__(self, name: str, single_gpu: bool = False, multi_gpu: bool = False): + self.name = name + self.single_gpu = single_gpu + self.multi_gpu = multi_gpu + self.paths = [] + + def __str__(self): + return self.name + + def add_path(self, path: str, gpu: Optional[str] = None): + self.paths.append({"name": self.name, "path": path, "gpu": gpu}) + + _available_artifacts: dict[str, Artifact] = {} + + directories = filter(os.path.isdir, os.listdir()) + for directory in directories: + artifact_name = directory + + name_parts = artifact_name.split("_postfix_") + if len(name_parts) > 1: + artifact_name = name_parts[0] + + if artifact_name.startswith("single-gpu"): + artifact_name = artifact_name[len("single-gpu") + 1 :] + + if artifact_name in _available_artifacts: + _available_artifacts[artifact_name].single_gpu = True + else: + _available_artifacts[artifact_name] = Artifact(artifact_name, single_gpu=True) + + _available_artifacts[artifact_name].add_path(directory, gpu="single") + + elif artifact_name.startswith("multi-gpu"): + artifact_name = artifact_name[len("multi-gpu") + 1 :] + + if artifact_name in _available_artifacts: + _available_artifacts[artifact_name].multi_gpu = True + else: + _available_artifacts[artifact_name] = Artifact(artifact_name, multi_gpu=True) + + _available_artifacts[artifact_name].add_path(directory, gpu="multi") + else: + if artifact_name not in _available_artifacts: + _available_artifacts[artifact_name] = Artifact(artifact_name) + + _available_artifacts[artifact_name].add_path(directory) + + return _available_artifacts + + +def prepare_reports(title, header, reports, to_truncate=True): + report = "" + + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + if not to_truncate: + MAX_ERROR_TEXT = float("inf") + + if len(reports) > 0: + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + + for idx in range(len(reports)): + _report = header + "\n".join(reports[: idx + 1]) + new_report = f"{title}:\n```\n{_report}\n```\n" + if len(new_report) > MAX_ERROR_TEXT: + # `report` here has length <= 3000 + report = report + "[Truncated]" + break + report = new_report + + return report + + +def pop_default(l: list[Any], i: int, default: Any) -> Any: + try: + return l.pop(i) + except IndexError: + return default + + +if __name__ == "__main__": + api = HfApi() + client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) + + SLACK_REPORT_CHANNEL_ID = os.environ["SLACK_REPORT_CHANNEL"] + + # runner_status = os.environ.get("RUNNER_STATUS") + # runner_env_status = os.environ.get("RUNNER_ENV_STATUS") + setup_status = os.environ.get("SETUP_STATUS") + + # runner_not_available = True if runner_status is not None and runner_status != "success" else False + # runner_failed = True if runner_env_status is not None and runner_env_status != "success" else False + # Let's keep the lines regardig runners' status (we might be able to use them again in the future) + runner_not_available = False + runner_failed = False + # Some jobs don't depend (`needs`) on the job `setup`: in this case, the status of the job `setup` is `skipped`. + setup_failed = setup_status not in ["skipped", "success"] + + org = "huggingface" + repo = "transformers" + repository_full_name = f"{org}/{repo}" + + # This env. variable is set in workflow file (under the job `send_results`). + ci_event = os.environ["CI_EVENT"] + + # To find the PR number in a commit title, for example, `Add AwesomeFormer model (#99999)` + pr_number_re = re.compile(r"\(#(\d+)\)$") + + # Add Commit/PR title with a link for push CI + # (check the title in 2 env. variables - depending on the CI is triggered via `push` or `workflow_run` event) + ci_title_push = os.environ.get("CI_TITLE_PUSH") + ci_title_workflow_run = os.environ.get("CI_TITLE_WORKFLOW_RUN") + ci_title = ci_title_push if ci_title_push else ci_title_workflow_run + + ci_sha = os.environ.get("CI_SHA") + + ci_url = None + if ci_sha: + ci_url = f"https://github.com/{repository_full_name}/commit/{ci_sha}" + + if ci_title is not None: + if ci_url is None: + raise ValueError( + "When a title is found (`ci_title`), it means a `push` event or a `workflow_run` even (triggered by " + "another `push` event), and the commit SHA has to be provided in order to create the URL to the " + "commit page." + ) + ci_title = ci_title.strip().split("\n")[0].strip() + + # Retrieve the PR title and author login to complete the report + commit_number = ci_url.split("/")[-1] + ci_detail_url = f"https://api.github.com/repos/{repository_full_name}/commits/{commit_number}" + ci_details = requests.get(ci_detail_url).json() + ci_author = ci_details["author"]["login"] + + merged_by = None + # Find the PR number (if any) and change the url to the actual PR page. + numbers = pr_number_re.findall(ci_title) + if len(numbers) > 0: + pr_number = numbers[0] + ci_detail_url = f"https://api.github.com/repos/{repository_full_name}/pulls/{pr_number}" + ci_details = requests.get(ci_detail_url).json() + + ci_author = ci_details["user"]["login"] + ci_url = f"https://github.com/{repository_full_name}/pull/{pr_number}" + + merged_by = ci_details["merged_by"]["login"] + + if merged_by is None: + ci_title = f"<{ci_url}|{ci_title}>\nAuthor: {ci_author}" + else: + ci_title = f"<{ci_url}|{ci_title}>\nAuthor: {ci_author} | Merged by: {merged_by}" + + elif ci_sha: + ci_title = f"<{ci_url}|commit: {ci_sha}>" + + else: + ci_title = "" + + # `title` will be updated at the end before calling `Message()`. + title = f"🤗 Results of {ci_event}" + if runner_not_available or runner_failed or setup_failed: + Message.error_out(title, ci_title, runner_not_available, runner_failed, setup_failed) + exit(0) + + # sys.argv[0] is always `utils/notification_service.py`. + arguments = sys.argv[1:] + # In our usage in `.github/workflows/slack-report.yml`, we always pass an argument when calling this script. + # The argument could be an empty string `""` if a job doesn't depend on the job `setup`. + if arguments[0] == "": + job_matrix = [] + else: + job_matrix_as_str = arguments[0] + try: + folder_slices = ast.literal_eval(job_matrix_as_str) + if len(folder_slices) > 0: + if isinstance(folder_slices[0], list): + # Need to change from elements like `models/bert` to `models_bert` (the ones used as artifact names). + job_matrix = [ + x.replace("models/", "models_").replace("quantization/", "quantization_") + for folders in folder_slices + for x in folders + ] + elif isinstance(folder_slices[0], str): + job_matrix = [ + x.replace("models/", "models_").replace("quantization/", "quantization_") + for x in folder_slices + ] + except Exception: + Message.error_out(title, ci_title) + raise ValueError("Errored out.") + + github_actions_jobs = get_jobs( + workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"] + ) + github_actions_job_links = {job["name"]: job["html_url"] for job in github_actions_jobs} + + artifact_name_to_job_map = {} + for job in github_actions_jobs: + for step in job["steps"]: + if step["name"].startswith("Test suite reports artifacts: "): + artifact_name = step["name"][len("Test suite reports artifacts: ") :] + artifact_name_to_job_map[artifact_name] = job + break + + available_artifacts = retrieve_available_artifacts() + + test_categories = [ + "PyTorch", + "TensorFlow", + "Flax", + "Tokenizers", + "Pipelines", + "Trainer", + "ONNX", + "Auto", + "Quantization", + "Unclassified", + ] + + job_name = os.getenv("CI_TEST_JOB") + report_name_prefix = job_name + + # This dict will contain all the information relative to each model: + # - Failures: the total, as well as the number of failures per-category defined above + # - Success: total + # - Time spent: as a comma-separated list of elapsed time + # - Failures: as a line-break separated list of errors + matrix_job_results = { + matrix_name: { + "failed": {m: {"unclassified": 0, "single": 0, "multi": 0} for m in test_categories}, + "errors": 0, + "success": 0, + "skipped": 0, + "time_spent": [], + "failures": {}, + "job_link": {}, + } + for matrix_name in job_matrix + if f"{report_name_prefix}_{matrix_name}_test_reports" in available_artifacts + } + + unclassified_model_failures = [] + + for matrix_name in matrix_job_results: + for artifact_path_dict in available_artifacts[f"{report_name_prefix}_{matrix_name}_test_reports"].paths: + path = artifact_path_dict["path"] + artifact_gpu = artifact_path_dict["gpu"] + + if path not in artifact_name_to_job_map: + # Mismatch between available artifacts and reported jobs on github. It happens. + continue + + artifact = retrieve_artifact(path, artifact_gpu) + if "stats" in artifact: + # Link to the GitHub Action job + job = artifact_name_to_job_map[path] + matrix_job_results[matrix_name]["job_link"][artifact_gpu] = job["html_url"] + failed, errors, success, skipped, time_spent = handle_test_results(artifact["stats"]) + matrix_job_results[matrix_name]["success"] += success + matrix_job_results[matrix_name]["errors"] += errors + matrix_job_results[matrix_name]["skipped"] += skipped + matrix_job_results[matrix_name]["time_spent"].append(float(time_spent[:-1])) + + stacktraces = handle_stacktraces(artifact["failures_line"]) + + # TODO: ??? + for line in artifact["summary_short"].split("\n"): + if line.startswith("FAILED "): + # Avoid the extra `FAILED` entry given by `run_test_using_subprocess` causing issue when calling + # `stacktraces.pop` below. + # See `run_test_using_subprocess` in `src/transformers/testing_utils.py` + if " - Failed: (subprocess)" in line: + continue + line = line[len("FAILED ") :] + line = line.split()[0].replace("\n", "") + + if artifact_gpu not in matrix_job_results[matrix_name]["failures"]: + matrix_job_results[matrix_name]["failures"][artifact_gpu] = [] + + trace = pop_default(stacktraces, 0, "Cannot retrieve error message.") + matrix_job_results[matrix_name]["failures"][artifact_gpu].append( + {"line": line, "trace": trace} + ) + + # TODO: How to deal wit this + + if re.search("tests/quantization", line): + matrix_job_results[matrix_name]["failed"]["Quantization"][artifact_gpu] += 1 + + elif re.search("test_modeling_tf_", line): + matrix_job_results[matrix_name]["failed"]["TensorFlow"][artifact_gpu] += 1 + + elif re.search("test_modeling_flax_", line): + matrix_job_results[matrix_name]["failed"]["Flax"][artifact_gpu] += 1 + + elif re.search("test_modeling", line): + matrix_job_results[matrix_name]["failed"]["PyTorch"][artifact_gpu] += 1 + + elif re.search("test_tokenization", line): + matrix_job_results[matrix_name]["failed"]["Tokenizers"][artifact_gpu] += 1 + + elif re.search("test_pipelines", line): + matrix_job_results[matrix_name]["failed"]["Pipelines"][artifact_gpu] += 1 + + elif re.search("test_trainer", line): + matrix_job_results[matrix_name]["failed"]["Trainer"][artifact_gpu] += 1 + + elif re.search("onnx", line): + matrix_job_results[matrix_name]["failed"]["ONNX"][artifact_gpu] += 1 + + elif re.search("auto", line): + matrix_job_results[matrix_name]["failed"]["Auto"][artifact_gpu] += 1 + + else: + matrix_job_results[matrix_name]["failed"]["Unclassified"][artifact_gpu] += 1 + unclassified_model_failures.append(line) + + # Additional runs + additional_files = { + "PyTorch pipelines": "run_pipelines_torch_gpu_test_reports", + "TensorFlow pipelines": "run_pipelines_tf_gpu_test_reports", + "Examples directory": "run_examples_gpu_test_reports", + "DeepSpeed": "run_torch_cuda_extensions_gpu_test_reports", + } + + if ci_event in ["push", "Nightly CI"] or ci_event.startswith("Past CI"): + del additional_files["Examples directory"] + del additional_files["PyTorch pipelines"] + del additional_files["TensorFlow pipelines"] + elif ci_event.startswith("Scheduled CI (AMD)"): + del additional_files["TensorFlow pipelines"] + del additional_files["DeepSpeed"] + elif ci_event.startswith("Push CI (AMD)"): + additional_files = {} + + report_repo_id = os.getenv("REPORT_REPO_ID") + + # if it is not a scheduled run, upload the reports to a subfolder under `report_repo_folder` + report_repo_subfolder = "" + if os.getenv("GITHUB_EVENT_NAME") != "schedule": + report_repo_subfolder = f"{os.getenv('GITHUB_RUN_NUMBER')}-{os.getenv('GITHUB_RUN_ID')}" + report_repo_subfolder = f"runs/{report_repo_subfolder}" + + workflow_run = get_last_daily_ci_run( + token=os.environ["ACCESS_REPO_INFO_TOKEN"], workflow_run_id=os.getenv("GITHUB_RUN_ID") + ) + workflow_run_created_time = workflow_run["created_at"] + workflow_id = workflow_run["workflow_id"] + + report_repo_folder = workflow_run_created_time.split("T")[0] + + if report_repo_subfolder: + report_repo_folder = f"{report_repo_folder}/{report_repo_subfolder}" + + # Remove some entries in `additional_files` if they are not concerned. + test_name = None + if job_name in job_to_test_map: + test_name = job_to_test_map[job_name] + additional_files = {k: v for k, v in additional_files.items() if k == test_name} + + additional_results = { + key: { + "failed": {"unclassified": 0, "single": 0, "multi": 0}, + "errors": 0, + "success": 0, + "skipped": 0, + "time_spent": [], + "error": False, + "failures": {}, + "job_link": {}, + } + for key in additional_files + } + + for key in additional_results: + # If a whole suite of test fails, the artifact isn't available. + if additional_files[key] not in available_artifacts: + additional_results[key]["error"] = True + continue + + for artifact_path_dict in available_artifacts[additional_files[key]].paths: + path = artifact_path_dict["path"] + artifact_gpu = artifact_path_dict["gpu"] + + # Link to the GitHub Action job + job = artifact_name_to_job_map[path] + additional_results[key]["job_link"][artifact_gpu] = job["html_url"] + + artifact = retrieve_artifact(path, artifact_gpu) + stacktraces = handle_stacktraces(artifact["failures_line"]) + + failed, errors, success, skipped, time_spent = handle_test_results(artifact["stats"]) + additional_results[key]["failed"][artifact_gpu or "unclassified"] += failed + additional_results[key]["success"] += success + additional_results[key]["errors"] += errors + additional_results[key]["skipped"] += skipped + additional_results[key]["time_spent"].append(float(time_spent[:-1])) + + if len(artifact["errors"]): + additional_results[key]["error"] = True + + if failed: + for line in artifact["summary_short"].split("\n"): + if line.startswith("FAILED "): + # Avoid the extra `FAILED` entry given by `run_test_using_subprocess` causing issue when calling + # `stacktraces.pop` below. + # See `run_test_using_subprocess` in `src/transformers/testing_utils.py` + if " - Failed: (subprocess)" in line: + continue + line = line[len("FAILED ") :] + line = line.split()[0].replace("\n", "") + + if artifact_gpu not in additional_results[key]["failures"]: + additional_results[key]["failures"][artifact_gpu] = [] + + trace = pop_default(stacktraces, 0, "Cannot retrieve error message.") + additional_results[key]["failures"][artifact_gpu].append({"line": line, "trace": trace}) + + # Let's only check the warning for the model testing job. Currently, the job `run_extract_warnings` is only run + # when `inputs.job` (in the workflow file) is `run_models_gpu`. The reason is: otherwise we need to save several + # artifacts with different names which complicates the logic for an insignificant part of the CI workflow reporting. + selected_warnings = [] + if job_name == "run_models_gpu": + if "warnings_in_ci" in available_artifacts: + directory = available_artifacts["warnings_in_ci"].paths[0]["path"] + with open(os.path.join(directory, "selected_warnings.json")) as fp: + selected_warnings = json.load(fp) + + if not os.path.isdir(os.path.join(os.getcwd(), f"ci_results_{job_name}")): + os.makedirs(os.path.join(os.getcwd(), f"ci_results_{job_name}")) + + nvidia_daily_ci_workflow = "huggingface/transformers/.github/workflows/self-scheduled-caller.yml" + amd_daily_ci_workflows = ( + "huggingface/transformers/.github/workflows/self-scheduled-amd-mi300-caller.yml", + "huggingface/transformers/.github/workflows/self-scheduled-amd-mi325-caller.yml", + ) + is_nvidia_daily_ci_workflow = os.environ.get("GITHUB_WORKFLOW_REF").startswith(nvidia_daily_ci_workflow) + is_amd_daily_ci_workflow = os.environ.get("GITHUB_WORKFLOW_REF").startswith(amd_daily_ci_workflows) + + is_scheduled_ci_run = os.environ.get("GITHUB_EVENT_NAME") == "schedule" + # For AMD workflow runs: the different AMD CI callers (MI210/MI250/MI300, etc.) are triggered by `workflow_run` + # event of `.github/workflows/self-scheduled-amd-caller.yml`. + if is_amd_daily_ci_workflow: + # Get the path to the file on the runner that contains the full event webhook payload. + event_payload_path = os.environ.get("GITHUB_EVENT_PATH") + # Load the event payload + with open(event_payload_path) as fp: + event_payload = json.load(fp) + # The event that triggers the `workflow_run` event. + if "workflow_run" in event_payload: + is_scheduled_ci_run = event_payload["workflow_run"]["event"] == "schedule" + + test_name_and_result_pairs = [] + if len(matrix_job_results) > 0: + test_name = job_to_test_map[job_name] + test_name_and_result_pairs.append((test_name, matrix_job_results)) + + for test_name, result in additional_results.items(): + test_name_and_result_pairs.append((test_name, result)) + + for test_name, result in test_name_and_result_pairs: + with open(f"ci_results_{job_name}/{test_to_result_name[test_name]}_results.json", "w", encoding="UTF-8") as fp: + json.dump(result, fp, indent=4, ensure_ascii=False) + + api.upload_file( + path_or_fileobj=f"ci_results_{job_name}/{test_to_result_name[test_name]}_results.json", + path_in_repo=f"{report_repo_folder}/ci_results_{job_name}/{test_to_result_name[test_name]}_results.json", + repo_id=report_repo_id, + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + + # Let's create a file contain job --> job link + if len(matrix_job_results) > 0: + target_results = matrix_job_results + else: + default_result = { + "failed": {"unclassified": 0, "single": 0, "multi": 0}, + "success": 0, + "time_spent": [], + "error": False, + "failures": {}, + "job_link": {}, + } + + key = job_to_test_map.get(job_name) + target_results = additional_results.get(key, default_result) if key is not None else default_result + + # Make the format uniform between `model_results` and `additional_results[XXX]` + if "failures" in target_results: + target_results = {job_name: target_results} + + job_links = {} + sorted_dict = sorted(target_results.items(), key=lambda t: t[0]) + for job, job_result in sorted_dict: + if job.startswith("models_"): + job = job[len("models_") :] + elif job.startswith("quantization_"): + job = job[len("quantization_") :] + job_links[job] = job_result["job_link"] + + with open(f"ci_results_{job_name}/job_links.json", "w", encoding="UTF-8") as fp: + json.dump(job_links, fp, indent=4, ensure_ascii=False) + + api.upload_file( + path_or_fileobj=f"ci_results_{job_name}/job_links.json", + path_in_repo=f"{report_repo_folder}/ci_results_{job_name}/job_links.json", + repo_id=report_repo_id, + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + + prev_workflow_run_id = None + other_workflow_run_ids = [] + + if is_scheduled_ci_run: + prev_workflow_run_id = get_last_daily_ci_workflow_run_id( + token=os.environ["ACCESS_REPO_INFO_TOKEN"], workflow_id=workflow_id + ) + # For a scheduled run that is not the Nvidia's scheduled daily CI, add Nvidia's scheduled daily CI run as a target to compare. + if not is_nvidia_daily_ci_workflow: + # The id of the workflow `.github/workflows/self-scheduled-caller.yml` (not of a workflow run of it). + other_workflow_id = "90575235" + # We need to get the Nvidia's scheduled daily CI run that match the current run (i.e. run with the same commit SHA) + other_workflow_run_id = get_last_daily_ci_workflow_run_id( + token=os.environ["ACCESS_REPO_INFO_TOKEN"], workflow_id=other_workflow_id, commit_sha=ci_sha + ) + other_workflow_run_ids.append(other_workflow_run_id) + else: + prev_workflow_run_id = os.environ["PREV_WORKFLOW_RUN_ID"] + other_workflow_run_id = os.environ["OTHER_WORKFLOW_RUN_ID"] + other_workflow_run_ids.append(other_workflow_run_id) + + prev_ci_artifacts = (None, None) + other_ci_artifacts = [] + + output_dir = os.path.join(os.getcwd(), "previous_reports") + os.makedirs(output_dir, exist_ok=True) + + for idx, target_workflow_run_id in enumerate([prev_workflow_run_id] + other_workflow_run_ids): + if target_workflow_run_id is None or target_workflow_run_id == "": + continue + else: + artifact_names = [f"ci_results_{job_name}"] + ci_artifacts = get_last_daily_ci_reports( + artifact_names=artifact_names, + output_dir=output_dir, + token=os.environ["ACCESS_REPO_INFO_TOKEN"], + workflow_run_id=target_workflow_run_id, + ) + if idx == 0: + prev_ci_artifacts = (target_workflow_run_id, ci_artifacts) + else: + other_ci_artifacts.append((target_workflow_run_id, ci_artifacts)) + + # Only for AMD at this moment. + # TODO: put this into a method + diff_file_url = None + if is_amd_daily_ci_workflow: + if not (prev_workflow_run_id is None or prev_workflow_run_id == ""): + ci_artifacts = get_last_daily_ci_reports( + artifact_names=None, + output_dir=output_dir, + token=os.environ["ACCESS_REPO_INFO_TOKEN"], + workflow_run_id=prev_workflow_run_id, + ) + + current_artifacts = sorted([d for d in os.listdir() if os.path.isdir(d) and d.endswith("_test_reports")]) + prev_artifacts = sorted([d for d in os.listdir(output_dir) if os.path.isdir(os.path.join(output_dir, d)) and d.endswith("_test_reports")]) # fmt: skip + + current_artifacts_set = {} + for d in current_artifacts: + current_artifacts_set[d] = os.path.join(d, "summary_short.txt") + + prev_artifacts_set = {} + for d in prev_artifacts: + prev_artifacts_set[d] = os.path.join(output_dir, d, "summary_short.txt") + + report = compare_job_sets(prev_artifacts_set, current_artifacts_set) + + with open(f"ci_results_{job_name}/test_results_diff.json", "w") as fp: + fp.write(report) + + # upload + commit_info = api.upload_file( + path_or_fileobj=f"ci_results_{job_name}/test_results_diff.json", + path_in_repo=f"{report_repo_folder}/ci_results_{job_name}/test_results_diff.json", + repo_id=report_repo_id, + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + diff_file_url = f"https://huggingface.co/datasets/{report_repo_id}/resolve/{commit_info.oid}/{report_repo_folder}/ci_results_{job_name}/test_results_diff.json" + + ci_name_in_report = "" + if job_name in job_to_test_map: + ci_name_in_report = job_to_test_map[job_name] + + title = f"🤗 Results of {ci_event}: {ci_name_in_report}" + + message = Message( + title, + ci_title, + matrix_job_results, + additional_results, + selected_warnings=selected_warnings, + prev_ci_artifacts=prev_ci_artifacts, + other_ci_artifacts=other_ci_artifacts, + ) + + # send report only if there is any failure (for push CI) + if message.n_failures or (ci_event != "push" and not ci_event.startswith("Push CI (AMD)")): + message.post() + message.post_reply() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/notification_service_doc_tests.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/notification_service_doc_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..f8f7b8c610a0bebdce7507d08579734d04e5a8ee --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/notification_service_doc_tests.py @@ -0,0 +1,384 @@ +# 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. + +import json +import os +import re +import time + +from get_ci_error_statistics import get_jobs +from slack_sdk import WebClient + + +client = WebClient(token=os.environ["CI_SLACK_BOT_TOKEN"]) + + +def handle_test_results(test_results): + expressions = test_results.split(" ") + + failed = 0 + success = 0 + + # When the output is short enough, the output is surrounded by = signs: "== OUTPUT ==" + # When it is too long, those signs are not present. + time_spent = expressions[-2] if "=" in expressions[-1] else expressions[-1] + + for i, expression in enumerate(expressions): + if "failed" in expression: + failed += int(expressions[i - 1]) + if "passed" in expression: + success += int(expressions[i - 1]) + + return failed, success, time_spent + + +def extract_first_line_failure(failures_short_lines): + failures = {} + file = None + in_error = False + for line in failures_short_lines.split("\n"): + if re.search(r"_ \[doctest\]", line): + in_error = True + file = line.split(" ")[2] + elif in_error and not line.split(" ")[0].isdigit(): + failures[file] = line + in_error = False + + return failures + + +class Message: + def __init__(self, title: str, doc_test_results: dict): + self.title = title + + self.n_success = sum(job_result["n_success"] for job_result in doc_test_results.values()) + self.n_failures = sum(job_result["n_failures"] for job_result in doc_test_results.values()) + self.n_tests = self.n_success + self.n_failures + + # Failures and success of the modeling tests + self.doc_test_results = doc_test_results + + @property + def time(self) -> str: + all_results = [*self.doc_test_results.values()] + time_spent = [r["time_spent"].split(", ")[0] for r in all_results if len(r["time_spent"])] + total_secs = 0 + + for time in time_spent: + time_parts = time.split(":") + + # Time can be formatted as xx:xx:xx, as .xx, or as x.xx if the time spent was less than a minute. + if len(time_parts) == 1: + time_parts = [0, 0, time_parts[0]] + + hours, minutes, seconds = int(time_parts[0]), int(time_parts[1]), float(time_parts[2]) + total_secs += hours * 3600 + minutes * 60 + seconds + + hours, minutes, seconds = total_secs // 3600, (total_secs % 3600) // 60, total_secs % 60 + return f"{int(hours)}h{int(minutes)}m{int(seconds)}s" + + @property + def header(self) -> dict: + return {"type": "header", "text": {"type": "plain_text", "text": self.title}} + + @property + def no_failures(self) -> dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": f"🌞 There were no failures: all {self.n_tests} tests passed. The suite ran in {self.time}.", + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def failures(self) -> dict: + return { + "type": "section", + "text": { + "type": "plain_text", + "text": ( + f"There were {self.n_failures} failures, out of {self.n_tests} tests.\nThe suite ran in" + f" {self.time}." + ), + "emoji": True, + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + + @property + def category_failures(self) -> list[dict]: + failure_blocks = [] + + MAX_ERROR_TEXT = 3000 - len("The following examples had failures:\n\n\n\n") - len("[Truncated]\n") + line_length = 40 + category_failures = {k: v["failed"] for k, v in doc_test_results.items() if isinstance(v, dict)} + + def single_category_failures(category, failures): + text = "" + if len(failures) == 0: + return "" + text += f"*{category} failures*:".ljust(line_length // 2).rjust(line_length // 2) + "\n" + + for idx, failure in enumerate(failures): + new_text = text + f"`{failure}`\n" + if len(new_text) > MAX_ERROR_TEXT: + text = text + "[Truncated]\n" + break + text = new_text + + return text + + for category, failures in category_failures.items(): + report = single_category_failures(category, failures) + if len(report) == 0: + continue + block = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": f"The following examples had failures:\n\n\n{report}\n", + }, + } + failure_blocks.append(block) + + return failure_blocks + + @property + def payload(self) -> str: + blocks = [self.header] + + if self.n_failures > 0: + blocks.append(self.failures) + + if self.n_failures > 0: + blocks.extend(self.category_failures) + + if self.n_failures == 0: + blocks.append(self.no_failures) + + return json.dumps(blocks) + + @staticmethod + def error_out(): + payload = [ + { + "type": "section", + "text": { + "type": "plain_text", + "text": "There was an issue running the tests.", + }, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/transformers/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + ] + + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(payload)})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text="There was an issue running the tests.", + blocks=payload, + ) + + def post(self): + print("Sending the following payload") + print(json.dumps({"blocks": json.loads(self.payload)})) + + text = f"{self.n_failures} failures out of {self.n_tests} tests," if self.n_failures else "All tests passed." + + self.thread_ts = client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + blocks=self.payload, + text=text, + ) + + def get_reply_blocks(self, job_name, job_link, failures, text): + # `text` must be less than 3001 characters in Slack SDK + # keep some room for adding "[Truncated]" when necessary + MAX_ERROR_TEXT = 3000 - len("[Truncated]") + + failure_text = "" + for key, value in failures.items(): + new_text = failure_text + f"*{key}*\n_{value}_\n\n" + if len(new_text) > MAX_ERROR_TEXT: + # `failure_text` here has length <= 3000 + failure_text = failure_text + "[Truncated]" + break + # `failure_text` here has length <= MAX_ERROR_TEXT + failure_text = new_text + + title = job_name + content = {"type": "section", "text": {"type": "mrkdwn", "text": text}} + + if job_link is not None: + content["accessory"] = { + "type": "button", + "text": {"type": "plain_text", "text": "GitHub Action job", "emoji": True}, + "url": job_link, + } + + return [ + {"type": "header", "text": {"type": "plain_text", "text": title, "emoji": True}}, + content, + {"type": "section", "text": {"type": "mrkdwn", "text": failure_text}}, + ] + + def post_reply(self): + if self.thread_ts is None: + raise ValueError("Can only post reply if a post has been made.") + + sorted_dict = sorted(self.doc_test_results.items(), key=lambda t: t[0]) + for job_name, job_result in sorted_dict: + if len(job_result["failures"]) > 0: + text = f"*Num failures* :{len(job_result['failed'])} \n" + failures = job_result["failures"] + blocks = self.get_reply_blocks(job_name, job_result["job_link"], failures, text=text) + + print("Sending the following reply") + print(json.dumps({"blocks": blocks})) + + client.chat_postMessage( + channel=SLACK_REPORT_CHANNEL_ID, + text=f"Results for {job_name}", + blocks=blocks, + thread_ts=self.thread_ts["ts"], + ) + + time.sleep(1) + + +def retrieve_artifact(name: str): + _artifact = {} + + if os.path.exists(name): + files = os.listdir(name) + for file in files: + try: + with open(os.path.join(name, file), encoding="utf-8") as f: + _artifact[file.split(".")[0]] = f.read() + except UnicodeDecodeError as e: + raise ValueError(f"Could not open {os.path.join(name, file)}.") from e + + return _artifact + + +def retrieve_available_artifacts(): + class Artifact: + def __init__(self, name: str): + self.name = name + self.paths = [] + + def __str__(self): + return self.name + + def add_path(self, path: str): + self.paths.append({"name": self.name, "path": path}) + + _available_artifacts: dict[str, Artifact] = {} + + directories = filter(os.path.isdir, os.listdir()) + for directory in directories: + artifact_name = directory + if artifact_name not in _available_artifacts: + _available_artifacts[artifact_name] = Artifact(artifact_name) + + _available_artifacts[artifact_name].add_path(directory) + + return _available_artifacts + + +if __name__ == "__main__": + SLACK_REPORT_CHANNEL_ID = os.environ["SLACK_REPORT_CHANNEL"] + + github_actions_jobs = get_jobs( + workflow_run_id=os.environ["GITHUB_RUN_ID"], token=os.environ["ACCESS_REPO_INFO_TOKEN"] + ) + + artifact_name_to_job_map = {} + for job in github_actions_jobs: + for step in job["steps"]: + if step["name"].startswith("Test suite reports artifacts: "): + artifact_name = step["name"][len("Test suite reports artifacts: ") :] + artifact_name_to_job_map[artifact_name] = job + break + + available_artifacts = retrieve_available_artifacts() + + doc_test_results = {} + # `artifact_key` is the artifact path + for artifact_obj in available_artifacts.values(): + artifact_path = artifact_obj.paths[0] + if not artifact_path["path"].startswith("doc_tests_gpu_test_reports_"): + continue + + # change "_" back to "/" (to show the job name as path) + job_name = artifact_path["path"].replace("doc_tests_gpu_test_reports_", "").replace("_", "/") + + # This dict (for each job) will contain all the information relative to each doc test job, in particular: + # - failed: list of failed tests + # - failures: dict in the format 'test': 'error_message' + job_result = {} + doc_test_results[job_name] = job_result + + job = artifact_name_to_job_map[artifact_path["path"]] + job_result["job_link"] = job["html_url"] + job_result["category"] = "Python Examples" if job_name.startswith("src/") else "MD Examples" + + artifact = retrieve_artifact(artifact_path["path"]) + if "stats" in artifact: + failed, success, time_spent = handle_test_results(artifact["stats"]) + job_result["n_failures"] = failed + job_result["n_success"] = success + job_result["time_spent"] = time_spent[1:-1] + ", " + job_result["failed"] = [] + job_result["failures"] = {} + + all_failures = extract_first_line_failure(artifact["failures_short"]) + for line in artifact["summary_short"].split("\n"): + if re.search("FAILED", line): + line = line.replace("FAILED ", "") + line = line.split()[0].replace("\n", "") + + if "::" in line: + file_path, test = line.split("::") + else: + file_path, test = line, line + + job_result["failed"].append(test) + failure = all_failures.get(test, "N/A") + job_result["failures"][test] = failure + + # Save and to be uploaded as artifact + os.makedirs("doc_test_results", exist_ok=True) + with open("doc_test_results/doc_test_results.json", "w", encoding="UTF-8") as fp: + json.dump(doc_test_results, fp, ensure_ascii=False, indent=4) + + message = Message("🤗 Results of the doc tests.", doc_test_results) + message.post() + message.post_reply() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/past_ci_versions.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/past_ci_versions.py new file mode 100644 index 0000000000000000000000000000000000000000..858f7184d707e4158821cb259b6869ac44612333 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/past_ci_versions.py @@ -0,0 +1,126 @@ +import argparse +import os + + +past_versions_testing = { + "pytorch": { + "1.13": { + "torch": "1.13.1", + "torchvision": "0.14.1", + "torchaudio": "0.13.1", + "python": 3.9, + "cuda": "cu116", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1" + " --extra-index-url https://download.pytorch.org/whl/cu116" + ), + "base_image": "nvidia/cuda:11.6.2-cudnn8-devel-ubuntu20.04", + }, + "1.12": { + "torch": "1.12.1", + "torchvision": "0.13.1", + "torchaudio": "0.12.1", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.12.1 torchvision==0.13.1 torchaudio==0.12.1" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "1.11": { + "torch": "1.11.0", + "torchvision": "0.12.0", + "torchaudio": "0.11.0", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.11.0 torchvision==0.12.0 torchaudio==0.11.0" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "1.10": { + "torch": "1.10.2", + "torchvision": "0.11.3", + "torchaudio": "0.10.2", + "python": 3.9, + "cuda": "cu113", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.10.2 torchvision==0.11.3 torchaudio==0.10.2" + " --extra-index-url https://download.pytorch.org/whl/cu113" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + # torchaudio < 0.10 has no CUDA-enabled binary distributions + "1.9": { + "torch": "1.9.1", + "torchvision": "0.10.1", + "torchaudio": "0.9.1", + "python": 3.9, + "cuda": "cu111", + "install": ( + "python3 -m pip install --no-cache-dir -U torch==1.9.1 torchvision==0.10.1 torchaudio==0.9.1" + " --extra-index-url https://download.pytorch.org/whl/cu111" + ), + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + }, + "tensorflow": { + "2.11": { + "tensorflow": "2.11.1", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.11.1", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.10": { + "tensorflow": "2.10.1", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.10.1", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.9": { + "tensorflow": "2.9.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.9.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.8": { + "tensorflow": "2.8.2", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.8.2", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.7": { + "tensorflow": "2.7.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.7.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.6": { + "tensorflow": "2.6.5", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.6.5", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + "2.5": { + "tensorflow": "2.5.3", + "install": "python3 -m pip install --no-cache-dir -U tensorflow==2.5.3", + "base_image": "nvidia/cuda:11.2.2-cudnn8-devel-ubuntu20.04", + }, + }, +} + + +if __name__ == "__main__": + parser = argparse.ArgumentParser("Choose the framework and version to install") + parser.add_argument( + "--framework", help="The framework to install. Should be `torch` or `tensorflow`", type=str, required=True + ) + parser.add_argument("--version", help="The version of the framework to install.", type=str, required=True) + args = parser.parse_args() + + info = past_versions_testing[args.framework][args.version] + + os.system(f"echo \"export INSTALL_CMD='{info['install']}'\" >> ~/.profile") + print(f"echo \"export INSTALL_CMD='{info['install']}'\" >> ~/.profile") + + cuda = "" + if args.framework == "pytorch": + cuda = info["cuda"] + os.system(f"echo \"export CUDA='{cuda}'\" >> ~/.profile") + print(f"echo \"export CUDA='{cuda}'\" >> ~/.profile") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/patch_helper.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/patch_helper.py new file mode 100644 index 0000000000000000000000000000000000000000..8aae0025188d541f1d50211c5a7829319125bea2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/patch_helper.py @@ -0,0 +1,156 @@ +# coding=utf-8 +# Copyright 2024 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. +""" +This should help you prepare a patch, automatically extracting the commits to cherry-pick +in chronological order to avoid merge conflicts. An equivalent way to do this is to use +`git log --pretty=oneline HEAD...v4.41.0` and grep. + +Potential TODO: automatically cherry-picks them. + +Pass in a list of PR: +`python utils/patch_helper.py --prs 31108 31054 31008 31010 31004` +will produce the following: +```bash +Skipping invalid version tag: list +Skipping invalid version tag: localattn1 +Git cherry-pick commands to run: +git cherry-pick 03935d300d60110bb86edb49d2315089cfb19789 #2024-05-24 11:00:59+02:00 +git cherry-pick bdb9106f247fca48a71eb384be25dbbd29b065a8 #2024-05-24 19:02:55+02:00 +git cherry-pick 84c4b72ee99e8e65a8a5754a5f9d6265b45cf67e #2024-05-27 10:34:14+02:00 +git cherry-pick 936ab7bae5e040ec58994cb722dd587b9ab26581 #2024-05-28 11:56:05+02:00 +git cherry-pick 0bef4a273825d2cfc52ddfe62ba486ee61cc116f #2024-05-29 13:33:26+01:00 +``` +""" + +import json +import subprocess + +import transformers + + +LABEL = "for patch" # Replace with your label +REPO = "huggingface/transformers" # Optional if already in correct repo + + +def get_release_branch_name(): + """Derive branch name from transformers version.""" + major, minor, *_ = transformers.__version__.split(".") + major = int(major) + minor = int(minor) + + if minor == 0: + # Handle major version rollback, e.g., from 5.0 to 4.latest (if ever needed) + major -= 1 + # You'll need logic to determine the last minor of the previous major version + raise ValueError("Minor version is 0; need logic to find previous major version's last minor") + + return f"v{major}.{minor}-release" + + +def checkout_branch(branch): + """Checkout the target branch.""" + try: + subprocess.run(["git", "checkout", branch], check=True) + print(f"✅ Checked out branch: {branch}") + except subprocess.CalledProcessError: + print(f"❌ Failed to checkout branch: {branch}. Does it exist?") + exit(1) + + +def get_prs_by_label(label): + """Call gh CLI to get PRs with a specific label.""" + cmd = [ + "gh", + "pr", + "list", + "--label", + label, + "--state", + "all", + "--json", + "number,title,mergeCommit,url", + "--limit", + "100", + ] + result = subprocess.run(cmd, check=False, capture_output=True, text=True) + result.check_returncode() + prs = json.loads(result.stdout) + for pr in prs: + is_merged = pr.get("mergeCommit", {}) + if is_merged: + pr["oid"] = is_merged.get("oid") + return prs + + +def get_commit_timestamp(commit_sha): + """Get UNIX timestamp of a commit using git.""" + result = subprocess.run( + ["git", "show", "-s", "--format=%ct", commit_sha], check=False, capture_output=True, text=True + ) + result.check_returncode() + return int(result.stdout.strip()) + + +def cherry_pick_commit(sha): + """Cherry-pick a given commit SHA.""" + try: + subprocess.run(["git", "cherry-pick", sha], check=True) + print(f"✅ Cherry-picked commit {sha}") + except subprocess.CalledProcessError: + print(f"⚠️ Failed to cherry-pick {sha}. Manual intervention required.") + + +def commit_in_history(commit_sha, base_branch="HEAD"): + """Return True if commit is already part of base_branch history.""" + result = subprocess.run( + ["git", "merge-base", "--is-ancestor", commit_sha, base_branch], + check=False, + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) + return result.returncode == 0 + + +def main(verbose=False): + branch = get_release_branch_name() + checkout_branch(branch) + prs = get_prs_by_label(LABEL) + # Attach commit timestamps + for pr in prs: + sha = pr.get("oid") + if sha: + pr["timestamp"] = get_commit_timestamp(sha) + else: + print("\n" + "=" * 80) + print(f"⚠️ WARNING: PR #{pr['number']} ({sha}) is NOT in main!") + print("⚠️ A core maintainer must review this before cherry-picking.") + print("=" * 80 + "\n") + # Sort by commit timestamp (ascending) + prs = [pr for pr in prs if pr.get("timestamp") is not None] + prs.sort(key=lambda pr: pr["timestamp"]) + for pr in prs: + sha = pr.get("oid") + if sha: + if commit_in_history(sha): + if verbose: + print(f"🔁 PR #{pr['number']} ({pr['title']}) already in history. Skipping.") + else: + print(f"🚀 PR #{pr['number']} ({pr['title']}) not in history. Cherry-picking...") + cherry_pick_commit(sha) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/pr_slow_ci_models.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/pr_slow_ci_models.py new file mode 100644 index 0000000000000000000000000000000000000000..4f6e8015711528db55ba987d1c3e6f92957d1ffd --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/pr_slow_ci_models.py @@ -0,0 +1,172 @@ +# 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. + +""" +This script is used to get the models for which to run slow CI. + +A new model added in a pull request will be included, as well as models specified in a GitHub pull request's comment +with a prefix `run-slow`, `run_slow` or `run slow`. For example, the commit message `run_slow: bert, gpt2` will give +`bert` and `gpt2`. + +Usage: + +```bash +python utils/pr_slow_ci_models.py +``` +""" + +import argparse +import os.path +import re +import string +from pathlib import Path + +from git import Repo + + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() + + +def get_new_python_files_between_commits(base_commit: str, commits: list[str]) -> list[str]: + """ + Get the list of added python files between a base commit and one or several commits. + + Args: + repo (`git.Repo`): + A git repository (for instance the Transformers repo). + base_commit (`str`): + The commit reference of where to compare for the diff. This is the current commit, not the branching point! + commits (`List[str]`): + The list of commits with which to compare the repo at `base_commit` (so the branching point). + + Returns: + `List[str]`: The list of python files added between a base commit and one or several commits. + """ + code_diff = [] + for commit in commits: + for diff_obj in commit.diff(base_commit): + # We always add new python files + if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"): + code_diff.append(diff_obj.b_path) + + return code_diff + + +def get_new_python_files(diff_with_last_commit=False) -> list[str]: + """ + Return a list of python files that have been added between the current head and the main branch. + + Returns: + `List[str]`: The list of python files added. + """ + repo = Repo(PATH_TO_REPO) + + try: + # For the cases where the main branch exists locally + main = repo.refs.main + except AttributeError: + # On GitHub Actions runners, it doesn't have local main branch + main = repo.remotes.origin.refs.main + + if not diff_with_last_commit: + print(f"main is at {main.commit}") + print(f"Current head is at {repo.head.commit}") + + commits = repo.merge_base(main, repo.head) + for commit in commits: + print(f"Branching commit: {commit}") + else: + print(f"main is at {main.commit}") + commits = main.commit.parents + for commit in commits: + print(f"Parent commit: {commit}") + + return get_new_python_files_between_commits(repo.head.commit, commits) + + +def get_new_model(diff_with_last_commit=False): + new_files = get_new_python_files(diff_with_last_commit) + reg = re.compile(r"src/transformers/models/(.*)/modeling_.*\.py") + + new_model = "" + for x in new_files: + find_new_model = reg.findall(x) + if len(find_new_model) > 0: + new_model = find_new_model[0] + # It's unlikely we have 2 new modeling files in a pull request. + break + return new_model + + +def parse_message(message: str) -> str: + """ + Parses a GitHub pull request's comment to find the models specified in it to run slow CI. + + Args: + message (`str`): The body of a GitHub pull request's comment. + + Returns: + `str`: The substring in `message` after `run-slow`, run_slow` or run slow`. If no such prefix is found, the + empty string is returned. + """ + if message is None: + return "" + + message = message.strip().lower() + + # run-slow: model_1, model_2 + if not message.startswith(("run-slow", "run_slow", "run slow")): + return "" + message = message[len("run slow") :] + # remove leading `:` + while message.strip().startswith(":"): + message = message.strip()[1:] + + return message + + +def get_models(message: str): + models = parse_message(message) + return models.replace(",", " ").split() + + +def check_model_names(model_name: str): + allowed = string.ascii_letters + string.digits + "_" + return not (model_name.startswith("_") or model_name.endswith("_")) and all(c in allowed for c in model_name) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--message", type=str, default="", help="The content of a comment.") + parser.add_argument("--quantization", action="store_true", help="If we collect quantization tests") + args = parser.parse_args() + + new_model = get_new_model() + specified_models = get_models(args.message) + models = ([] if new_model == "" else [new_model]) + specified_models + # a guard for strange model names + models = [model for model in models if check_model_names(model)] + + # Add prefix + final_list = [] + for model in models: + if not args.quantization: + if os.path.isdir(f"tests/models/{model}"): + final_list.append(f"models/{model}") + elif os.path.isdir(f"tests/{model}") and model != "quantization": + final_list.append(model) + elif os.path.isdir(f"tests/quantization/{model}"): + final_list.append(f"quantization/{model}") + + print(sorted(set(final_list))) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/print_env.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/print_env.py new file mode 100644 index 0000000000000000000000000000000000000000..d693d7e83b6f1cf5bd9355412d2beb2631dadde2 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/print_env.py @@ -0,0 +1,85 @@ +#!/usr/bin/env python3 + +# coding=utf-8 +# Copyright 2020 The HuggingFace Inc. team. +# +# 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 script dumps information about the environment + +import os +import sys + +import transformers +from transformers import is_torch_hpu_available, is_torch_xpu_available + + +os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3" + +print("Python version:", sys.version) +print("transformers version:", transformers.__version__) + +try: + import torch + + print("Torch version:", torch.__version__) + accelerator = "NA" + if torch.cuda.is_available(): + accelerator = "CUDA" + elif is_torch_xpu_available(): + accelerator = "XPU" + elif is_torch_hpu_available(): + accelerator = "HPU" + + print("Torch accelerator:", accelerator) + + if accelerator == "CUDA": + print("Cuda version:", torch.version.cuda) + print("CuDNN version:", torch.backends.cudnn.version()) + print("Number of GPUs available:", torch.cuda.device_count()) + print("NCCL version:", torch.cuda.nccl.version()) + elif accelerator == "XPU": + print("SYCL version:", torch.version.xpu) + print("Number of XPUs available:", torch.xpu.device_count()) + elif accelerator == "HPU": + print("HPU version:", torch.__version__.split("+")[-1]) + print("Number of HPUs available:", torch.hpu.device_count()) +except ImportError: + print("Torch version:", None) + +try: + import deepspeed + + print("DeepSpeed version:", deepspeed.__version__) +except ImportError: + print("DeepSpeed version:", None) + +try: + import tensorflow as tf + + print("TensorFlow version:", tf.__version__) + print("TF GPUs available:", bool(tf.config.list_physical_devices("GPU"))) + print("Number of TF GPUs available:", len(tf.config.list_physical_devices("GPU"))) +except ImportError: + print("TensorFlow version:", None) + + +try: + import torchcodec + + versions = torchcodec._core.get_ffmpeg_library_versions() + print("FFmpeg version:", versions["ffmpeg_version"]) +except ImportError: + print("FFmpeg version:", None) +except (AttributeError, KeyError, RuntimeError): + print("Failed to get FFmpeg version") diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_bad_commit_report.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_bad_commit_report.py new file mode 100644 index 0000000000000000000000000000000000000000..432291faec235c56283b92bda26089ce3990a7ea --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_bad_commit_report.py @@ -0,0 +1,122 @@ +"""An internal script to process `new_failures_with_bad_commit.json` produced by `utils/check_bad_commit.py`. + +This is used by `.github/workflows/check_failed_model_tests.yml` to produce a slack report of the following form + +``` +<{url}|New failed tests> +{ + "GH_ydshieh": { + "vit": 1 + } +} +``` +""" + +import json +import os +from collections import Counter +from copy import deepcopy + +from get_previous_daily_ci import get_last_daily_ci_run +from huggingface_hub import HfApi + + +if __name__ == "__main__": + api = HfApi() + + job_name = os.environ.get("JOB_NAME") + + with open("new_failures_with_bad_commit.json") as fp: + data = json.load(fp) + + with open(f"ci_results_{job_name}/job_links.json") as fp: + job_links = json.load(fp) + + # TODO: extend + team_members = [ + "ydshieh", + "zucchini-nlp", + "ArthurZucker", + "gante", + "LysandreJik", + "molbap", + "qubvel", + "Rocketknight1", + "muellerzr", + "SunMarc", + ] + + # Counting the number of failures grouped by authors + new_data = {} + for model, model_result in data.items(): + for device, failed_tests in model_result.items(): + for failed_test in failed_tests: + author = failed_test["author"] + + if author not in team_members: + author = failed_test["merged_by"] + + if author not in new_data: + new_data[author] = Counter() + new_data[author].update([model]) + for author in new_data: + new_data[author] = dict(new_data[author]) + + # Group by author + new_data_full = {author: deepcopy(data) for author in new_data} + for author, _data in new_data_full.items(): + for model, model_result in _data.items(): + for device, failed_tests in model_result.items(): + # prepare job_link and add it to each entry of new failed test information. + # need to change from `single-gpu` to `single` and same for `multi-gpu` to match `job_link`. + key = model + if list(job_links.keys()) == [job_name]: + key = job_name + job_link = job_links[key][device.replace("-gpu", "")] + + failed_tests = [x for x in failed_tests if x["author"] == author or x["merged_by"] == author] + for x in failed_tests: + x.update({"job_link": job_link}) + model_result[device] = failed_tests + _data[model] = {k: v for k, v in model_result.items() if len(v) > 0} + new_data_full[author] = {k: v for k, v in _data.items() if len(v) > 0} + + # Upload to Hub and get the url + # if it is not a scheduled run, upload the reports to a subfolder under `report_repo_folder` + report_repo_subfolder = "" + if os.getenv("GITHUB_EVENT_NAME") != "schedule": + report_repo_subfolder = f"{os.getenv('GITHUB_RUN_NUMBER')}-{os.getenv('GITHUB_RUN_ID')}" + report_repo_subfolder = f"runs/{report_repo_subfolder}" + + workflow_run = get_last_daily_ci_run( + token=os.environ["ACCESS_REPO_INFO_TOKEN"], workflow_run_id=os.getenv("GITHUB_RUN_ID") + ) + workflow_run_created_time = workflow_run["created_at"] + + report_repo_folder = workflow_run_created_time.split("T")[0] + + if report_repo_subfolder: + report_repo_folder = f"{report_repo_folder}/{report_repo_subfolder}" + + report_repo_id = os.getenv("REPORT_REPO_ID") + + with open("new_failures_with_bad_commit_grouped_by_authors.json", "w") as fp: + json.dump(new_data_full, fp, ensure_ascii=False, indent=4) + commit_info = api.upload_file( + path_or_fileobj="new_failures_with_bad_commit_grouped_by_authors.json", + path_in_repo=f"{report_repo_folder}/ci_results_{job_name}/new_failures_with_bad_commit_grouped_by_authors.json", + repo_id=report_repo_id, + repo_type="dataset", + token=os.environ.get("TRANSFORMERS_CI_RESULTS_UPLOAD_TOKEN", None), + ) + url = f"https://huggingface.co/datasets/{report_repo_id}/raw/{commit_info.oid}/{report_repo_folder}/ci_results_{job_name}/new_failures_with_bad_commit_grouped_by_authors.json" + + # Add `GH_` prefix as keyword mention + output = {} + for author, item in new_data.items(): + author = f"GH_{author}" + output[author] = item + + report = f"<{url}|New failed tests>\\n\\n" + report += json.dumps(output, indent=4).replace('"', '\\"').replace("\n", "\\n") + print(report) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_circleci_workflow_test_reports.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_circleci_workflow_test_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..eb61f6d586e536130fef31a0f0764b27afec519f --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_circleci_workflow_test_reports.py @@ -0,0 +1,85 @@ +# 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. +import argparse +import json +import os + +import requests + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--workflow_id", type=str, required=True) + args = parser.parse_args() + workflow_id = args.workflow_id + + r = requests.get( + f"https://circleci.com/api/v2/workflow/{workflow_id}/job", + headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")}, + ) + jobs = r.json()["items"] + + os.makedirs("outputs", exist_ok=True) + + workflow_summary = {} + # for each job, download artifacts + for job in jobs: + project_slug = job["project_slug"] + if job["name"].startswith(("tests_", "examples_", "pipelines_")): + url = f"https://circleci.com/api/v2/project/{project_slug}/{job['job_number']}/artifacts" + r = requests.get(url, headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")}) + job_artifacts = r.json()["items"] + + os.makedirs(job["name"], exist_ok=True) + os.makedirs(f"outputs/{job['name']}", exist_ok=True) + + job_test_summaries = {} + for artifact in job_artifacts: + if artifact["path"].startswith("reports/") and artifact["path"].endswith("/summary_short.txt"): + node_index = artifact["node_index"] + url = artifact["url"] + r = requests.get(url, headers={"Circle-Token": os.environ.get("CIRCLE_TOKEN", "")}) + test_summary = r.text + job_test_summaries[node_index] = test_summary + + summary = {} + for node_index, node_test_summary in job_test_summaries.items(): + for line in node_test_summary.splitlines(): + if line.startswith("PASSED "): + test = line[len("PASSED ") :] + summary[test] = "passed" + elif line.startswith("FAILED "): + test = line[len("FAILED ") :].split()[0] + summary[test] = "failed" + # failed before passed + summary = dict(sorted(summary.items(), key=lambda x: (x[1], x[0]))) + workflow_summary[job["name"]] = summary + + # collected version + with open(f"outputs/{job['name']}/test_summary.json", "w") as fp: + json.dump(summary, fp, indent=4) + + new_workflow_summary = {} + for job_name, job_summary in workflow_summary.items(): + for test, status in job_summary.items(): + if test not in new_workflow_summary: + new_workflow_summary[test] = {} + new_workflow_summary[test][job_name] = status + + for test, result in new_workflow_summary.items(): + new_workflow_summary[test] = dict(sorted(result.items())) + new_workflow_summary = dict(sorted(new_workflow_summary.items())) + + with open("outputs/test_summary.json", "w") as fp: + json.dump(new_workflow_summary, fp, indent=4) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_test_artifacts.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_test_artifacts.py new file mode 100644 index 0000000000000000000000000000000000000000..e685a99095067b012fc8a036dd7555c6b0143271 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/process_test_artifacts.py @@ -0,0 +1,75 @@ +# coding=utf-8 +# Copyright 2024 The HuggingFace Inc. team. +# +# 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 helper computes the "ideal" number of nodes to use in circle CI. +For each job, we compute this parameter and pass it to the `generated_config.yaml`. +""" + +import json +import math +import os + + +MAX_PARALLEL_NODES = 8 # TODO create a mapping! +AVERAGE_TESTS_PER_NODES = 5 + + +def count_lines(filepath): + """Count the number of lines in a file.""" + try: + with open(filepath, "r") as f: + return len(f.read().split("\n")) + except FileNotFoundError: + return 0 + + +def compute_parallel_nodes(line_count, max_tests_per_node=10): + """Compute the number of parallel nodes required.""" + num_nodes = math.ceil(line_count / AVERAGE_TESTS_PER_NODES) + if line_count < 4: + return 1 + return min(MAX_PARALLEL_NODES, num_nodes) + + +def process_artifacts(input_file, output_file): + # Read the JSON data from the input file + with open(input_file, "r") as f: + data = json.load(f) + + # Process items and build the new JSON structure + transformed_data = {} + for item in data.get("items", []): + if "test_list" in item["path"]: + key = os.path.splitext(os.path.basename(item["path"]))[0] + transformed_data[key] = item["url"] + parallel_key = key.split("_test")[0] + "_parallelism" + file_path = os.path.join("test_preparation", f"{key}.txt") + line_count = count_lines(file_path) + transformed_data[parallel_key] = compute_parallel_nodes(line_count) + + # Remove the "generated_config" key if it exists + if "generated_config" in transformed_data: + del transformed_data["generated_config"] + + # Write the transformed data to the output file + with open(output_file, "w") as f: + json.dump(transformed_data, f, indent=2) + + +if __name__ == "__main__": + input_file = "test_preparation/artifacts.json" + output_file = "test_preparation/transformed_artifacts.json" + process_artifacts(input_file, output_file) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/release.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/release.py new file mode 100644 index 0000000000000000000000000000000000000000..d8fee77733e7cf885a4df9aa3ca439851ab210fe --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/release.py @@ -0,0 +1,218 @@ +# coding=utf-8 +# 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. +""" +Utility that prepares the repository for releases (or patches) by updating all versions in the relevant places. It +also performs some post-release cleanup, by updating the links in the main README to respective model doc pages (from +main to stable). + +To prepare for a release, use from the root of the repo on the release branch with: + +```bash +python release.py +``` + +or use `make pre-release`. + +To prepare for a patch release, use from the root of the repo on the release branch with: + +```bash +python release.py --patch +``` + +or use `make pre-patch`. + +To do the post-release cleanup, use from the root of the repo on the main branch with: + +```bash +python release.py --post_release +``` + +or use `make post-release`. +""" + +import argparse +import os +import re +from pathlib import Path + +import packaging.version + + +# All paths are defined with the intent that this script should be run from the root of the repo. +PATH_TO_EXAMPLES = "examples/" +PATH_TO_MODELS = "src/transformers/models" +# This maps a type of file to the pattern to look for when searching where the version is defined, as well as the +# template to follow when replacing it with the new version. +REPLACE_PATTERNS = { + "examples": (re.compile(r'^check_min_version\("[^"]+"\)\s*$', re.MULTILINE), 'check_min_version("VERSION")\n'), + "init": (re.compile(r'^__version__\s+=\s+"([^"]+)"\s*$', re.MULTILINE), '__version__ = "VERSION"\n'), + "setup": (re.compile(r'^(\s*)version\s*=\s*"[^"]+",', re.MULTILINE), r'\1version="VERSION",'), + "uv_script_release": ( + re.compile(r'^# "transformers(\[.+\])?.*$', re.MULTILINE), + r'# "transformers\g<1>==VERSION",', + ), + "uv_script_dev": ( + re.compile(r'^# "transformers(\[.+\])?.*$', re.MULTILINE), + r'# "transformers\g<1> @ git+https://github.com/huggingface/transformers.git",', + ), +} +# This maps a type of file to its path in Transformers +REPLACE_FILES = { + "init": "src/transformers/__init__.py", + "setup": "setup.py", +} +README_FILE = "README.md" +UV_SCRIPT_MARKER = "# /// script" + + +def update_version_in_file(fname: str, version: str, file_type: str): + """ + Update the version of Transformers in one file. + + Args: + fname (`str`): The path to the file where we want to update the version. + version (`str`): The new version to set in the file. + file_type (`str`): The type of the file (should be a key in `REPLACE_PATTERNS`). + """ + with open(fname, "r", encoding="utf-8", newline="\n") as f: + code = f.read() + re_pattern, replace = REPLACE_PATTERNS[file_type] + replace = replace.replace("VERSION", version) + code = re_pattern.sub(replace, code) + with open(fname, "w", encoding="utf-8", newline="\n") as f: + f.write(code) + + +def update_version_in_examples(version: str, patch: bool = False): + """ + Update the version in all examples files. + + Args: + version (`str`): The new version to set in the examples. + patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release. + """ + for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES): + # Removing some of the folders with non-actively maintained examples from the walk + if "legacy" in directories: + directories.remove("legacy") + for fname in fnames: + if fname.endswith(".py"): + if UV_SCRIPT_MARKER in Path(folder, fname).read_text(): + # Update the depdendencies in UV scripts + uv_script_file_type = "uv_script_dev" if ".dev" in version else "uv_script_release" + update_version_in_file(os.path.join(folder, fname), version, file_type=uv_script_file_type) + if not patch: + # We don't update the version in the examples for patch releases. + update_version_in_file(os.path.join(folder, fname), version, file_type="examples") + + +def global_version_update(version: str, patch: bool = False): + """ + Update the version in all needed files. + + Args: + version (`str`): The new version to set everywhere. + patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release. + """ + for pattern, fname in REPLACE_FILES.items(): + update_version_in_file(fname, version, pattern) + update_version_in_examples(version, patch=patch) + + +def remove_conversion_scripts(): + """ + Delete the scripts that convert models from older, unsupported formats. We don't want to include these + in release wheels because they often have to open insecure file types (pickle, Torch .bin models). This results in + vulnerability scanners flagging us and can cause compliance issues for users with strict security policies. + """ + model_dir = Path(PATH_TO_MODELS) + for conversion_script in list(model_dir.glob("**/convert*.py")): + conversion_script.unlink() + + +def get_version() -> packaging.version.Version: + """ + Reads the current version in the main __init__. + """ + with open(REPLACE_FILES["init"], "r") as f: + code = f.read() + default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0] + return packaging.version.parse(default_version) + + +def pre_release_work(patch: bool = False): + """ + Do all the necessary pre-release steps: + - figure out the next minor release version and ask confirmation + - update the version everywhere + - clean-up the model list in the main README + + Args: + patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release. + """ + # First let's get the default version: base version if we are in dev, bump minor otherwise. + default_version = get_version() + if patch and default_version.is_devrelease: + raise ValueError("Can't create a patch version from the dev branch, checkout a released version!") + if default_version.is_devrelease: + default_version = default_version.base_version + elif patch: + default_version = f"{default_version.major}.{default_version.minor}.{default_version.micro + 1}" + else: + default_version = f"{default_version.major}.{default_version.minor + 1}.0" + + # Now let's ask nicely if we have found the right version. + version = input(f"Which version are you releasing? [{default_version}]") + if len(version) == 0: + version = default_version + + print(f"Updating version to {version}.") + global_version_update(version, patch=patch) + print("Deleting conversion scripts.") + remove_conversion_scripts() + + +def post_release_work(): + """ + Do all the necessary post-release steps: + - figure out the next dev version and ask confirmation + - update the version everywhere + - clean-up the model list in the main README + """ + # First let's get the current version + current_version = get_version() + dev_version = f"{current_version.major}.{current_version.minor + 1}.0.dev0" + current_version = current_version.base_version + + # Check with the user we got that right. + version = input(f"Which version are we developing now? [{dev_version}]") + if len(version) == 0: + version = dev_version + + print(f"Updating version to {version}.") + global_version_update(version) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--post_release", action="store_true", help="Whether this is pre or post release.") + parser.add_argument("--patch", action="store_true", help="Whether or not this is a patch release.") + args = parser.parse_args() + if not args.post_release: + pre_release_work(patch=args.patch) + elif args.patch: + print("Nothing to do after a patch :-)") + else: + post_release_work() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/scan_skipped_tests.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/scan_skipped_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..20d794f733dc20ed3897359dc6175c0986155d18 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/scan_skipped_tests.py @@ -0,0 +1,199 @@ +# 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. + + +import argparse +import json +import re +from pathlib import Path + + +REPO_ROOT = Path().cwd() + +COMMON_TEST_FILES: list[tuple[Path, str]] = [ + (REPO_ROOT / "tests/test_modeling_common.py", "common"), + (REPO_ROOT / "tests/generation/test_utils.py", "GenerationMixin"), +] + +MODELS_DIR = REPO_ROOT / "tests/models" + + +def get_common_tests(file_paths_with_origin: list[tuple[Path, str]]) -> dict[str, str]: + """Extract all common test function names (e.g., 'test_forward').""" + tests_with_origin: dict[str, str] = {} + for file_path, origin_tag in file_paths_with_origin: + if not file_path.is_file(): + continue + content = file_path.read_text(encoding="utf-8") + for test_name in re.findall(r"^\s*def\s+(test_[A-Za-z0-9_]+)", content, re.MULTILINE): + tests_with_origin[test_name] = origin_tag + return tests_with_origin + + +def get_models_and_test_files(models_dir: Path) -> tuple[list[str], list[Path]]: + if not models_dir.is_dir(): + raise FileNotFoundError(f"Models directory not found at {models_dir}") + test_files: list[Path] = sorted(models_dir.rglob("test_modeling_*.py")) + model_names: list[str] = sorted({file_path.parent.name for file_path in test_files}) + return model_names, test_files + + +def _extract_reason_from_decorators(decorators_block: str) -> str: + """Extracts the reason string from a decorator block, if any.""" + reason_match = re.search(r'reason\s*=\s*["\'](.*?)["\']', decorators_block) + if reason_match: + return reason_match.group(1) + reason_match = re.search(r'\((?:.*?,\s*)?["\'](.*?)["\']\)', decorators_block) + if reason_match: + return reason_match.group(1) + return decorators_block.strip().split("\n")[-1].strip() + + +def extract_test_info(file_content: str) -> dict[str, tuple[str, str]]: + """ + Parse a test file once and return a mapping of test functions to their + status and skip reason, e.g. {'test_forward': ('SKIPPED', 'too slow')}. + """ + result: dict[str, tuple[str, str]] = {} + pattern = re.compile(r"((?:^\s*@.*?\n)*?)^\s*def\s+(test_[A-Za-z0-9_]+)\b", re.MULTILINE) + for decorators_block, test_name in pattern.findall(file_content): + if "skip" in decorators_block: + result[test_name] = ("SKIPPED", _extract_reason_from_decorators(decorators_block)) + else: + result[test_name] = ("RAN", "") + return result + + +def build_model_overrides(model_test_files: list[Path]) -> dict[str, dict[str, tuple[str, str]]]: + """Return *model_name → {test_name → (status, reason)}* mapping.""" + model_overrides: dict[str, dict[str, tuple[str, str]]] = {} + for file_path in model_test_files: + model_name = file_path.parent.name + file_content = file_path.read_text(encoding="utf-8") + model_overrides.setdefault(model_name, {}).update(extract_test_info(file_content)) + return model_overrides + + +def save_json(obj: dict, output_path: Path) -> None: + output_path.parent.mkdir(parents=True, exist_ok=True) + output_path.write_text(json.dumps(obj, indent=2), encoding="utf-8") + + +def summarize_single_test( + test_name: str, + model_names: list[str], + model_overrides: dict[str, dict[str, tuple[str, str]]], +) -> dict[str, object]: + """Print a concise terminal summary for *test_name* and return the raw data.""" + models_ran, models_skipped, reasons_for_skipping = [], [], [] + for model_name in model_names: + status, reason = model_overrides.get(model_name, {}).get(test_name, ("RAN", "")) + if status == "SKIPPED": + models_skipped.append(model_name) + reasons_for_skipping.append(f"{model_name}: {reason}") + else: + models_ran.append(model_name) + + total_models = len(model_names) + skipped_ratio = len(models_skipped) / total_models if total_models else 0.0 + + print(f"\n== {test_name} ==") + print(f"Ran : {len(models_ran)}/{total_models}") + print(f"Skipped : {len(models_skipped)}/{total_models} ({skipped_ratio:.1%})") + for reason_entry in reasons_for_skipping[:10]: + print(f" - {reason_entry}") + if len(reasons_for_skipping) > 10: + print(" - ...") + + return { + "models_ran": sorted(models_ran), + "models_skipped": sorted(models_skipped), + "skipped_proportion": round(skipped_ratio, 4), + "reasons_skipped": sorted(reasons_for_skipping), + } + + +def summarize_all_tests( + tests_with_origin: dict[str, str], + model_names: list[str], + model_overrides: dict[str, dict[str, tuple[str, str]]], +) -> dict[str, object]: + """Return aggregated data for every discovered common test.""" + results: dict[str, object] = {} + total_models = len(model_names) + test_names = list(tests_with_origin) + + print(f"📝 Aggregating {len(test_names)} tests...") + for index, test_fn in enumerate(test_names, 1): + print(f" ({index}/{len(test_names)}) {test_fn}", end="\r") + models_ran, models_skipped, reasons_for_skipping = [], [], [] + for model_name in model_names: + status, reason = model_overrides.get(model_name, {}).get(test_fn, ("RAN", "")) + if status == "SKIPPED": + models_skipped.append(model_name) + reasons_for_skipping.append(f"{model_name}: {reason}") + else: + models_ran.append(model_name) + + skipped_ratio = len(models_skipped) / total_models if total_models else 0.0 + results[test_fn] = { + "origin": tests_with_origin[test_fn], + "models_ran": sorted(models_ran), + "models_skipped": sorted(models_skipped), + "skipped_proportion": round(skipped_ratio, 4), + "reasons_skipped": sorted(reasons_for_skipping), + } + print("\n✅ Scan complete.") + return results + + +def main() -> None: + parser = argparse.ArgumentParser( + description="Scan model tests for overridden or skipped common or generat tests.", + ) + parser.add_argument( + "--output_dir", + default=".", + help="Directory for JSON output (default: %(default)s)", + ) + parser.add_argument( + "--test_method_name", + help="Scan only this test method (single‑test mode)", + ) + args = parser.parse_args() + + output_dir = Path(args.output_dir).expanduser() + test_method_name = args.test_method_name + + tests_with_origin = get_common_tests(COMMON_TEST_FILES) + if test_method_name: + tests_with_origin = {test_method_name: tests_with_origin.get(test_method_name, "unknown")} + + model_names, model_test_files = get_models_and_test_files(MODELS_DIR) + print(f"🔬 Parsing {len(model_test_files)} model test files once each...") + model_overrides = build_model_overrides(model_test_files) + + if test_method_name: + data = summarize_single_test(test_method_name, model_names, model_overrides) + json_path = output_dir / f"scan_{test_method_name}.json" + else: + data = summarize_all_tests(tests_with_origin, model_names, model_overrides) + json_path = output_dir / "all_tests_scan_result.json" + save_json(data, json_path) + print(f"\n📄 JSON saved to {json_path.resolve()}") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/set_cuda_devices_for_ci.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/set_cuda_devices_for_ci.py new file mode 100644 index 0000000000000000000000000000000000000000..da3638955ff3959fed7a2fe39f00c3608ff3d3fe --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/set_cuda_devices_for_ci.py @@ -0,0 +1,26 @@ +"""A simple script to set flexibly CUDA_VISIBLE_DEVICES in GitHub Actions CI workflow files.""" + +import argparse +import os + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--test_folder", + type=str, + default=None, + help="The test folder name of the model being tested. For example, `models/cohere`.", + ) + args = parser.parse_args() + + # `test_eager_matches_sdpa_generate` for `cohere` needs a lot of GPU memory! + # This depends on the runners. At this moment we are targeting our AWS CI runners. + if args.test_folder == "models/cohere": + cuda_visible_devices = "0,1,2,3" + elif "CUDA_VISIBLE_DEVICES" in os.environ: + cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES") + else: + cuda_visible_devices = "0" + + print(cuda_visible_devices) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/slow_documentation_tests.txt b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/slow_documentation_tests.txt new file mode 100644 index 0000000000000000000000000000000000000000..03ef646f04bc7262bec01891ca7763c61992dc2e --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/slow_documentation_tests.txt @@ -0,0 +1,15 @@ +docs/source/en/generation_strategies.md +docs/source/en/model_doc/code_llama.md +docs/source/en/model_doc/ctrl.md +docs/source/en/model_doc/kosmos-2.md +docs/source/en/model_doc/seamless_m4t.md +docs/source/en/model_doc/seamless_m4t_v2.md +docs/source/en/tasks/prompting.md +docs/source/ja/model_doc/code_llama.md +src/transformers/models/blip_2/modeling_blip_2.py +src/transformers/models/ctrl/modeling_ctrl.py +src/transformers/models/fuyu/modeling_fuyu.py +src/transformers/models/idefics2/modeling_idefics2.py +src/transformers/models/kosmos2/modeling_kosmos2.py +src/transformers/models/musicgen_melody/modeling_musicgen_melody.py +src/transformers/models/musicgen_melody/processing_musicgen_melody.py diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/sort_auto_mappings.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/sort_auto_mappings.py new file mode 100644 index 0000000000000000000000000000000000000000..42382b6dfec07ac3d012a23b4920a073a11b62a6 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/sort_auto_mappings.py @@ -0,0 +1,125 @@ +# coding=utf-8 +# Copyright 2022 The HuggingFace Inc. team. +# +# 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. +""" +Utility that sorts the names in the auto mappings defines in the auto modules in alphabetical order. + +Use from the root of the repo with: + +```bash +python utils/sort_auto_mappings.py +``` + +to auto-fix all the auto mappings (used in `make style`). + +To only check if the mappings are properly sorted (as used in `make quality`), do: + +```bash +python utils/sort_auto_mappings.py --check_only +``` +""" + +import argparse +import os +import re +from typing import Optional + + +# Path are set with the intent you should run this script from the root of the repo. +PATH_TO_AUTO_MODULE = "src/transformers/models/auto" + + +# re pattern that matches mapping introductions: +# SUPER_MODEL_MAPPING_NAMES = OrderedDict or SUPER_MODEL_MAPPING = OrderedDict +_re_intro_mapping = re.compile(r"[A-Z_]+_MAPPING(\s+|_[A-Z_]+\s+)=\s+OrderedDict") +# re pattern that matches identifiers in mappings +_re_identifier = re.compile(r'\s*\(\s*"(\S[^"]+)"') + + +def sort_auto_mapping(fname: str, overwrite: bool = False) -> Optional[bool]: + """ + Sort all auto mappings in a file. + + Args: + fname (`str`): The name of the file where we want to sort auto-mappings. + overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file. + + Returns: + `Optional[bool]`: Returns `None` if `overwrite=True`. Otherwise returns `True` if the file has an auto-mapping + improperly sorted, `False` if the file is okay. + """ + with open(fname, "r", encoding="utf-8") as f: + content = f.read() + + lines = content.split("\n") + new_lines = [] + line_idx = 0 + while line_idx < len(lines): + if _re_intro_mapping.search(lines[line_idx]) is not None: + # Start of a new mapping! + indent = len(re.search(r"^(\s*)\S", lines[line_idx]).groups()[0]) + 8 + while not lines[line_idx].startswith(" " * indent + "("): + new_lines.append(lines[line_idx]) + line_idx += 1 + + blocks = [] + while lines[line_idx].strip() != "]": + # Blocks either fit in one line or not + if lines[line_idx].strip() == "(": + start_idx = line_idx + while not lines[line_idx].startswith(" " * indent + ")"): + line_idx += 1 + blocks.append("\n".join(lines[start_idx : line_idx + 1])) + else: + blocks.append(lines[line_idx]) + line_idx += 1 + + # Sort blocks by their identifiers + blocks = sorted(blocks, key=lambda x: _re_identifier.search(x).groups()[0]) + new_lines += blocks + else: + new_lines.append(lines[line_idx]) + line_idx += 1 + + if overwrite: + with open(fname, "w", encoding="utf-8") as f: + f.write("\n".join(new_lines)) + else: + return "\n".join(new_lines) != content + + +def sort_all_auto_mappings(overwrite: bool = False): + """ + Sort all auto mappings in the library. + + Args: + overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file. + """ + fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE) if f.endswith(".py")] + diffs = [sort_auto_mapping(fname, overwrite=overwrite) for fname in fnames] + + if not overwrite and any(diffs): + failures = [f for f, d in zip(fnames, diffs) if d] + raise ValueError( + f"The following files have auto mappings that need sorting: {', '.join(failures)}. Run `make style` to fix" + " this." + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--check_only", action="store_true", help="Whether to only check or fix style.") + args = parser.parse_args() + + sort_all_auto_mappings(not args.check_only) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/split_doctest_jobs.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/split_doctest_jobs.py new file mode 100644 index 0000000000000000000000000000000000000000..fd887394dea30f67389e68a8295ec09d8a7b483d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/split_doctest_jobs.py @@ -0,0 +1,98 @@ +# 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. + +""" +This script is used to get the files against which we will run doc testing. +This uses `tests_fetcher.get_all_doctest_files` then groups the test files by their directory paths. + +The files in `docs/source/en/model_doc` or `docs/source/en/tasks` are **NOT** grouped together with other files in the +same directory: the objective is to run doctest against them in independent GitHub Actions jobs. + +Assume we are under `transformers` root directory: +To get a map (dictionary) between directory (or file) paths and the corresponding files +```bash +python utils/split_doctest_jobs.py +``` +or to get a list of lists of directory (or file) paths +```bash +python utils/split_doctest_jobs.py --only_return_keys --num_splits 4 +``` +(this is used to allow GitHub Actions to generate more than 256 jobs using matrix) +""" + +import argparse +from collections import defaultdict +from pathlib import Path + +from tests_fetcher import get_all_doctest_files + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--only_return_keys", + action="store_true", + help="if to only return the keys (which is a list of list of files' directory or file paths).", + ) + parser.add_argument( + "--num_splits", + type=int, + default=1, + help="the number of splits into which the (flat) list of directory/file paths will be split. This has effect only if `only_return_keys` is `True`.", + ) + args = parser.parse_args() + + all_doctest_files = get_all_doctest_files() + + raw_test_collection_map = defaultdict(list) + + for file in all_doctest_files: + file_dir = "/".join(Path(file).parents[0].parts) + + # not to run files in `src/` for now as it is completely broken at this moment. See issues/39159 and + # https://github.com/huggingface/transformers/actions/runs/15988670157 + # TODO (ydshieh): fix the error, ideally before 2025/09 + if file_dir.startswith("src/"): + continue + + raw_test_collection_map[file_dir].append(file) + + refined_test_collection_map = {} + for file_dir in raw_test_collection_map: + if file_dir in ["docs/source/en/model_doc", "docs/source/en/tasks"]: + for file in raw_test_collection_map[file_dir]: + refined_test_collection_map[file] = file + else: + refined_test_collection_map[file_dir] = " ".join(sorted(raw_test_collection_map[file_dir])) + + sorted_file_dirs = sorted(refined_test_collection_map.keys()) + + test_collection_map = {} + for file_dir in sorted_file_dirs: + test_collection_map[file_dir] = refined_test_collection_map[file_dir] + + num_jobs = len(test_collection_map) + num_jobs_per_splits = num_jobs // args.num_splits + + file_directory_splits = [] + end = 0 + for idx in range(args.num_splits): + start = end + end = start + num_jobs_per_splits + (1 if idx < num_jobs % args.num_splits else 0) + file_directory_splits.append(sorted_file_dirs[start:end]) + + if args.only_return_keys: + print(file_directory_splits) + else: + print(dict(test_collection_map)) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/split_model_tests.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/split_model_tests.py new file mode 100644 index 0000000000000000000000000000000000000000..3539a2fb3178aa71f03e016926bbef3361b10296 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/split_model_tests.py @@ -0,0 +1,66 @@ +# 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. + +""" +This script is used to get the list of folders under `tests/models` and split the list into `NUM_SLICES` splits. +The main use case is a GitHub Actions workflow file calling this script to get the (nested) list of folders allowing it +to split the list of jobs to run into multiple slices each containing a smaller number of jobs. This way, we can bypass +the maximum of 256 jobs in a matrix. + +See the `setup` and `run_models_gpu` jobs defined in the workflow file `.github/workflows/self-scheduled.yml` for more +details. + +Usage: + +This script is required to be run under `tests` folder of `transformers` root directory. + +Assume we are under `transformers` root directory: +```bash +cd tests +python ../utils/split_model_tests.py --num_splits 64 +``` +""" + +import argparse +import os + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--num_splits", + type=int, + default=1, + help="the number of splits into which the (flat) list of folders will be split.", + ) + args = parser.parse_args() + + tests = os.getcwd() + model_tests = os.listdir(os.path.join(tests, "models")) + d1 = sorted(filter(os.path.isdir, os.listdir(tests))) + d2 = sorted(filter(os.path.isdir, [f"models/{x}" for x in model_tests])) + d1.remove("models") + d = d2 + d1 + + num_jobs = len(d) + num_jobs_per_splits = num_jobs // args.num_splits + + model_splits = [] + end = 0 + for idx in range(args.num_splits): + start = end + end = start + num_jobs_per_splits + (1 if idx < num_jobs % args.num_splits else 0) + model_splits.append(d[start:end]) + + print(model_splits) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/__init__.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_configuration.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_configuration.py new file mode 100644 index 0000000000000000000000000000000000000000..4bb0fe6a15dc15202318c099d32ff4a35b846930 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_configuration.py @@ -0,0 +1,9 @@ +from transformers import PretrainedConfig + + +class CustomConfig(PretrainedConfig): + model_type = "custom" + + def __init__(self, attribute=1, **kwargs): + self.attribute = attribute + super().__init__(**kwargs) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_feature_extraction.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_feature_extraction.py new file mode 100644 index 0000000000000000000000000000000000000000..de367032d8fe8e73fc1b5f3d281eb21506af7b66 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_feature_extraction.py @@ -0,0 +1,5 @@ +from transformers import Wav2Vec2FeatureExtractor + + +class CustomFeatureExtractor(Wav2Vec2FeatureExtractor): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_image_processing.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_image_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..e4984854adc600678c12c156bac7264c481952e0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_image_processing.py @@ -0,0 +1,5 @@ +from transformers import CLIPImageProcessor + + +class CustomImageProcessor(CLIPImageProcessor): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_modeling.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..fafa7bff253d8e686a459f64294c3eb070fae792 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_modeling.py @@ -0,0 +1,19 @@ +import torch + +from transformers import PreTrainedModel + +from .custom_configuration import CustomConfig + + +class CustomModel(PreTrainedModel): + config_class = CustomConfig + + def __init__(self, config): + super().__init__(config) + self.linear = torch.nn.Linear(config.hidden_size, config.hidden_size) + + def forward(self, x): + return self.linear(x) + + def _init_weights(self, module): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_pipeline.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_pipeline.py new file mode 100644 index 0000000000000000000000000000000000000000..4c7928b1ccd145fb8ea51c32554dc0b19567ce0c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_pipeline.py @@ -0,0 +1,33 @@ +import numpy as np + +from transformers import Pipeline + + +def softmax(outputs): + maxes = np.max(outputs, axis=-1, keepdims=True) + shifted_exp = np.exp(outputs - maxes) + return shifted_exp / shifted_exp.sum(axis=-1, keepdims=True) + + +class PairClassificationPipeline(Pipeline): + def _sanitize_parameters(self, **kwargs): + preprocess_kwargs = {} + if "second_text" in kwargs: + preprocess_kwargs["second_text"] = kwargs["second_text"] + return preprocess_kwargs, {}, {} + + def preprocess(self, text, second_text=None): + return self.tokenizer(text, text_pair=second_text, return_tensors=self.framework) + + def _forward(self, model_inputs): + return self.model(**model_inputs) + + def postprocess(self, model_outputs): + logits = model_outputs.logits[0].numpy() + probabilities = softmax(logits) + + best_class = np.argmax(probabilities) + label = self.model.config.id2label[best_class] + score = probabilities[best_class].item() + logits = logits.tolist() + return {"label": label, "score": score, "logits": logits} diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_processing.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..196fc511b65b3bd589a5456a965b630f2c8be91b --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_processing.py @@ -0,0 +1,6 @@ +from transformers import ProcessorMixin + + +class CustomProcessor(ProcessorMixin): + feature_extractor_class = "AutoFeatureExtractor" + tokenizer_class = "AutoTokenizer" diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_tokenization.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_tokenization.py new file mode 100644 index 0000000000000000000000000000000000000000..d67b1373041e7c8b6682300cf507ffbaa0143211 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_tokenization.py @@ -0,0 +1,5 @@ +from transformers import BertTokenizer + + +class CustomTokenizer(BertTokenizer): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_tokenization_fast.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_tokenization_fast.py new file mode 100644 index 0000000000000000000000000000000000000000..ace94fdd1a5d1a726c3840db2b66e4f0a053e05c --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_tokenization_fast.py @@ -0,0 +1,8 @@ +from transformers import BertTokenizerFast + +from .custom_tokenization import CustomTokenizer + + +class CustomTokenizerFast(BertTokenizerFast): + slow_tokenizer_class = CustomTokenizer + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_video_processing.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_video_processing.py new file mode 100644 index 0000000000000000000000000000000000000000..5cdc7880df44b59dc25bdc3d84ea8a7dcc3fd3f3 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/test_module/custom_video_processing.py @@ -0,0 +1,5 @@ +from transformers import LlavaOnevisionVideoProcessor + + +class CustomVideoProcessor(LlavaOnevisionVideoProcessor): + pass diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/tests_fetcher.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/tests_fetcher.py new file mode 100644 index 0000000000000000000000000000000000000000..7b8d98405ce9bd7ca59a28fa0359ddbe29cd34b0 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/tests_fetcher.py @@ -0,0 +1,1229 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# 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. + +""" +Welcome to tests_fetcher V2. + +This util is designed to fetch tests to run on a PR so that only the tests impacted by the modifications are run, and +when too many models are being impacted, only run the tests of a subset of core models. It works like this. + +Stage 1: Identify the modified files. For jobs that run on the main branch, it's just the diff with the last commit. +On a PR, this takes all the files from the branching point to the current commit (so all modifications in a PR, not +just the last commit) but excludes modifications that are on docstrings or comments only. + +Stage 2: Extract the tests to run. This is done by looking at the imports in each module and test file: if module A +imports module B, then changing module B impacts module A, so the tests using module A should be run. We thus get the +dependencies of each model and then recursively builds the 'reverse' map of dependencies to get all modules and tests +impacted by a given file. We then only keep the tests (and only the core models tests if there are too many modules). + +Caveats: + - This module only filters tests by files (not individual tests) so it's better to have tests for different things + in different files. + - This module assumes inits are just importing things, not really building objects, so it's better to structure + them this way and move objects building in separate submodules. + +Usage: + +Base use to fetch the tests in a pull request + +```bash +python utils/tests_fetcher.py +``` + +Base use to fetch the tests on a the main branch (with diff from the last commit): + +```bash +python utils/tests_fetcher.py --diff_with_last_commit +``` +""" + +import argparse +import collections +import glob +import json +import os +import re +from contextlib import contextmanager +from pathlib import Path +from typing import Optional, Union + +from git import Repo + + +PATH_TO_REPO = Path(__file__).parent.parent.resolve() +PATH_TO_EXAMPLES = PATH_TO_REPO / "examples" +PATH_TO_TRANFORMERS = PATH_TO_REPO / "src/transformers" +PATH_TO_TESTS = PATH_TO_REPO / "tests" + +# The value is just a heuristic to determine if we `guess` all models are impacted. +# This variable has effect only if `filter_models=False`. +NUM_MODELS_TO_TRIGGER_FULL_CI = 30 + +# List here the models to always test. +IMPORTANT_MODELS = [ + "auto", + "bert", + "gpt2", + "t5", + "modernbert", + "vit,clip", + "detr", + "table_transformer", + "got_ocr2", + "whisper", + "wav2vec2", + "qwen2_audio", + "speech_t5", + "csm", + "llama", + "gemma3", + "qwen2", + "mistral3", + "qwen2_5_vl", + "llava", + "smolvlm", + "internvl", + "gemma3n", + "gpt_oss", + "qwen2_5_omni", +] + + +@contextmanager +def checkout_commit(repo: Repo, commit_id: str): + """ + Context manager that checks out a given commit when entered, but gets back to the reference it was at on exit. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + commit_id (`str`): The commit reference to checkout inside the context manager. + """ + current_head = repo.head.commit if repo.head.is_detached else repo.head.ref + + try: + repo.git.checkout(commit_id) + yield + + finally: + repo.git.checkout(current_head) + + +def clean_code(content: str) -> str: + """ + Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern + comments or docstings). + + Args: + content (`str`): The code to clean + + Returns: + `str`: The cleaned code. + """ + # We need to deactivate autoformatting here to write escaped triple quotes (we cannot use real triple quotes or + # this would mess up the result if this function applied to this particular file). + # fmt: off + # Remove docstrings by splitting on triple " then triple ': + splits = content.split('\"\"\"') + content = "".join(splits[::2]) + splits = content.split("\'\'\'") + # fmt: on + content = "".join(splits[::2]) + + # Remove empty lines and comments + lines_to_keep = [] + for line in content.split("\n"): + # remove anything that is after a # sign. + line = re.sub("#.*$", "", line) + # remove white lines + if len(line) != 0 and not line.isspace(): + lines_to_keep.append(line) + return "\n".join(lines_to_keep) + + +def keep_doc_examples_only(content: str) -> str: + """ + Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc + tests or not). + + Args: + content (`str`): The code to clean + + Returns: + `str`: The cleaned code. + """ + # Keep doc examples only by splitting on triple "`" + splits = content.split("```") + # Add leading and trailing "```" so the navigation is easier when compared to the original input `content` + content = "```" + "```".join(splits[1::2]) + "```" + + # Remove empty lines and comments + lines_to_keep = [] + for line in content.split("\n"): + # remove anything that is after a # sign. + line = re.sub("#.*$", "", line) + # remove white lines + if len(line) != 0 and not line.isspace(): + lines_to_keep.append(line) + return "\n".join(lines_to_keep) + + +def get_all_tests() -> list[str]: + """ + Walks the `tests` folder to return a list of files/subfolders. This is used to split the tests to run when using + parallelism. The split is: + + - folders under `tests`: (`tokenization`, `pipelines`, etc) except the subfolder `models` is excluded. + - folders under `tests/models`: `bert`, `gpt2`, etc. + - test files under `tests`: `test_modeling_common.py`, `test_tokenization_common.py`, etc. + """ + + # test folders/files directly under `tests` folder + tests = os.listdir(PATH_TO_TESTS) + tests = [f"tests/{f}" for f in tests if "__pycache__" not in f] + tests = sorted([f for f in tests if (PATH_TO_REPO / f).is_dir() or f.startswith("tests/test_")]) + + # model specific test folders + model_test_folders = os.listdir(PATH_TO_TESTS / "models") + model_test_folders = [f"tests/models/{f}" for f in model_test_folders if "__pycache__" not in f] + model_test_folders = sorted([f for f in model_test_folders if (PATH_TO_REPO / f).is_dir()]) + + tests.remove("tests/models") + # Sagemaker tests are not meant to be run on the CI. + if "tests/sagemaker" in tests: + tests.remove("tests/sagemaker") + tests = model_test_folders + tests + + return tests + + +def diff_is_docstring_only(repo: Repo, branching_point: str, filename: str) -> bool: + """ + Check if the diff is only in docstrings (or comments and whitespace) in a filename. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + branching_point (`str`): The commit reference of where to compare for the diff. + filename (`str`): The filename where we want to know if the diff isonly in docstrings/comments. + + Returns: + `bool`: Whether the diff is docstring/comments only or not. + """ + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_point): + with open(folder / filename, "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / filename, "r", encoding="utf-8") as f: + new_content = f.read() + + old_content_clean = clean_code(old_content) + new_content_clean = clean_code(new_content) + + return old_content_clean == new_content_clean + + +def diff_contains_doc_examples(repo: Repo, branching_point: str, filename: str) -> bool: + """ + Check if the diff is only in code examples of the doc in a filename. + + Args: + repo (`git.Repo`): A git repository (for instance the Transformers repo). + branching_point (`str`): The commit reference of where to compare for the diff. + filename (`str`): The filename where we want to know if the diff is only in codes examples. + + Returns: + `bool`: Whether the diff is only in code examples of the doc or not. + """ + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_point): + with open(folder / filename, "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / filename, "r", encoding="utf-8") as f: + new_content = f.read() + + old_content_clean = keep_doc_examples_only(old_content) + new_content_clean = keep_doc_examples_only(new_content) + + return old_content_clean != new_content_clean + + +def get_impacted_files_from_tiny_model_summary(diff_with_last_commit: bool = False) -> list[str]: + """ + Return a list of python modeling files that are impacted by the changes of `tiny_model_summary.json` in between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python modeling files that are impacted by the changes of `tiny_model_summary.json`. + """ + repo = Repo(PATH_TO_REPO) + + folder = Path(repo.working_dir) + + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + commits = repo.merge_base(repo.refs.main, repo.head) + for commit in commits: + print(f"Branching commit: {commit}") + else: + print(f"main is at {repo.head.commit}") + commits = repo.head.commit.parents + for commit in commits: + print(f"Parent commit: {commit}") + + if not os.path.isfile(folder / "tests/utils/tiny_model_summary.json"): + return [] + + files = set() + for commit in commits: + with checkout_commit(repo, commit): + with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f: + old_content = f.read() + + with open(folder / "tests/utils/tiny_model_summary.json", "r", encoding="utf-8") as f: + new_content = f.read() + + # get the content as json object + old_content = json.loads(old_content) + new_content = json.loads(new_content) + + old_keys = set(old_content.keys()) + new_keys = set(new_content.keys()) + + # get the difference + keys_with_diff = old_keys.symmetric_difference(new_keys) + common_keys = old_keys.intersection(new_keys) + # if both have the same key, check its content + for key in common_keys: + if old_content[key] != new_content[key]: + keys_with_diff.add(key) + + # get the model classes + impacted_model_classes = [] + for key in keys_with_diff: + if key in new_keys: + impacted_model_classes.extend(new_content[key]["model_classes"]) + + # Add imports via `define_import_structure` after the #35167 as we remove explicit import in `__init__.py` + from transformers.utils.import_utils import define_import_structure + + reversed_structure = {} + new_imported_modules_from_import_structure = define_import_structure("src/transformers/__init__.py") + for mapping in new_imported_modules_from_import_structure.values(): + for _module, _imports in mapping.items(): + for _import in _imports: + reversed_structure[_import] = _module + + # Get the corresponding modeling file path + for model_class in impacted_model_classes: + module = reversed_structure[model_class] + framework = "" + if model_class.startswith("TF"): + framework = "tf" + elif model_class.startswith("Flax"): + framework = "flax" + fn = ( + f"modeling_{module.split('.')[-1]}.py" + if framework == "" + else f"modeling_{framework}_{module.split('.')[-1]}.py" + ) + files.add(f"src.transformers.{module}.{fn}".replace(".", os.path.sep).replace(f"{os.path.sep}py", ".py")) + + return sorted(files) + + +def get_diff(repo: Repo, base_commit: str, commits: list[str]) -> list[str]: + """ + Get the diff between a base commit and one or several commits. + + Args: + repo (`git.Repo`): + A git repository (for instance the Transformers repo). + base_commit (`str`): + The commit reference of where to compare for the diff. This is the current commit, not the branching point! + commits (`List[str]`): + The list of commits with which to compare the repo at `base_commit` (so the branching point). + + Returns: + `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files + modified are returned if the diff in the file is not only in docstrings or comments, see + `diff_is_docstring_only`). + """ + print("\n### DIFF ###\n") + code_diff = [] + for commit in commits: + for diff_obj in commit.diff(base_commit): + # We always add new python files + if diff_obj.change_type == "A" and diff_obj.b_path.endswith(".py"): + code_diff.append(diff_obj.b_path) + # We check that deleted python files won't break corresponding tests. + elif diff_obj.change_type == "D" and diff_obj.a_path.endswith(".py"): + code_diff.append(diff_obj.a_path) + # Now for modified files + elif diff_obj.change_type in ["M", "R"] and diff_obj.b_path.endswith(".py"): + # In case of renames, we'll look at the tests using both the old and new name. + if diff_obj.a_path != diff_obj.b_path: + code_diff.extend([diff_obj.a_path, diff_obj.b_path]) + else: + # Otherwise, we check modifications are in code and not docstrings. + if diff_is_docstring_only(repo, commit, diff_obj.b_path): + print(f"Ignoring diff in {diff_obj.b_path} as it only concerns docstrings or comments.") + else: + code_diff.append(diff_obj.a_path) + + return code_diff + + +def get_modified_python_files(diff_with_last_commit: bool = False) -> list[str]: + """ + Return a list of python files that have been modified between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python files with a diff (files added, renamed or deleted are always returned, files + modified are returned if the diff in the file is not only in docstrings or comments, see + `diff_is_docstring_only`). + """ + repo = Repo(PATH_TO_REPO) + + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + branching_commits = repo.merge_base(repo.refs.main, repo.head) + for commit in branching_commits: + print(f"Branching commit: {commit}") + return get_diff(repo, repo.head.commit, branching_commits) + else: + print(f"main is at {repo.head.commit}") + parent_commits = repo.head.commit.parents + for commit in parent_commits: + print(f"Parent commit: {commit}") + return get_diff(repo, repo.head.commit, parent_commits) + + +def get_diff_for_doctesting(repo: Repo, base_commit: str, commits: list[str]) -> list[str]: + """ + Get the diff in doc examples between a base commit and one or several commits. + + Args: + repo (`git.Repo`): + A git repository (for instance the Transformers repo). + base_commit (`str`): + The commit reference of where to compare for the diff. This is the current commit, not the branching point! + commits (`List[str]`): + The list of commits with which to compare the repo at `base_commit` (so the branching point). + + Returns: + `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files + modified are returned if the diff in the file is only in doctest examples). + """ + print("\n### DIFF ###\n") + code_diff = [] + for commit in commits: + for diff_obj in commit.diff(base_commit): + # We only consider Python files and doc files. + if not diff_obj.b_path.endswith(".py") and not diff_obj.b_path.endswith(".md"): + continue + # We always add new python/md files + if diff_obj.change_type in ["A"]: + code_diff.append(diff_obj.b_path) + # Now for modified files + elif diff_obj.change_type in ["M", "R"]: + # In case of renames, we'll look at the tests using both the old and new name. + if diff_obj.a_path != diff_obj.b_path: + code_diff.extend([diff_obj.a_path, diff_obj.b_path]) + else: + # Otherwise, we check modifications contain some doc example(s). + if diff_contains_doc_examples(repo, commit, diff_obj.b_path): + code_diff.append(diff_obj.a_path) + else: + print(f"Ignoring diff in {diff_obj.b_path} as it doesn't contain any doc example.") + + return code_diff + + +def get_all_doctest_files() -> list[str]: + """ + Return the complete list of python and Markdown files on which we run doctest. + + At this moment, we restrict this to only take files from `src/` or `docs/source/en/` that are not in `utils/not_doctested.txt`. + + Returns: + `List[str]`: The complete list of Python and Markdown files on which we run doctest. + """ + py_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.py")] + md_files = [str(x.relative_to(PATH_TO_REPO)) for x in PATH_TO_REPO.glob("**/*.md")] + + test_files_to_run = py_files + md_files + # change to use "/" as path separator + test_files_to_run = ["/".join(Path(x).parts) for x in test_files_to_run] + # don't run doctest for files in `src/transformers/models/deprecated` + test_files_to_run = [x for x in test_files_to_run if "models/deprecated" not in x] + + # only include files in `src` or `docs/source/en/` + test_files_to_run = [x for x in test_files_to_run if x.startswith(("src/", "docs/source/en/"))] + # not include init files + test_files_to_run = [x for x in test_files_to_run if not x.endswith(("__init__.py",))] + + # These are files not doctested yet. + with open("utils/not_doctested.txt") as fp: + not_doctested = {x.split(" ")[0] for x in fp.read().strip().split("\n")} + + # So far we don't have 100% coverage for doctest. This line will be removed once we achieve 100%. + test_files_to_run = [x for x in test_files_to_run if x not in not_doctested] + + return sorted(test_files_to_run) + + +def get_new_doctest_files(repo, base_commit, branching_commit) -> list[str]: + """ + Get the list of files that were removed from "utils/not_doctested.txt", between `base_commit` and + `branching_commit`. + + Returns: + `List[str]`: List of files that were removed from "utils/not_doctested.txt". + """ + for diff_obj in branching_commit.diff(base_commit): + # Ignores all but the "utils/not_doctested.txt" file. + if diff_obj.a_path != "utils/not_doctested.txt": + continue + # Loads the two versions + folder = Path(repo.working_dir) + with checkout_commit(repo, branching_commit): + with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f: + old_content = f.read() + with open(folder / "utils/not_doctested.txt", "r", encoding="utf-8") as f: + new_content = f.read() + # Compute the removed lines and return them + removed_content = {x.split(" ")[0] for x in old_content.split("\n")} - { + x.split(" ")[0] for x in new_content.split("\n") + } + return sorted(removed_content) + return [] + + +def get_doctest_files(diff_with_last_commit: bool = False) -> list[str]: + """ + Return a list of python and Markdown files where doc example have been modified between: + + - the current head and the main branch if `diff_with_last_commit=False` (default) + - the current head and its parent commit otherwise. + + Returns: + `List[str]`: The list of Python and Markdown files with a diff (files added or renamed are always returned, files + modified are returned if the diff in the file is only in doctest examples). + """ + repo = Repo(PATH_TO_REPO) + + test_files_to_run = [] # noqa + if not diff_with_last_commit: + print(f"main is at {repo.refs.main.commit}") + print(f"Current head is at {repo.head.commit}") + + branching_commits = repo.merge_base(repo.refs.main, repo.head) + for commit in branching_commits: + print(f"Branching commit: {commit}") + test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, branching_commits) + else: + print(f"main is at {repo.head.commit}") + parent_commits = repo.head.commit.parents + for commit in parent_commits: + print(f"Parent commit: {commit}") + test_files_to_run = get_diff_for_doctesting(repo, repo.head.commit, parent_commits) + + all_test_files_to_run = get_all_doctest_files() + + # Add to the test files to run any removed entry from "utils/not_doctested.txt". + new_test_files = get_new_doctest_files(repo, repo.head.commit, repo.refs.main.commit) + test_files_to_run = list(set(test_files_to_run + new_test_files)) + + # Do not run slow doctest tests on CircleCI + with open("utils/slow_documentation_tests.txt") as fp: + slow_documentation_tests = set(fp.read().strip().split("\n")) + test_files_to_run = [ + x for x in test_files_to_run if x in all_test_files_to_run and x not in slow_documentation_tests + ] + + # Make sure we did not end up with a test file that was removed + test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()] + + return sorted(test_files_to_run) + + +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+(\.+\S+)\s+import\s+([^\n]+) -> Line only contains from .xxx import yyy and we catch .xxx and yyy +# (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every +# other import. +_re_single_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+([^\n]+)(?=\n)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\) -> Line continues with from .xxx import (yyy) and we catch .xxx and yyy +# yyy will take multiple lines otherwise there wouldn't be parenthesis. +_re_multi_line_relative_imports = re.compile(r"(?:^|\n)\s*from\s+(\.+\S+)\s+import\s+\(([^\)]+)\)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+transformers(\S*)\s+import\s+([^\n]+) -> Line only contains from transformers.xxx import yyy and we catch +# .xxx and yyy +# (?=\n) -> Look-ahead to a new line. We can't just put \n here or using find_all on this re will only catch every +# other import. +_re_single_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+([^\n]+)(?=\n)") +# (:?^|\n) -> Non-catching group for the beginning of the doc or a new line. +# \s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\) -> Line continues with from transformers.xxx import (yyy) and we +# catch .xxx and yyy. yyy will take multiple lines otherwise there wouldn't be parenthesis. +_re_multi_line_direct_imports = re.compile(r"(?:^|\n)\s*from\s+transformers(\S*)\s+import\s+\(([^\)]+)\)") + + +def extract_imports(module_fname: str, cache: Optional[dict[str, list[str]]] = None) -> list[str]: + """ + Get the imports a given module makes. + + Args: + module_fname (`str`): + The name of the file of the module where we want to look at the imports (given relative to the root of + the repo). + cache (Dictionary `str` to `List[str]`, *optional*): + To speed up this function if it was previously called on `module_fname`, the cache of all previously + computed results. + + Returns: + `List[str]`: The list of module filenames imported in the input `module_fname` (a submodule we import from that + is a subfolder will give its init file). + """ + if cache is not None and module_fname in cache: + return cache[module_fname] + + with open(PATH_TO_REPO / module_fname, "r", encoding="utf-8") as f: + content = f.read() + + # Filter out all docstrings to not get imports in code examples. As before we need to deactivate formatting to + # keep this as escaped quotes and avoid this function failing on this file. + splits = content.split('\"\"\"') # fmt: skip + content = "".join(splits[::2]) + + module_parts = str(module_fname).split(os.path.sep) + imported_modules = [] + + # Let's start with relative imports + relative_imports = _re_single_line_relative_imports.findall(content) + relative_imports = [ + (mod, imp) for mod, imp in relative_imports if "# tests_ignore" not in imp and imp.strip() != "(" + ] + multiline_relative_imports = _re_multi_line_relative_imports.findall(content) + relative_imports += [(mod, imp) for mod, imp in multiline_relative_imports if "# tests_ignore" not in imp] + + # We need to remove parts of the module name depending on the depth of the relative imports. + for module, imports in relative_imports: + level = 0 + while module.startswith("."): + module = module[1:] + level += 1 + + if len(module) > 0: + dep_parts = module_parts[: len(module_parts) - level] + module.split(".") + else: + dep_parts = module_parts[: len(module_parts) - level] + imported_module = os.path.sep.join(dep_parts) + imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")])) + + # Let's continue with direct imports + direct_imports = _re_single_line_direct_imports.findall(content) + direct_imports = [(mod, imp) for mod, imp in direct_imports if "# tests_ignore" not in imp and imp.strip() != "("] + multiline_direct_imports = _re_multi_line_direct_imports.findall(content) + direct_imports += [(mod, imp) for mod, imp in multiline_direct_imports if "# tests_ignore" not in imp] + + # We need to find the relative path of those imports. + for module, imports in direct_imports: + import_parts = module.split(".")[1:] # ignore the name of the repo since we add it below. + dep_parts = ["src", "transformers"] + import_parts + imported_module = os.path.sep.join(dep_parts) + imported_modules.append((imported_module, [imp.strip() for imp in imports.split(",")])) + + result = [] + # Double check we get proper modules (either a python file or a folder with an init). + for module_file, imports in imported_modules: + if (PATH_TO_REPO / f"{module_file}.py").is_file(): + module_file = f"{module_file}.py" + elif (PATH_TO_REPO / module_file).is_dir() and (PATH_TO_REPO / module_file / "__init__.py").is_file(): + module_file = os.path.sep.join([module_file, "__init__.py"]) + imports = [imp for imp in imports if len(imp) > 0 and re.match("^[A-Za-z0-9_]*$", imp)] + if len(imports) > 0: + result.append((module_file, imports)) + + if cache is not None: + cache[module_fname] = result + + return result + + +def get_module_dependencies(module_fname: str, cache: Optional[dict[str, list[str]]] = None) -> list[str]: + """ + Refines the result of `extract_imports` to remove subfolders and get a proper list of module filenames: if a file + as an import `from utils import Foo, Bar`, with `utils` being a subfolder containing many files, this will traverse + the `utils` init file to check where those dependencies come from: for instance the files utils/foo.py and utils/bar.py. + + Warning: This presupposes that all intermediate inits are properly built (with imports from the respective + submodules) and work better if objects are defined in submodules and not the intermediate init (otherwise the + intermediate init is added, and inits usually have a lot of dependencies). + + Args: + module_fname (`str`): + The name of the file of the module where we want to look at the imports (given relative to the root of + the repo). + cache (Dictionary `str` to `List[str]`, *optional*): + To speed up this function if it was previously called on `module_fname`, the cache of all previously + computed results. + + Returns: + `List[str]`: The list of module filenames imported in the input `module_fname` (with submodule imports refined). + """ + dependencies = [] + imported_modules = extract_imports(module_fname, cache=cache) + # The while loop is to recursively traverse all inits we may encounter: we will add things as we go. + while len(imported_modules) > 0: + new_modules = [] + for module, imports in imported_modules: + if "models" in module.split("/") and module.split("/")[-1].startswith("convert_"): + continue + # If we end up in an __init__ we are often not actually importing from this init (except in the case where + # the object is fully defined in the __init__) + if module.endswith("__init__.py"): + # So we get the imports from that init then try to find where our objects come from. + new_imported_modules = dict(extract_imports(module, cache=cache)) + + # Add imports via `define_import_structure` after the #35167 as we remove explicit import in `__init__.py` + from transformers.utils.import_utils import define_import_structure + + new_imported_modules_from_import_structure = define_import_structure(PATH_TO_REPO / module) + + for mapping in new_imported_modules_from_import_structure.values(): + for _module, _imports in mapping.items(): + # Import Structure returns _module keys as import paths rather than local paths + # We replace with os.path.sep so that it's Windows-compatible + _module = _module.replace(".", os.path.sep) + _module = module.replace("__init__.py", f"{_module}.py") + if _module not in new_imported_modules: + new_imported_modules[_module] = list(_imports) + else: + original_imports = new_imported_modules[_module] + for potential_new_item in list(_imports): + if potential_new_item not in original_imports: + new_imported_modules[_module].append(potential_new_item) + + for new_module, new_imports in new_imported_modules.items(): + if any(i in new_imports for i in imports): + if new_module not in dependencies: + new_modules.append((new_module, [i for i in new_imports if i in imports])) + imports = [i for i in imports if i not in new_imports] + + if len(imports) > 0: + # If there are any objects lefts, they may be a submodule + path_to_module = PATH_TO_REPO / module.replace("__init__.py", "") + dependencies.extend( + [ + os.path.join(module.replace("__init__.py", ""), f"{i}.py") + for i in imports + if (path_to_module / f"{i}.py").is_file() + ] + ) + imports = [i for i in imports if not (path_to_module / f"{i}.py").is_file()] + if len(imports) > 0: + # Then if there are still objects left, they are fully defined in the init, so we keep it as a + # dependency. + dependencies.append(module) + else: + dependencies.append(module) + + imported_modules = new_modules + + return dependencies + + +def create_reverse_dependency_tree() -> list[tuple[str, str]]: + """ + Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files. + """ + cache = {} + all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + all_modules = [x for x in all_modules if not ("models" in x.parts and x.parts[-1].startswith("convert_"))] + all_modules += list(PATH_TO_TESTS.glob("**/*.py")) + all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] + edges = [(dep, mod) for mod in all_modules for dep in get_module_dependencies(mod, cache=cache)] + + return list(set(edges)) + + +def get_tree_starting_at(module: str, edges: list[tuple[str, str]]) -> list[Union[str, list[str]]]: + """ + Returns the tree starting at a given module following all edges. + + Args: + module (`str`): The module that will be the root of the subtree we want. + eges (`List[Tuple[str, str]]`): The list of all edges of the tree. + + Returns: + `List[Union[str, List[str]]]`: The tree to print in the following format: [module, [list of edges + starting at module], [list of edges starting at the preceding level], ...] + """ + vertices_seen = [module] + new_edges = [edge for edge in edges if edge[0] == module and edge[1] != module and "__init__.py" not in edge[1]] + tree = [module] + while len(new_edges) > 0: + tree.append(new_edges) + final_vertices = list({edge[1] for edge in new_edges}) + vertices_seen.extend(final_vertices) + new_edges = [ + edge + for edge in edges + if edge[0] in final_vertices and edge[1] not in vertices_seen and "__init__.py" not in edge[1] + ] + + return tree + + +def print_tree_deps_of(module, all_edges=None): + """ + Prints the tree of modules depending on a given module. + + Args: + module (`str`): The module that will be the root of the subtree we want. + all_eges (`List[Tuple[str, str]]`, *optional*): + The list of all edges of the tree. Will be set to `create_reverse_dependency_tree()` if not passed. + """ + if all_edges is None: + all_edges = create_reverse_dependency_tree() + tree = get_tree_starting_at(module, all_edges) + + # The list of lines is a list of tuples (line_to_be_printed, module) + # Keeping the modules lets us know where to insert each new lines in the list. + lines = [(tree[0], tree[0])] + for index in range(1, len(tree)): + edges = tree[index] + start_edges = {edge[0] for edge in edges} + + for start in start_edges: + end_edges = {edge[1] for edge in edges if edge[0] == start} + # We will insert all those edges just after the line showing start. + pos = 0 + while lines[pos][1] != start: + pos += 1 + lines = lines[: pos + 1] + [(" " * (2 * index) + end, end) for end in end_edges] + lines[pos + 1 :] + + for line in lines: + # We don't print the refs that where just here to help build lines. + print(line[0]) + + +def init_test_examples_dependencies() -> tuple[dict[str, list[str]], list[str]]: + """ + The test examples do not import from the examples (which are just scripts, not modules) so we need some extra + care initializing the dependency map, which is the goal of this function. It initializes the dependency map for + example files by linking each example to the example test file for the example framework. + + Returns: + `Tuple[Dict[str, List[str]], List[str]]`: A tuple with two elements: the initialized dependency map which is a + dict test example file to list of example files potentially tested by that test file, and the list of all + example files (to avoid recomputing it later). + """ + test_example_deps = {} + all_examples = [] + for framework in ["flax", "pytorch", "tensorflow"]: + test_files = list((PATH_TO_EXAMPLES / framework).glob("test_*.py")) + all_examples.extend(test_files) + # Remove the files at the root of examples/framework since they are not proper examples (they are eith utils + # or example test files). + examples = [ + f for f in (PATH_TO_EXAMPLES / framework).glob("**/*.py") if f.parent != PATH_TO_EXAMPLES / framework + ] + all_examples.extend(examples) + for test_file in test_files: + with open(test_file, "r", encoding="utf-8") as f: + content = f.read() + # Map all examples to the test files found in examples/framework. + test_example_deps[str(test_file.relative_to(PATH_TO_REPO))] = [ + str(e.relative_to(PATH_TO_REPO)) for e in examples if e.name in content + ] + # Also map the test files to themselves. + test_example_deps[str(test_file.relative_to(PATH_TO_REPO))].append( + str(test_file.relative_to(PATH_TO_REPO)) + ) + return test_example_deps, all_examples + + +def create_reverse_dependency_map() -> dict[str, list[str]]: + """ + Create the dependency map from module/test filename to the list of modules/tests that depend on it recursively. + + Returns: + `Dict[str, List[str]]`: The reverse dependency map as a dictionary mapping filenames to all the filenames + depending on it recursively. This way the tests impacted by a change in file A are the test files in the list + corresponding to key A in this result. + """ + + cache = {} + # Start from the example deps init. + example_deps, examples = init_test_examples_dependencies() + # Add all modules and all tests to all examples + all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py")) + all_modules = [x for x in all_modules if not ("models" in x.parts and x.parts[-1].startswith("convert_"))] + all_modules += list(PATH_TO_TESTS.glob("**/*.py")) + examples + all_modules = [str(mod.relative_to(PATH_TO_REPO)) for mod in all_modules] + # Compute the direct dependencies of all modules. + direct_deps = {m: get_module_dependencies(m, cache=cache) for m in all_modules} + direct_deps.update(example_deps) + + # This recurses the dependencies + something_changed = True + while something_changed: + something_changed = False + for m in all_modules: + for d in direct_deps[m]: + # We stop recursing at an init (cause we always end up in the main init and we don't want to add all + # files which the main init imports) + if d.endswith("__init__.py"): + continue + if d not in direct_deps: + raise ValueError(f"KeyError:{d}. From {m}") + new_deps = set(direct_deps[d]) - set(direct_deps[m]) + if len(new_deps) > 0: + direct_deps[m].extend(list(new_deps)) + something_changed = True + + # Finally we can build the reverse map. + reverse_map = collections.defaultdict(list) + for m in all_modules: + for d in direct_deps[m]: + reverse_map[d].append(m) + + # For inits, we don't do the reverse deps but the direct deps: if modifying an init, we want to make sure we test + # all the modules impacted by that init. + for m in [f for f in all_modules if f.endswith("__init__.py")]: + direct_deps = get_module_dependencies(m, cache=cache) + deps = sum([reverse_map[d] for d in direct_deps if not d.endswith("__init__.py")], direct_deps) + reverse_map[m] = list(set(deps) - {m}) + + return reverse_map + + +def create_module_to_test_map( + reverse_map: Optional[dict[str, list[str]]] = None, filter_models: bool = False +) -> dict[str, list[str]]: + """ + Extract the tests from the reverse_dependency_map and potentially filters the model tests. + + Args: + reverse_map (`Dict[str, List[str]]`, *optional*): + The reverse dependency map as created by `create_reverse_dependency_map`. Will default to the result of + that function if not provided. + filter_models (`bool`, *optional*, defaults to `False`): + Whether or not to filter model tests to only include core models if a file impacts a lot of models. + + Returns: + `Dict[str, List[str]]`: A dictionary that maps each file to the tests to execute if that file was modified. + """ + if reverse_map is None: + reverse_map = create_reverse_dependency_map() + + # Utility that tells us if a given file is a test (taking test examples into account) + def is_test(fname): + if fname.startswith("tests"): + return True + if fname.startswith("examples") and fname.split(os.path.sep)[-1].startswith("test"): + return True + return False + + # Build the test map + test_map = {module: [f for f in deps if is_test(f)] for module, deps in reverse_map.items()} + + if not filter_models: + return test_map + + # Now we deal with the filtering if `filter_models` is True. + num_model_tests = len(list(PATH_TO_TESTS.glob("models/*"))) + + def has_many_models(tests): + # We filter to core models when a given file impacts more than half the model tests. + model_tests = {Path(t).parts[2] for t in tests if t.startswith("tests/models/")} + return len(model_tests) > num_model_tests // 2 + + # for each module (if specified in the argument `module`) of the form `models/my_model` (i.e. starting with it), + # we always keep the tests (those are already in the argument `tests`) which are in `tests/models/my_model`. + # This is to avoid them being excluded when a module has many impacted tests: the directly related test files should + # always be included! + def filter_tests(tests, module=""): + filtered_tests = [] + for t in tests: + if ( + not t.startswith("tests/models/") + or Path(t).parts[2] in IMPORTANT_MODELS + # at this point, `t` is of the form `tests/models/my_model`, and we check if `models/my_model` + # (i.e. `parts[1:3]`) is in `module`. + or "/".join(Path(t).parts[1:3]) in module + ): + filtered_tests += [t] + return filtered_tests + + return { + module: (filter_tests(tests, module=module) if has_many_models(tests) else tests) + for module, tests in test_map.items() + } + + +def _print_list(l) -> str: + """ + Pretty print a list of elements with one line per element and a - starting each line. + """ + return "\n".join([f"- {f}" for f in l]) + + +def infer_tests_to_run( + output_file: str, diff_with_last_commit: bool = False, filter_models: bool = False, test_all: bool = False +): + """ + The main function called by the test fetcher. Determines the tests to run from the diff. + + Args: + output_file (`str`): + The path where to store the summary of the test fetcher analysis. Other files will be stored in the same + folder: + + - examples_test_list.txt: The list of examples tests to run. + - test_repo_utils.txt: Will indicate if the repo utils tests should be run or not. + - doctest_list.txt: The list of doctests to run. + + diff_with_last_commit (`bool`, *optional*, defaults to `False`): + Whether to analyze the diff with the last commit (for use on the main branch after a PR is merged) or with + the branching point from main (for use on each PR). + filter_models (`bool`, *optional*, defaults to `True`): + Whether or not to filter the tests to core models only, when a file modified results in a lot of model + tests. + """ + if not test_all: + modified_files = get_modified_python_files(diff_with_last_commit=diff_with_last_commit) + else: + modified_files = [str(k) for k in PATH_TO_TESTS.glob("*/*") if str(k).endswith(".py") and "test_" in str(k)] + print("\n### test_all is TRUE, FETCHING ALL FILES###\n") + print(f"\n### MODIFIED FILES ###\n{_print_list(modified_files)}") + + reverse_map = create_reverse_dependency_map() + impacted_files = modified_files.copy() + for f in modified_files: + if f in reverse_map: + impacted_files.extend(reverse_map[f]) + + # Remove duplicates + impacted_files = sorted(set(impacted_files)) + print(f"\n### IMPACTED FILES ###\n{_print_list(impacted_files)}") + + model_impacted = {"/".join(x.split("/")[:3]) for x in impacted_files if x.startswith("tests/models/")} + # Grab the corresponding test files: + if ( + any(x in modified_files for x in ["setup.py", ".circleci/create_circleci_config.py"]) + or not filter_models + and len(model_impacted) >= NUM_MODELS_TO_TRIGGER_FULL_CI + or commit_flags["test_all"] + ): + test_files_to_run = glob.glob("tests/**/test_**.py", recursive=True) + glob.glob( + "examples/**/*.py", recursive=True + ) + if len(model_impacted) >= NUM_MODELS_TO_TRIGGER_FULL_CI and filter_models: + print( + f"More than {NUM_MODELS_TO_TRIGGER_FULL_CI - 1} models are impacted and `filter_models=False`. CI is configured to test everything." + ) + else: + # All modified tests need to be run. + test_files_to_run = [f for f in modified_files if f.startswith("tests") and "/test_" in f] + impacted_files = get_impacted_files_from_tiny_model_summary(diff_with_last_commit=diff_with_last_commit) + + # Then we grab the corresponding test files. + test_map = create_module_to_test_map(reverse_map=reverse_map, filter_models=filter_models) + for f in modified_files + impacted_files: + if f in test_map: + test_files_to_run.extend(test_map[f]) + test_files_to_run = sorted(set(test_files_to_run)) + # Remove repo utils tests + test_files_to_run = [f for f in test_files_to_run if f.split(os.path.sep)[1] != "repo_utils"] + # Remove SageMaker tests + test_files_to_run = [f for f in test_files_to_run if f.split(os.path.sep)[1] != "sagemaker"] + # Make sure we did not end up with a test file that was removed + test_files_to_run = [f for f in test_files_to_run if (PATH_TO_REPO / f).exists()] + + print(f"\n### TEST TO RUN ###\n{_print_list(test_files_to_run)}") + + create_test_list_from_filter(test_files_to_run, out_path="test_preparation/") + + doctest_list = get_doctest_files() + + print(f"\n### DOCTEST TO RUN ###\n{_print_list(doctest_list)}") + if len(doctest_list) > 0: + doctest_file = Path(output_file).parent / "doctest_list.txt" + with open(doctest_file, "w", encoding="utf-8") as f: + f.write(" ".join(doctest_list)) + + +def filter_tests(output_file: str, filters: list[str]): + """ + Reads the content of the output file and filters out all the tests in a list of given folders. + + Args: + output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher. + filters (`List[str]`): A list of folders to filter. + """ + if not os.path.isfile(output_file): + print("No test file found.") + return + with open(output_file, "r", encoding="utf-8") as f: + test_files = f.read().split(" ") + + if len(test_files) == 0 or test_files == [""]: + print("No tests to filter.") + return + + if test_files == ["tests"]: + test_files = [os.path.join("tests", f) for f in os.listdir("tests") if f not in ["__init__.py"] + filters] + else: + test_files = [f for f in test_files if f.split(os.path.sep)[1] not in filters] + + with open(output_file, "w", encoding="utf-8") as f: + f.write(" ".join(test_files)) + + +def parse_commit_message(commit_message: str) -> dict[str, bool]: + """ + Parses the commit message to detect if a command is there to skip, force all or part of the CI. + + Args: + commit_message (`str`): The commit message of the current commit. + + Returns: + `Dict[str, bool]`: A dictionary of strings to bools with keys the following keys: `"skip"`, + `"test_all_models"` and `"test_all"`. + """ + if commit_message is None: + return {"skip": False, "no_filter": False, "test_all": False} + + command_search = re.search(r"\[([^\]]*)\]", commit_message) + if command_search is not None: + command = command_search.groups()[0] + command = command.lower().replace("-", " ").replace("_", " ") + skip = command in ["ci skip", "skip ci", "circleci skip", "skip circleci"] + no_filter = set(command.split(" ")) == {"no", "filter"} + test_all = set(command.split(" ")) == {"test", "all"} + return {"skip": skip, "no_filter": no_filter, "test_all": test_all} + else: + return {"skip": False, "no_filter": False, "test_all": False} + + +JOB_TO_TEST_FILE = { + "tests_torch": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*", + "tests_generate": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*", + "tests_tokenization": r"tests/(?:models/.*/test_tokenization.*|test_tokenization_mistral_common\.py)", + "tests_processors": r"tests/models/.*/test_(?!(?:modeling_|tokenization_)).*", # takes feature extractors, image processors, processors + "examples_torch": r"examples/pytorch/.*test_.*", + "tests_exotic_models": r"tests/models/.*(?=layoutlmv|nat|deta|udop|nougat).*", + "tests_custom_tokenizers": r"tests/models/.*/test_tokenization_(?=bert_japanese|openai|clip).*", + # "repo_utils": r"tests/[^models].*test.*", TODO later on we might want to do + "pipelines_torch": r"tests/models/.*/test_modeling_(?!(?:flax_|tf_)).*", + "tests_hub": r"tests/.*", + "tests_onnx": r"tests/models/.*/test_modeling_(?:tf_|(?!flax)).*", + "tests_non_model": r"tests/[^/]*?/test_.*\.py", +} + + +def create_test_list_from_filter(full_test_list, out_path): + os.makedirs(out_path, exist_ok=True) + all_test_files = "\n".join(full_test_list) + for job_name, _filter in JOB_TO_TEST_FILE.items(): + file_name = os.path.join(out_path, f"{job_name}_test_list.txt") + if job_name == "tests_hub": + files_to_test = ["tests"] + else: + files_to_test = list(re.findall(_filter, all_test_files)) + print(job_name, file_name) + if len(files_to_test) > 0: # No tests -> no file with test list + with open(file_name, "w") as f: + f.write("\n".join(files_to_test)) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument( + "--output_file", type=str, default="test_list.txt", help="Where to store the list of tests to run" + ) + parser.add_argument( + "--json_output_file", + type=str, + default="test_map.json", + help="Where to store the tests to run in a dictionary format mapping test categories to test files", + ) + parser.add_argument( + "--diff_with_last_commit", + action="store_true", + help="To fetch the tests between the current commit and the last commit", + ) + parser.add_argument( + "--filter_tests", + action="store_true", + help="Will filter the pipeline/repo utils tests outside of the generated list of tests.", + ) + parser.add_argument( + "--print_dependencies_of", + type=str, + help="Will only print the tree of modules depending on the file passed.", + default=None, + ) + parser.add_argument( + "--fetch_all", + action="store_true", + help="Will fetch all tests.", + default=None, + ) + args = parser.parse_args() + if args.print_dependencies_of is not None: + print_tree_deps_of(args.print_dependencies_of) + elif args.filter_tests: + filter_tests(args.output_file, ["pipelines", "repo_utils"]) + else: + repo = Repo(PATH_TO_REPO) + commit_message = repo.head.commit.message + commit_flags = parse_commit_message(commit_message) + if commit_flags["skip"]: + print("Force-skipping the CI") + quit() + if commit_flags["no_filter"]: + print("Running all tests fetched without filtering.") + + if args.fetch_all: + commit_flags["test_all"] = True + if commit_flags["test_all"]: + print("Force-launching all tests") + + is_main_branch = not repo.head.is_detached and repo.head.ref == repo.refs.main + diff_with_last_commit = args.diff_with_last_commit + if not diff_with_last_commit and is_main_branch: + print("main branch detected, fetching tests against last commit.") + diff_with_last_commit = True + + infer_tests_to_run( + args.output_file, + diff_with_last_commit=diff_with_last_commit, + filter_models=False, + test_all=commit_flags["test_all"], + ) + filter_tests(args.output_file, ["repo_utils"]) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/tf_ops/onnx.json b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/tf_ops/onnx.json new file mode 100644 index 0000000000000000000000000000000000000000..a468145d66eb541bd39ef57d25be6263500491d7 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/tf_ops/onnx.json @@ -0,0 +1,245 @@ +{ + "opsets": { + "1": [ + "Abs", + "Add", + "AddV2", + "ArgMax", + "ArgMin", + "AvgPool", + "AvgPool3D", + "BatchMatMul", + "BatchMatMulV2", + "BatchToSpaceND", + "BiasAdd", + "BiasAddV1", + "Cast", + "Ceil", + "CheckNumerics", + "ComplexAbs", + "Concat", + "ConcatV2", + "Const", + "ConstV2", + "Conv1D", + "Conv2D", + "Conv2DBackpropInput", + "Conv3D", + "Conv3DBackpropInputV2", + "DepthToSpace", + "DepthwiseConv2d", + "DepthwiseConv2dNative", + "Div", + "Dropout", + "Elu", + "Equal", + "Erf", + "Exp", + "ExpandDims", + "Flatten", + "Floor", + "Gather", + "GatherNd", + "GatherV2", + "Greater", + "Identity", + "IdentityN", + "If", + "LRN", + "LSTMBlockCell", + "LeakyRelu", + "Less", + "Log", + "LogSoftmax", + "LogicalAnd", + "LogicalNot", + "LogicalOr", + "LookupTableSizeV2", + "MatMul", + "Max", + "MaxPool", + "MaxPool3D", + "MaxPoolV2", + "Maximum", + "Mean", + "Min", + "Minimum", + "MirrorPad", + "Mul", + "Neg", + "NoOp", + "NotEqual", + "OneHot", + "Pack", + "Pad", + "PadV2", + "Placeholder", + "PlaceholderV2", + "PlaceholderWithDefault", + "Pow", + "Prod", + "RFFT", + "RandomNormal", + "RandomNormalLike", + "RandomUniform", + "RandomUniformLike", + "RealDiv", + "Reciprocal", + "Relu", + "Relu6", + "Reshape", + "Rsqrt", + "Selu", + "Shape", + "Sigmoid", + "Sign", + "Size", + "Slice", + "Softmax", + "Softplus", + "Softsign", + "SpaceToBatchND", + "SpaceToDepth", + "Split", + "SplitV", + "Sqrt", + "Square", + "SquaredDifference", + "Squeeze", + "StatelessIf", + "StopGradient", + "StridedSlice", + "StringJoin", + "Sub", + "Sum", + "Tanh", + "Tile", + "TopKV2", + "Transpose", + "TruncateDiv", + "Unpack", + "ZerosLike" + ], + "2": [], + "3": [], + "4": [], + "5": [], + "6": [ + "AddN", + "All", + "Any", + "FloorDiv", + "FusedBatchNorm", + "FusedBatchNormV2", + "FusedBatchNormV3" + ], + "7": [ + "Acos", + "Asin", + "Atan", + "Cos", + "Fill", + "FloorMod", + "GreaterEqual", + "LessEqual", + "Loop", + "MatrixBandPart", + "Multinomial", + "Range", + "ResizeBilinear", + "ResizeNearestNeighbor", + "Scan", + "Select", + "SelectV2", + "Sin", + "SoftmaxCrossEntropyWithLogits", + "SparseSoftmaxCrossEntropyWithLogits", + "StatelessWhile", + "Tan", + "TensorListFromTensor", + "TensorListGetItem", + "TensorListLength", + "TensorListReserve", + "TensorListResize", + "TensorListSetItem", + "TensorListStack", + "While" + ], + "8": [ + "BroadcastTo", + "ClipByValue", + "FIFOQueueV2", + "HashTableV2", + "IteratorGetNext", + "IteratorV2", + "LookupTableFindV2", + "MaxPoolWithArgmax", + "QueueDequeueManyV2", + "QueueDequeueUpToV2", + "QueueDequeueV2", + "ReverseSequence" + ], + "9": [ + "SegmentMax", + "SegmentMean", + "SegmentMin", + "SegmentProd", + "SegmentSum", + "Sinh", + "SparseSegmentMean", + "SparseSegmentMeanWithNumSegments", + "SparseSegmentSqrtN", + "SparseSegmentSqrtNWithNumSegments", + "SparseSegmentSum", + "SparseSegmentSumWithNumSegments", + "UnsortedSegmentMax", + "UnsortedSegmentMin", + "UnsortedSegmentProd", + "UnsortedSegmentSum", + "Where" + ], + "10": [ + "CropAndResize", + "CudnnRNN", + "DynamicStitch", + "FakeQuantWithMinMaxArgs", + "IsFinite", + "IsInf", + "NonMaxSuppressionV2", + "NonMaxSuppressionV3", + "NonMaxSuppressionV4", + "NonMaxSuppressionV5", + "ParallelDynamicStitch", + "ReverseV2", + "Roll" + ], + "11": [ + "Bincount", + "Cumsum", + "InvertPermutation", + "LeftShift", + "MatrixDeterminant", + "MatrixDiagPart", + "MatrixDiagPartV2", + "MatrixDiagPartV3", + "RaggedRange", + "RightShift", + "Round", + "ScatterNd", + "SparseFillEmptyRows", + "SparseReshape", + "SparseToDense", + "TensorScatterUpdate", + "Unique" + ], + "12": [ + "Einsum", + "MatrixDiag", + "MatrixDiagV2", + "MatrixDiagV3", + "MatrixSetDiagV3", + "SquaredDistance" + ], + "13": [] + } +} \ No newline at end of file diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/update_metadata.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/update_metadata.py new file mode 100644 index 0000000000000000000000000000000000000000..8d60c4b374b8a24d6ef6c8e8d5ca2be86b86de2a --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/update_metadata.py @@ -0,0 +1,371 @@ +# coding=utf-8 +# Copyright 2021 The HuggingFace Inc. team. +# +# 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. +""" +Utility that updates the metadata of the Transformers library in the repository `huggingface/transformers-metadata`. + +Usage for an update (as used by the GitHub action `update_metadata`): + +```bash +python utils/update_metadata.py --token --commit_sha +``` + +Usage to check all pipelines are properly defined in the constant `PIPELINE_TAGS_AND_AUTO_MODELS` of this script, so +that new pipelines are properly added as metadata (as used in `make repo-consistency`): + +```bash +python utils/update_metadata.py --check-only +``` +""" + +import argparse +import collections +import os +import re +import tempfile + +import pandas as pd +from datasets import Dataset +from huggingface_hub import hf_hub_download, upload_folder + +from transformers.utils import direct_transformers_import + + +# All paths are set with the intent you should run this script from the root of the repo with the command +# python utils/update_metadata.py +TRANSFORMERS_PATH = "src/transformers" + + +# This is to make sure the transformers module imported is the one in the repo. +transformers_module = direct_transformers_import(TRANSFORMERS_PATH) + + +# Regexes that match TF/Flax/PT model names. +_re_tf_models = re.compile(r"TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") +_re_flax_models = re.compile(r"Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)") +# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes. +_re_pt_models = re.compile(r"(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration|ForRetrieval)") + + +# Fill this with tuples (pipeline_tag, model_mapping, auto_model) +PIPELINE_TAGS_AND_AUTO_MODELS = [ + ("pretraining", "MODEL_FOR_PRETRAINING_MAPPING_NAMES", "AutoModelForPreTraining"), + ("feature-extraction", "MODEL_MAPPING_NAMES", "AutoModel"), + ("image-feature-extraction", "MODEL_FOR_IMAGE_MAPPING_NAMES", "AutoModel"), + ("audio-classification", "MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForAudioClassification"), + ("text-generation", "MODEL_FOR_CAUSAL_LM_MAPPING_NAMES", "AutoModelForCausalLM"), + ("automatic-speech-recognition", "MODEL_FOR_CTC_MAPPING_NAMES", "AutoModelForCTC"), + ("image-classification", "MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForImageClassification"), + ("image-segmentation", "MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES", "AutoModelForImageSegmentation"), + ("image-text-to-text", "MODEL_FOR_IMAGE_TEXT_TO_TEXT_MAPPING_NAMES", "AutoModelForImageTextToText"), + ("image-to-image", "MODEL_FOR_IMAGE_TO_IMAGE_MAPPING_NAMES", "AutoModelForImageToImage"), + ("fill-mask", "MODEL_FOR_MASKED_LM_MAPPING_NAMES", "AutoModelForMaskedLM"), + ("object-detection", "MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES", "AutoModelForObjectDetection"), + ( + "zero-shot-object-detection", + "MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES", + "AutoModelForZeroShotObjectDetection", + ), + ("question-answering", "MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES", "AutoModelForQuestionAnswering"), + ("text2text-generation", "MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES", "AutoModelForSeq2SeqLM"), + ("text-classification", "MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES", "AutoModelForSequenceClassification"), + ("automatic-speech-recognition", "MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES", "AutoModelForSpeechSeq2Seq"), + ( + "table-question-answering", + "MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForTableQuestionAnswering", + ), + ("token-classification", "MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES", "AutoModelForTokenClassification"), + ("multiple-choice", "MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES", "AutoModelForMultipleChoice"), + ( + "next-sentence-prediction", + "MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES", + "AutoModelForNextSentencePrediction", + ), + ( + "audio-frame-classification", + "MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES", + "AutoModelForAudioFrameClassification", + ), + ("audio-xvector", "MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES", "AutoModelForAudioXVector"), + ( + "document-question-answering", + "MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForDocumentQuestionAnswering", + ), + ( + "visual-question-answering", + "MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES", + "AutoModelForVisualQuestionAnswering", + ), + ("image-to-text", "MODEL_FOR_VISION_2_SEQ_MAPPING_NAMES", "AutoModelForVision2Seq"), + ( + "zero-shot-image-classification", + "MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES", + "AutoModelForZeroShotImageClassification", + ), + ("depth-estimation", "MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES", "AutoModelForDepthEstimation"), + ("video-classification", "MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES", "AutoModelForVideoClassification"), + ("mask-generation", "MODEL_FOR_MASK_GENERATION_MAPPING_NAMES", "AutoModelForMaskGeneration"), + ("text-to-audio", "MODEL_FOR_TEXT_TO_SPECTROGRAM_MAPPING_NAMES", "AutoModelForTextToSpectrogram"), + ("text-to-audio", "MODEL_FOR_TEXT_TO_WAVEFORM_MAPPING_NAMES", "AutoModelForTextToWaveform"), +] + + +def camel_case_split(identifier: str) -> list[str]: + """ + Split a camel-cased name into words. + + Args: + identifier (`str`): The camel-cased name to parse. + + Returns: + `List[str]`: The list of words in the identifier (as separated by capital letters). + + Example: + + ```py + >>> camel_case_split("CamelCasedClass") + ["Camel", "Cased", "Class"] + ``` + """ + # Regex thanks to https://stackoverflow.com/questions/29916065/how-to-do-camelcase-split-in-python + matches = re.finditer(".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)", identifier) + return [m.group(0) for m in matches] + + +def get_frameworks_table() -> pd.DataFrame: + """ + Generates a dataframe containing the supported auto classes for each model type, using the content of the auto + modules. + """ + # Dictionary model names to config. + config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES + model_prefix_to_model_type = { + config.replace("Config", ""): model_type for model_type, config in config_maping_names.items() + } + + # Dictionaries flagging if each model prefix has a backend in PT/TF/Flax. + pt_models = collections.defaultdict(bool) + tf_models = collections.defaultdict(bool) + flax_models = collections.defaultdict(bool) + + # Let's lookup through all transformers object (once) and find if models are supported by a given backend. + for attr_name in dir(transformers_module): + lookup_dict = None + if _re_tf_models.match(attr_name) is not None: + lookup_dict = tf_models + attr_name = _re_tf_models.match(attr_name).groups()[0] + elif _re_flax_models.match(attr_name) is not None: + lookup_dict = flax_models + attr_name = _re_flax_models.match(attr_name).groups()[0] + elif _re_pt_models.match(attr_name) is not None: + lookup_dict = pt_models + attr_name = _re_pt_models.match(attr_name).groups()[0] + + if lookup_dict is not None: + while len(attr_name) > 0: + if attr_name in model_prefix_to_model_type: + lookup_dict[model_prefix_to_model_type[attr_name]] = True + break + # Try again after removing the last word in the name + attr_name = "".join(camel_case_split(attr_name)[:-1]) + + all_models = set(list(pt_models.keys()) + list(tf_models.keys()) + list(flax_models.keys())) + all_models = list(all_models) + all_models.sort() + + data = {"model_type": all_models} + data["pytorch"] = [pt_models[t] for t in all_models] + data["tensorflow"] = [tf_models[t] for t in all_models] + data["flax"] = [flax_models[t] for t in all_models] + + # Now let's find the right processing class for each model. In order we check if there is a Processor, then a + # Tokenizer, then a FeatureExtractor, then an ImageProcessor + processors = {} + for t in all_models: + if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES: + processors[t] = "AutoProcessor" + elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES: + processors[t] = "AutoTokenizer" + elif t in transformers_module.models.auto.image_processing_auto.IMAGE_PROCESSOR_MAPPING_NAMES: + processors[t] = "AutoImageProcessor" + elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES: + processors[t] = "AutoFeatureExtractor" + else: + # Default to AutoTokenizer if a model has nothing, for backward compatibility. + processors[t] = "AutoTokenizer" + + data["processor"] = [processors[t] for t in all_models] + + return pd.DataFrame(data) + + +def update_pipeline_and_auto_class_table(table: dict[str, tuple[str, str]]) -> dict[str, tuple[str, str]]: + """ + Update the table mapping models to pipelines and auto classes without removing old keys if they don't exist anymore. + + Args: + table (`Dict[str, Tuple[str, str]]`): + The existing table mapping model names to a tuple containing the pipeline tag and the auto-class name with + which they should be used. + + Returns: + `Dict[str, Tuple[str, str]]`: The updated table in the same format. + """ + auto_modules = [ + transformers_module.models.auto.modeling_auto, + transformers_module.models.auto.modeling_tf_auto, + transformers_module.models.auto.modeling_flax_auto, + ] + for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS: + model_mappings = [model_mapping, f"TF_{model_mapping}", f"FLAX_{model_mapping}"] + auto_classes = [auto_class, f"TF_{auto_class}", f"Flax_{auto_class}"] + # Loop through all three frameworks + for module, cls, mapping in zip(auto_modules, auto_classes, model_mappings): + # The type of pipeline may not exist in this framework + if not hasattr(module, mapping): + continue + # First extract all model_names + model_names = [] + for name in getattr(module, mapping).values(): + if isinstance(name, str): + model_names.append(name) + else: + model_names.extend(list(name)) + + # Add pipeline tag and auto model class for those models + table.update(dict.fromkeys(model_names, (pipeline_tag, cls))) + + return table + + +def update_metadata(token: str, commit_sha: str): + """ + Update the metadata for the Transformers repo in `huggingface/transformers-metadata`. + + Args: + token (`str`): A valid token giving write access to `huggingface/transformers-metadata`. + commit_sha (`str`): The commit SHA on Transformers corresponding to this update. + """ + frameworks_table = get_frameworks_table() + frameworks_dataset = Dataset.from_pandas(frameworks_table) + + resolved_tags_file = hf_hub_download( + "huggingface/transformers-metadata", "pipeline_tags.json", repo_type="dataset", token=token + ) + tags_dataset = Dataset.from_json(resolved_tags_file) + table = { + tags_dataset[i]["model_class"]: (tags_dataset[i]["pipeline_tag"], tags_dataset[i]["auto_class"]) + for i in range(len(tags_dataset)) + } + table = update_pipeline_and_auto_class_table(table) + + # Sort the model classes to avoid some nondeterministic updates to create false update commits. + model_classes = sorted(table.keys()) + tags_table = pd.DataFrame( + { + "model_class": model_classes, + "pipeline_tag": [table[m][0] for m in model_classes], + "auto_class": [table[m][1] for m in model_classes], + } + ) + tags_dataset = Dataset.from_pandas(tags_table) + + hub_frameworks_json = hf_hub_download( + repo_id="huggingface/transformers-metadata", + filename="frameworks.json", + repo_type="dataset", + token=token, + ) + with open(hub_frameworks_json) as f: + hub_frameworks_json = f.read() + + hub_pipeline_tags_json = hf_hub_download( + repo_id="huggingface/transformers-metadata", + filename="pipeline_tags.json", + repo_type="dataset", + token=token, + ) + with open(hub_pipeline_tags_json) as f: + hub_pipeline_tags_json = f.read() + + with tempfile.TemporaryDirectory() as tmp_dir: + frameworks_dataset.to_json(os.path.join(tmp_dir, "frameworks.json")) + tags_dataset.to_json(os.path.join(tmp_dir, "pipeline_tags.json")) + + with open(os.path.join(tmp_dir, "frameworks.json")) as f: + frameworks_json = f.read() + with open(os.path.join(tmp_dir, "pipeline_tags.json")) as f: + pipeline_tags_json = f.read() + + frameworks_equal = hub_frameworks_json == frameworks_json + hub_pipeline_tags_equal = hub_pipeline_tags_json == pipeline_tags_json + + if frameworks_equal and hub_pipeline_tags_equal: + print("No updates on the Hub, not pushing the metadata files.") + return + + if commit_sha is not None: + commit_message = ( + f"Update with commit {commit_sha}\n\nSee: " + f"https://github.com/huggingface/transformers/commit/{commit_sha}" + ) + else: + commit_message = "Update" + + upload_folder( + repo_id="huggingface/transformers-metadata", + folder_path=tmp_dir, + repo_type="dataset", + token=token, + commit_message=commit_message, + ) + + +def check_pipeline_tags(): + """ + Check all pipeline tags are properly defined in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant of this script. + """ + in_table = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS} + pipeline_tasks = transformers_module.pipelines.SUPPORTED_TASKS + missing = [] + for key in pipeline_tasks: + if key not in in_table: + model = pipeline_tasks[key]["pt"] + if isinstance(model, (list, tuple)): + model = model[0] + model = model.__name__ + if model not in in_table.values(): + missing.append(key) + + if len(missing) > 0: + msg = ", ".join(missing) + raise ValueError( + "The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside " + f"`utils/update_metadata.py`: {msg}. Please add them!" + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--token", type=str, help="The token to use to push to the transformers-metadata dataset.") + parser.add_argument("--commit_sha", type=str, help="The sha of the commit going with this update.") + parser.add_argument("--check-only", action="store_true", help="Activate to just check all pipelines are present.") + args = parser.parse_args() + + if args.check_only: + check_pipeline_tags() + else: + update_metadata(args.token, args.commit_sha) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/update_tiny_models.py b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/update_tiny_models.py new file mode 100644 index 0000000000000000000000000000000000000000..9dc4cdf6e6b29e3a3df13b1685dd620a82c9ad3d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/source/utils/update_tiny_models.py @@ -0,0 +1,199 @@ +# coding=utf-8 +# Copyright 2023 The HuggingFace Inc. team. +# +# 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. +"""A script running `create_dummy_models.py` with a pre-defined set of arguments. + +This file is intended to be used in a CI workflow file without the need of specifying arguments. It creates and uploads +tiny models for all model classes (if their tiny versions are not on the Hub yet), as well as produces an updated +version of `tests/utils/tiny_model_summary.json`. That updated file should be merged into the `main` branch of +`transformers` so the pipeline testing will use the latest created/updated tiny models. +""" + +import argparse +import copy +import json +import multiprocessing +import os +import time + +from create_dummy_models import COMPOSITE_MODELS, create_tiny_models +from huggingface_hub import ModelFilter, hf_api + +import transformers +from transformers import AutoFeatureExtractor, AutoImageProcessor, AutoTokenizer +from transformers.image_processing_utils import BaseImageProcessor + + +def get_all_model_names(): + model_names = set() + # Each auto modeling files contains multiple mappings. Let's get them in a dynamic way. + for module_name in ["modeling_auto", "modeling_tf_auto", "modeling_flax_auto"]: + module = getattr(transformers.models.auto, module_name, None) + if module is None: + continue + # all mappings in a single auto modeling file + mapping_names = [ + x + for x in dir(module) + if x.endswith("_MAPPING_NAMES") + and (x.startswith("MODEL_") or x.startswith("TF_MODEL_") or x.startswith("FLAX_MODEL_")) + ] + for name in mapping_names: + mapping = getattr(module, name) + if mapping is not None: + for v in mapping.values(): + if isinstance(v, (list, tuple)): + model_names.update(v) + elif isinstance(v, str): + model_names.add(v) + + return sorted(model_names) + + +def get_tiny_model_names_from_repo(): + # All model names defined in auto mappings + model_names = set(get_all_model_names()) + + with open("tests/utils/tiny_model_summary.json") as fp: + tiny_model_info = json.load(fp) + tiny_models_names = set() + for model_base_name in tiny_model_info: + tiny_models_names.update(tiny_model_info[model_base_name]["model_classes"]) + + # Remove a tiny model name if one of its framework implementation hasn't yet a tiny version on the Hub. + not_on_hub = model_names.difference(tiny_models_names) + for model_name in copy.copy(tiny_models_names): + if not model_name.startswith("TF") and f"TF{model_name}" in not_on_hub: + tiny_models_names.remove(model_name) + elif model_name.startswith("TF") and model_name[2:] in not_on_hub: + tiny_models_names.remove(model_name) + + return sorted(tiny_models_names) + + +def get_tiny_model_summary_from_hub(output_path): + special_models = COMPOSITE_MODELS.values() + + # All tiny model base names on Hub + model_names = get_all_model_names() + models = hf_api.list_models( + filter=ModelFilter( + author="hf-internal-testing", + ) + ) + _models = set() + for x in models: + model = x.id + org, model = model.split("/") + if not model.startswith("tiny-random-"): + continue + model = model.replace("tiny-random-", "") + if not model[0].isupper(): + continue + if model not in model_names and model not in special_models: + continue + _models.add(model) + + models = sorted(_models) + # All tiny model names on Hub + summary = {} + for model in models: + repo_id = f"hf-internal-testing/tiny-random-{model}" + model = model.split("-")[0] + try: + repo_info = hf_api.repo_info(repo_id) + content = { + "tokenizer_classes": set(), + "processor_classes": set(), + "model_classes": set(), + "sha": repo_info.sha, + } + except Exception: + continue + try: + time.sleep(1) + tokenizer_fast = AutoTokenizer.from_pretrained(repo_id) + content["tokenizer_classes"].add(tokenizer_fast.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + tokenizer_slow = AutoTokenizer.from_pretrained(repo_id, use_fast=False) + content["tokenizer_classes"].add(tokenizer_slow.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + img_p = AutoImageProcessor.from_pretrained(repo_id) + content["processor_classes"].add(img_p.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + feat_p = AutoFeatureExtractor.from_pretrained(repo_id) + if not isinstance(feat_p, BaseImageProcessor): + content["processor_classes"].add(feat_p.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + model_class = getattr(transformers, model) + m = model_class.from_pretrained(repo_id) + content["model_classes"].add(m.__class__.__name__) + except Exception: + pass + try: + time.sleep(1) + model_class = getattr(transformers, f"TF{model}") + m = model_class.from_pretrained(repo_id) + content["model_classes"].add(m.__class__.__name__) + except Exception: + pass + + content["tokenizer_classes"] = sorted(content["tokenizer_classes"]) + content["processor_classes"] = sorted(content["processor_classes"]) + content["model_classes"] = sorted(content["model_classes"]) + + summary[model] = content + with open(os.path.join(output_path, "hub_tiny_model_summary.json"), "w") as fp: + json.dump(summary, fp, ensure_ascii=False, indent=4) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("--num_workers", default=1, type=int, help="The number of workers to run.") + args = parser.parse_args() + + # This has to be `spawn` to avoid hanging forever! + multiprocessing.set_start_method("spawn") + + output_path = "tiny_models" + all = True + model_types = None + models_to_skip = get_tiny_model_names_from_repo() + no_check = True + upload = True + organization = "hf-internal-testing" + + create_tiny_models( + output_path, + all, + model_types, + models_to_skip, + no_check, + upload, + organization, + token=os.environ.get("TOKEN", None), + num_workers=args.num_workers, + ) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/test.sh b/tasks/tasksmith-5cbfd9f64dbc/tests/test.sh new file mode 100644 index 0000000000000000000000000000000000000000..c92b552378bd5c90e06861fb4c3cf5e93ef8dd72 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/test.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +exec /opt/tasksmith-venv/bin/python -I /tests/grade.py diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/test_driver.py b/tasks/tasksmith-5cbfd9f64dbc/tests/test_driver.py new file mode 100644 index 0000000000000000000000000000000000000000..c0b8bb331c4499e300b92f0e022ff6a723a4a562 --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/test_driver.py @@ -0,0 +1,41 @@ +"""Private pytest entry point with a bounded framework-tampering check. + +The host still owns reward parsing. This guard detects replacement or in-place +editing of unittest assertions, a demonstrated attack against repository tests. +It does not claim to isolate arbitrary test and solution code in one interpreter. +""" + +from __future__ import annotations + +import sys +import unittest + + +def run(arguments: list[str]) -> int: + import pytest + + # Capture before pytest imports any repository modules. Retain code objects + # too: an attacker can mutate function.__code__ without replacing a method. + original = { + name: (value, getattr(value, "__code__", None)) + for name, value in vars(unittest.TestCase).items() + if name.startswith("assert") and callable(value) + } + case = unittest.TestCase + # The harness supplies selectors and reporting explicitly. Repository addopts + # often enable optional coverage/report plugins that are intentionally not + # auto-loaded in this isolated verifier; they are not test dependencies. + code = int(pytest.main(["-o", "addopts=", *arguments])) + changed = [] + for name, (method, implementation) in original.items(): + current = getattr(case, name, None) + if current is not method or getattr(current, "__code__", None) is not implementation: + changed.append(name) + if unittest.TestCase is not case or changed: + sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n") + return 254 + return code + + +if __name__ == "__main__": + raise SystemExit(run(sys.argv[1:])) diff --git a/tasks/tasksmith-5cbfd9f64dbc/tests/test_results.py b/tasks/tasksmith-5cbfd9f64dbc/tests/test_results.py new file mode 100644 index 0000000000000000000000000000000000000000..05ce2c730e38e02bad44f2344e88e5f1cb02cb8d --- /dev/null +++ b/tasks/tasksmith-5cbfd9f64dbc/tests/test_results.py @@ -0,0 +1,65 @@ +"""Strict test evidence used by repository recipes and their exported verifiers.""" + +from __future__ import annotations + +from dataclasses import dataclass +from xml.etree import ElementTree + + +@dataclass(frozen=True) +class TestResults: + __test__ = False + statuses: dict[str, str] + returncode: int + + @property + def passed(self) -> set[str]: + return {name for name, status in self.statuses.items() if status == "passed"} + + +def parse_junit(text: str, *, returncode: int) -> TestResults: + if " dict[str, list[str]]: + if healthy.returncode != 0 or not healthy.passed: + raise ValueError("Reference must execute successfully with passing tests") + if healthy.statuses.keys() != defective.statuses.keys(): + raise ValueError("Mutation changed test collection; contrast is not comparable") + failing = sorted( + name for name in healthy.passed if defective.statuses[name] in {"failed", "error"} + ) + if not failing or defective.returncode != 1: + raise ValueError("No intended fail-to-pass contrast") + return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))} diff --git a/tasks/tasksmith-5d12db5414d2/environment/Dockerfile b/tasks/tasksmith-5d12db5414d2/environment/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..2241e6ce5148b77c2a681508536589615510e139 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/Dockerfile @@ -0,0 +1,8 @@ +FROM python:3.12-slim-bookworm +WORKDIR /workspace +RUN python -m pip install --no-cache-dir certifi==2026.7.22 charset-normalizer==3.5.1 click==8.5.0 filelock==3.32.3 fsspec==2026.7.0 hf-xet==1.6.0 huggingface_hub==0.36.2 idna==3.19 iniconfig==2.3.0 Jinja2==3.1.6 MarkupSafe==3.0.3 mpmath==1.3.0 networkx==3.6.1 numpy==2.5.3 packaging==26.3 parameterized==0.9.0 pluggy==1.6.0 psutil==7.2.2 Pygments==2.21.0 pytest==8.4.2 PyYAML==6.0.3 regex==2024.11.6 requests==2.32.3 safetensors==0.8.0 setuptools==78.1.0 sympy==1.14.0 tokenizers==0.21.4 torch==2.11.0+cpu transformers==4.47.0 tqdm==4.70.1 typing_extensions==4.16.0 urllib3==2.4.0 wheel==0.48.0 --extra-index-url https://download.pytorch.org/whl/cpu +COPY source /workspace +RUN python -m pip install --no-cache-dir -e . +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/* +RUN useradd -m -u 1000 learner && chown -R learner:learner /workspace diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.devcontainer/devcontainer.json b/tasks/tasksmith-5d12db5414d2/environment/source/.devcontainer/devcontainer.json new file mode 100644 index 0000000000000000000000000000000000000000..7a0da2404899e9335e4ccd7559d7af36f825be37 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.devcontainer/devcontainer.json @@ -0,0 +1,29 @@ +// File only needed for VSCode users to have proper Docker based interpreters +{ + "name": "accelerate_dev_environment", + "build": { + // ACTION NEEDED: comment/uncomment the relevant line depending on whether you are in a CPU/GPU environment + "dockerfile": "../docker/accelerate-cpu/Dockerfile" +// "dockerfile": "../docker/accelerate-gpu/Dockerfile" + }, + "runArgs": [ + // ACTION NEEDED: uncomment the next line if your local machine has GPUs available +// "--gpus", "all", + // Enable the docker container to access system resources + "--ipc", "host" + ], + "remoteEnv": { + "PYTHONPATH": "${containerEnv:PATH}:${containerWorkspaceFolder}" + }, + "customizations": { + "vscode": { + "extensions": [ + // Ensure we have IntelliSense in VSCode when running inside container + "ms-python.python" + ] + } + }, + "workspaceFolder": "/workspaces/accelerate", + // Need git for VSCode to color code modifications. Only runs when building environment. + "onCreateCommand": "apt-get update && apt-get install -y git && pip install -e '.[dev]'" +} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/ISSUE_TEMPLATE/bug-report.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000000000000000000000000000000000000..16111314f4f733d0551f3ce917a58e4ff74bda0e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,63 @@ +name: "\U0001F41B Bug Report" +description: Submit a bug report to help us improve Accelerate +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to submit a bug report! 🐛 + If this is not a bug related to the Accelerate library directly, but instead a general question about your code or the library specifically please use the [forums](https://discuss.huggingface.co/c/accelerate/18). + + - type: textarea + id: system-info + attributes: + label: System Info + description: Please share your accelerate configuration with us. You can run the command `accelerate env` and copy-paste its outputs below + render: Shell + placeholder: accelerate version, OS, python version, numpy version, torch version, and accelerate's configuration + validations: + required: true + + - type: checkboxes + id: information-scripts-examples + attributes: + label: Information + description: 'The problem arises when using:' + options: + - label: "The official example scripts" + - label: "My own modified scripts" + + - type: checkboxes + id: information-tasks + attributes: + label: Tasks + description: "The tasks I am working on are:" + options: + - label: "One of the scripts in the examples/ folder of Accelerate or an officially supported `no_trainer` script in the `examples` folder of the `transformers` repo (such as `run_no_trainer_glue.py`)" + - label: "My own task or dataset (give details below)" + + - type: textarea + id: reproduction + validations: + required: true + attributes: + label: Reproduction + description: | + Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet. + If you have code snippets, error messages, stack traces please provide them here as well. + Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting + Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code. + + placeholder: | + Steps to reproduce the behavior: + + 1. + 2. + 3. + + - type: textarea + id: expected-behavior + validations: + required: true + attributes: + label: Expected behavior + description: "A clear and concise description of what you would expect to happen." diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/PULL_REQUEST_TEMPLATE.md b/tasks/tasksmith-5d12db5414d2/environment/source/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..6ec3b6498f7093951e1a49e93f22b7984c05551d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,47 @@ +# What does this PR do? + + + + + +Fixes # (issue) + + +## Before submitting +- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case). +- [ ] Did you read the [contributor guideline](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md#submitting-a-pull-request-pr), + Pull Request section? +- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link + to it if that's the case. +- [ ] Did you make sure to update the documentation with your changes? Here are the + [documentation guidelines](https://github.com/huggingface/accelerate/tree/main/docs), and + [here are tips on formatting docstrings](https://github.com/huggingface/accelerate/tree/main/docs#writing-documentation---specification). +- [ ] Did you write any new necessary tests? + + +## Who can review? + +Anyone in the community is free to review the PR once the tests have passed. Feel free to tag +members/contributors who may be interested in your PR. + + \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build-docker-images-release.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build-docker-images-release.yml new file mode 100644 index 0000000000000000000000000000000000000000..3a5c5052fac608a72a55c66af9414f200d18bb1c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build-docker-images-release.yml @@ -0,0 +1,104 @@ +name: Build Docker images (releases) + +on: + workflow_dispatch: + release: + types: [published] + +concurrency: + group: docker-image-builds + cancel-in-progress: false + +jobs: + get-version: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.step1.outputs.version }} + steps: + - uses: actions/checkout@v3.1.0 + - id: step1 + run: echo "version=$(python setup.py --version)" >> $GITHUB_OUTPUT + + version-cpu: + name: "Latest Accelerate CPU [version]" + runs-on: + group: aws-general-8-plus + needs: get-version + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push CPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-cpu/Dockerfile + push: true + tags: huggingface/accelerate:cpu-release-${{ needs.get-version.outputs.version }} + + version-cuda: + name: "Latest Accelerate GPU [version]" + runs-on: + group: aws-g6-4xlarge-plus + needs: get-version + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu/Dockerfile + push: true + tags: huggingface/accelerate:gpu-release-${{needs.get-version.outputs.version}} + + version-cuda-deepspeed: + name: "Latest Accelerate GPU DeepSpeed [version]" + runs-on: + group: aws-g6-4xlarge-plus + needs: get-version + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu-deepspeed/Dockerfile + push: true + tags: huggingface/accelerate:gpu-deepspeed-release-${{needs.get-version.outputs.version}} + + version-cuda-fp8-transformerengine: + name: "Latest Accelerate GPU FP8 TransformerEngine [version]" + runs-on: + group: aws-g6-4xlarge-plus + needs: get-version + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu/Dockerfile + push: true + tags: huggingface/accelerate:gpu-fp8-transformerengine-release-${{needs.get-version.outputs.version}} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_and_run_tests.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_and_run_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..3169e8546128ff643660891599c2217f413a2e5e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_and_run_tests.yml @@ -0,0 +1,50 @@ +name: Trigger docker images and run tests + +on: + push: + branches: + - main + workflow_dispatch: + +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + +jobs: + check-for-source: + runs-on: ubuntu-latest + name: Check if setup was changed + outputs: + changed: ${{ steps.was_changed.outputs.changed }} + steps: + - uses: actions/checkout@v3.1.0 + with: + fetch-depth: "2" + + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@v41 + + - name: Was setup changed + id: was_changed + run: | + for file in ${{ steps.changed-files.outputs.all_changed_files }}; do + if [ `basename "${file}"` == "setup.py" ]; then + echo "changed=1" >> $GITHUB_OUTPUT + fi + done + + build-docker-containers: + needs: check-for-source + if: (github.event_name == 'push') && (needs.check-for-source.outputs.changed == '1') + uses: ./.github/workflows/build_docker_images.yml + secrets: inherit + + run-merge-tests: + needs: build-docker-containers + if: always() + uses: ./.github/workflows/run_merge_tests.yml + + run-integration-tests: + needs: build-docker-containers + if: always() + uses: ./.github/workflows/self_hosted_integration_tests.yml \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_docker_images.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_docker_images.yml new file mode 100644 index 0000000000000000000000000000000000000000..2050bbba7147827c07b51264002b611d6383abc5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_docker_images.yml @@ -0,0 +1,110 @@ +name: Build Docker images (scheduled) + +on: + workflow_dispatch: + workflow_call: + schedule: + - cron: "0 1 * * *" + +concurrency: + group: docker-image-builds + cancel-in-progress: false + +jobs: + latest-cpu: + name: "Latest Accelerate CPU [dev]" + runs-on: + group: aws-general-8-plus + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - name: Get current date + id: date + run: | + echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV + - name: Build and Push CPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-cpu/Dockerfile + push: true + tags: | + huggingface/accelerate:cpu-nightly + huggingface/accelerate:cpu-nightly-${{ env.date }} + + latest-cuda: + name: "Latest Accelerate GPU [dev]" + runs-on: + group: aws-g6-4xlarge-plus + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - name: Get current date + id: date + run: | + echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu/Dockerfile + push: true + tags: | + huggingface/accelerate:gpu-nightly + huggingface/accelerate:gpu-nightly-${{ env.date }} + + latest-cuda-deepspeed: + name: "Latest Accelerate GPU DeepSpeed [dev]" + runs-on: + group: aws-g6-4xlarge-plus + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - name: Get current date + id: date + run: | + echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu-deepspeed/Dockerfile + push: true + tags: | + huggingface/accelerate:gpu-deepspeed-nightly + huggingface/accelerate:gpu-deepspeed-nightly-${{ env.date }} + + latest-cuda-fp8-transformerengine: + name: "Latest Accelerate GPU FP8 TransformerEngine [dev]" + runs-on: + group: aws-g6-4xlarge-plus + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - name: Get current date + id: date + run: | + echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: benchmarks/fp8/Dockerfile + push: true + tags: huggingface/accelerate:gpu-fp8-transformerengine-nightly-${{ env.date }} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_documentation.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..dc529d9dbfad72b24184ceb7f34a6b2da7dc9512 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_documentation.yml @@ -0,0 +1,18 @@ +name: Build documentation + +on: + push: + branches: + - main + - doc-builder* + - v*-release + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main + with: + commit_sha: ${{ github.sha }} + package: accelerate + custom_container: huggingface/transformers-doc-builder + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_pr_documentation.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..7b8463e20b3e212d29eacbd31f5c5ae609029b2d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/build_pr_documentation.yml @@ -0,0 +1,17 @@ +name: Build PR Documentation + +on: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main + with: + commit_sha: ${{ github.event.pull_request.head.sha }} + pr_number: ${{ github.event.number }} + package: accelerate + custom_container: huggingface/transformers-doc-builder diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/integration_tests.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/integration_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..59aeb66b6a5c3868e00400806f3a3954f20d19a6 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/integration_tests.yml @@ -0,0 +1,58 @@ +# CI for specifically ensuring integrations work fine (`transformers` mainly) +# Useful tips: +# - New integrations to test should have its own job, and follow a strategy method where we check both +# the pypi and github versions. +# - When checking the latest release of the integration, use +# git checkout $(git describe --tags `git rev-list --tags --max-count=1`) to get the latest release. + +name: Integration Tests + +on: + pull_request: + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "examples/**" + - "setup.py" + types: [opened, synchronize, reopened] + +env: + HF_HOME: ~/hf_cache + +jobs: + run-trainer-tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + steps: + - uses: actions/checkout@v3.1.0 + - name: Set up python 3.8 + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + + - name: Install Accelerate from source + run: | + pip install --upgrade pip + pip install -e . + + - name: Clone and install transformers + run: | + cd .. + git clone https://github.com/huggingface/transformers + cd transformers + pip install .[torch,testing] + + - name: Show installed libraries + run: | + pip freeze + + - name: Run Trainer tests + env: + WANDB_DISABLED: true + run: | + cd ../transformers + pytest -sv tests/trainer diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/nightly.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/nightly.yml new file mode 100644 index 0000000000000000000000000000000000000000..c1eb49e952bfdb930699c34d4c5911a5813e40b0 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/nightly.yml @@ -0,0 +1,233 @@ +name: Self-hosted runner with slow tests (scheduled) + +on: + workflow_dispatch: + schedule: + - cron: "0 2 * * *" + +env: + RUN_SLOW: "yes" + IS_GITHUB_CI: "1" + SLACK_API_TOKEN: ${{ secrets.SLACK_API_TOKEN }} + + +jobs: + run_core_tests_single_gpu: + runs-on: + group: aws-g6-4xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0" + TEST_TYPE: "single_gpu" + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone & pip install + run: | + source activate accelerate + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e . --no-deps + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + run: | + source activate accelerate + make test + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + pip uninstall comet_ml -y + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install slack_sdk tabulate + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_deepspeed_tests_single_gpu: + runs-on: + group: aws-g6-4xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0" + TEST_TYPE: "single_gpu_deepspeed" + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone & pip install + run: | + source activate accelerate + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e . --no-deps + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + run: | + source activate accelerate + make test_deepspeed + + - name: Run Integration tests on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + make test_integrations + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + pip uninstall comet_ml -y + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install slack_sdk tabulate + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_core_tests_multi_gpu: + runs-on: + group: aws-g6-12xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0,1" + TEST_TYPE: "multi_gpu" + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone + run: | + source activate accelerate + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e . --no-deps + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run core and big modeling tests on GPUs + working-directory: accelerate + run: | + source activate accelerate + make test_core + make test_big_modeling + make test_cli + + - name: Run Integration tests on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + make test_integrations + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + pip uninstall comet_ml -y + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install slack_sdk tabulate + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_deepspeed_tests_multi_gpu: + runs-on: + group: aws-g6-12xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0,1" + TEST_TYPE: "multi_gpu_deepspeed" + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone + run: | + source activate accelerate + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e . --no-deps + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run DeepSpeed tests + working-directory: accelerate + run: | + source activate accelerate + make test_deepspeed + + - name: Run Integration tests on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + make test_integrations + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + pip uninstall comet_ml -y + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install slack_sdk tabulate + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + + run-integration-tests: + if: always() + uses: ./.github/workflows/self_hosted_integration_tests.yml diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/quality.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/quality.yml new file mode 100644 index 0000000000000000000000000000000000000000..bb590777fb42a14264487557351daa264c429050 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/quality.yml @@ -0,0 +1,24 @@ +name: Quality Check + +on: [pull_request] + +jobs: + quality: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3.1.0 + - name: Set up Python 3.8 + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + - name: Install Python dependencies + run: pip install -e .[quality] + - name: Run Quality check + run: make quality + - name: Check if failure + if: ${{ failure() }} + run: | + echo "Quality check failed. Please ensure the right dependency versions are installed with 'pip install -e .[quality]' and rerun 'make style; make quality;'" >> $GITHUB_STEP_SUMMARY + diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/run_merge_tests.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/run_merge_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..92a193a19c6017d9a005bafc3909341e5dde76aa --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/run_merge_tests.yml @@ -0,0 +1,188 @@ +name: Self-hosted runner tests (push to "main") + +on: + workflow_call: + workflow_dispatch: + +env: + TESTING_MOCKED_DATALOADERS: "1" + IS_GITHUB_CI: "1" + +jobs: + run_core_tests_single_gpu: + runs-on: + group: aws-g6-4xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0" + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Install accelerate + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing,test_trackers] -U; + pip install pytest-reportlog tabulate ; + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run CLI tests (use make cli) + working-directory: accelerate + run: | + source activate accelerate; + make test_cli + + - name: Run test on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + make test + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + pip uninstall comet_ml -y; + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install tabulate; + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_deepspeed_tests_single_gpu: + runs-on: + group: aws-g6-4xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0" + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Install accelerate + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing,test_trackers] -U; + pip install pytest-reportlog tabulate ; + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + make test_deepspeed + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install tabulate; + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_core_tests_multi_gpu: + runs-on: + group: aws-g6-12xlarge-plus + env: + CUDA_VISIBLE_DEVICES: 0,1 + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing,test_trackers] -U; + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + run: | + source activate accelerate; + make test + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + pip uninstall comet_ml -y; + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + source activate accelerate; + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_deepspeed_tests_multi_gpu: + runs-on: + group: aws-g6-12xlarge-plus + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Install accelerate + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing,test_trackers] -U; + pip install pytest-reportlog tabulate ; + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + make test_deepspeed + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install tabulate; + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/self_hosted_integration_tests.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/self_hosted_integration_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..9939c4b826fd2589bcfc7ae5e146534c6fa38e4f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/self_hosted_integration_tests.yml @@ -0,0 +1,127 @@ +# CI for specifically ensuring integrations work fine (`transformers` mainly) on GPUs +# Useful tips: +# - `working-directory` should be set to the root of the repo, which is cloned on the actual CI runner. +# It follows the directory structure of `actions-runner/_work/{repo_name}/{repo_name}/{cloned_repo} on +# prem, but in Actions setting `working-directory` looks just in the `{repo_name}` level. +# - New integrations to test should have its own job, and follow a strategy method where we check both +# the pypi and github versions. +# - Workflow call lets this be called from `build_and_run_tests.yml` +# - When using a docker container, it's recommended to set `--shm-size`, we use 16gb. +name: Integration Tests (push to "main") + +on: + workflow_call: + workflow_dispatch: + +env: + HF_HOME: ~/hf_cache + +defaults: + run: + shell: bash + +jobs: + run-trainer-tests: + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + runs-on: + group: aws-g6-12xlarge-plus + strategy: + fail-fast: false + matrix: + cuda_visible_devices: [ + "0", + "0,1" + ] + steps: + - name: Install transformers + run: | + source activate accelerate; + git clone https://github.com/huggingface/transformers --depth 1; + cd transformers; + pip install .[torch,deepspeed-testing]; + cd ..; + + - name: Install accelerate + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }} ; + pip install -e .[testing]; + pip uninstall comet_ml wandb dvclive -y + cd ..; + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run trainer tests + working-directory: transformers/ + env: + CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }} + WANDB_DISABLED: true + run: | + source activate accelerate; + pytest -sv tests/trainer + + - name: Run deepspeed tests + working-directory: transformers/ + env: + CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }} + WANDB_DISABLED: true + if: always() + run: | + source activate accelerate; + pytest -sv tests/deepspeed + + - name: Run transformers examples tests + working-directory: transformers/ + env: + CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }} + WANDB_DISABLED: true + run: | + source activate accelerate + pip install -r examples/pytorch/_tests_requirements.txt + pytest -sv examples/pytorch/test_accelerate_examples.py examples/pytorch/test_pytorch_examples.py + + run-skorch-tests: + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + runs-on: + group: aws-g6-12xlarge-plus + strategy: + fail-fast: false + steps: + - name: Install accelerate + run: + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing]; + cd .. + + - name: Install skorch + run: | + source activate accelerate + git clone https://github.com/skorch-dev/skorch; + cd skorch; + git config --global --add safe.directory '*' + git checkout master && git pull + pip install .[testing] + pip install flaky + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run skorch tests + working-directory: skorch/ + run: | + source activate accelerate; + pytest -sv -k TestAccelerate diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/stale.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..b91d320141fc8627a7fdf6d77f2c1de42314f613 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/stale.yml @@ -0,0 +1,30 @@ +name: Stale Bot + +on: + schedule: + - cron: "0 15 * * *" + workflow_dispatch: + +jobs: + close_stale_issues: + name: Close Stale Issues + if: github.repository == 'huggingface/accelerate' + runs-on: ubuntu-latest + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v3.1.0 + + - name: Setup Python + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + + - name: Install requirements + run: | + pip install PyGithub + - name: Close stale issues + run: | + python utils/stale.py diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/test.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/test.yml new file mode 100644 index 0000000000000000000000000000000000000000..9940caac264f62a31762f463f3eef5c630b6bea5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/test.yml @@ -0,0 +1,70 @@ +name: Run Tests + +on: + pull_request: + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "examples/**" + - "setup.py" + types: [opened, synchronize, reopened] + +env: + HF_HOME: ~/hf_cache + TESTING_MOCKED_DATALOADERS: "1" + IS_GITHUB_CI: "1" + +jobs: + run-tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + pytorch-version: [ + latest, + minimum, + ] + test-kind: [ + test_prod, + test_core, + test_cli, + test_big_modeling, + test_deepspeed, + test_fsdp, + test_example_differences, + test_checkpoint_step, + test_checkpoint_epoch, + test_rest + ] + steps: + - uses: actions/checkout@v3.1.0 + - name: Set up python 3.8 + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + + - name: Install the library + run: | + if [[ ${{ matrix.test-kind }} = test_prod ]]; then pip install -e .[test_prod]; fi + if [[ ${{ matrix.test-kind }} != test_prod ]]; then pip install -e .[testing,test_trackers]; fi + if [[ ${{ matrix.test-kind }} = test_rest ]]; then pip uninstall comet_ml -y; fi + if [[ ${{ matrix.pytorch-version }} = minimum ]]; then pip install torchvision==0.18.1 torch==2.3.1; fi + pip install pytest-reportlog tabulate setuptools + + - name: Show installed libraries + run: | + pip freeze + + - name: Run Tests + env: + PYTORCH_VERSION: ${{ matrix.pytorch-version }} + run: | + make ${{ matrix.test-kind }} + + - name: Generate Report + if: always() + run: | + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/test_imports.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/test_imports.yml new file mode 100644 index 0000000000000000000000000000000000000000..90e5229bc860249d9887e635b535b8f0c73e7af8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/test_imports.yml @@ -0,0 +1,55 @@ +name: Run Import Tests + +on: + pull_request: + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "examples/**" + - "setup.py" + types: [opened, synchronize, reopened] + +env: + HF_HOME: ~/hf_cache + TESTING_MOCKED_DATALOADERS: "1" + IS_GITHUB_CI: "1" + +jobs: + run-tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + pytorch-version: [ + latest, + minimum, + ] + steps: + - uses: actions/checkout@v3.1.0 + - name: Set up python 3.8 + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + + - name: Install the library + run: | + pip install -e . + pip install pytest-reportlog tabulate setuptools git+https://github.com/muellerzr/import-timer + + - name: Show installed libraries + run: | + pip freeze + + - name: Run Import Tests + env: + PYTORCH_VERSION: ${{ matrix.pytorch-version }} + run: | + pytest -sv tests/test_imports.py + + - name: Generate Report + if: always() + run: | + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/trufflehog.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/trufflehog.yml new file mode 100644 index 0000000000000000000000000000000000000000..9cbbf6803724dacc4759b69d7002bb34831e5937 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/trufflehog.yml @@ -0,0 +1,15 @@ +on: + push: + +name: Secret Leaks + +jobs: + trufflehog: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Secret Scanning + uses: trufflesecurity/trufflehog@main diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/upload_pr_documentation.yml b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/upload_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd6ed29f9f87a1e6e8364aead9740cf8a059e6a4 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.github/workflows/upload_pr_documentation.yml @@ -0,0 +1,16 @@ +name: Upload PR Documentation + +on: + workflow_run: + workflows: ["Build PR Documentation"] + types: + - completed + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main + with: + package_name: accelerate + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} + comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.gitignore b/tasks/tasksmith-5d12db5414d2/environment/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ff24394ddad2419878db4f3c27b44b2d8fb686ab --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.gitignore @@ -0,0 +1,144 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# VSCode +.vscode + +# IntelliJ +.idea + +# Mac .DS_Store +.DS_Store + +# More test things +wandb + +# ruff +.ruff_cache diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/.pre-commit-config.yaml b/tasks/tasksmith-5d12db5414d2/environment/source/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1563cffda8f500200924130ddf1e57497f6f2750 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/.pre-commit-config.yaml @@ -0,0 +1,13 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.2.1 + hooks: + - id: ruff + args: + - --fix + - id: ruff-format + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: check-merge-conflict + - id: check-yaml diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/CODE_OF_CONDUCT.md b/tasks/tasksmith-5d12db5414d2/environment/source/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..c8ad966288a9faeeb71b2fad3ba12f6048e1a03f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/CODE_OF_CONDUCT.md @@ -0,0 +1,129 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +feedback@huggingface.co. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/CONTRIBUTING.md b/tasks/tasksmith-5d12db5414d2/environment/source/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..78ad064bd86b39a9f69c3bbd5be3910db1a93d8d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/CONTRIBUTING.md @@ -0,0 +1,249 @@ + + +# How to contribute to 🤗 Accelerate? + +Everyone is welcome to contribute, and we value everybody's contribution. Code +is thus not the only way to help the community. Answering questions, helping +others, reaching out and improving the documentations are immensely valuable to +the community. + +It also helps us if you spread the word: reference the library from blog posts +on the awesome projects it made possible, shout out on Twitter every time it has +helped you, or simply star the repo to say "thank you". + +Whichever way you choose to contribute, please be mindful to respect our +[code of conduct](https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md). + +## You can contribute in so many ways! + +Some of the ways you can contribute to Accelerate: +* Fixing outstanding issues with the existing code; +* Contributing to the examples or to the documentation; +* Submitting issues related to bugs or desired new features. + +## Submitting a new issue or feature request + +Do your best to follow these guidelines when submitting an issue or a feature +request. It will make it easier for us to come back to you quickly and with good +feedback. + +### Did you find a bug? + +The 🤗 Accelerate library is robust and reliable thanks to the users who notify us of +the problems they encounter. So thank you for reporting an issue. + +First, we would really appreciate it if you could **make sure the bug was not +already reported** (use the search bar on Github under Issues). + +Did not find it? :( So we can act quickly on it, please follow these steps: + +* Include your **OS type and version**, the versions of **Python** and **PyTorch**. +* A short, self-contained, code snippet that allows us to reproduce the bug in + less than 30s; +* Provide the with your Accelerate configuration (located by default in `~/.cache/huggingface/accelerate/default_config.yaml`) + +### Do you want a new feature? + +A good feature request addresses the following points: + +1. Motivation first: +* Is it related to a problem/frustration with the library? If so, please explain + why. Providing a code snippet that demonstrates the problem is best. +* Is it related to something you would need for a project? We'd love to hear + about it! +* Is it something you worked on and think could benefit the community? + Awesome! Tell us what problem it solved for you. +2. Write a *full paragraph* describing the feature; +3. Provide a **code snippet** that demonstrates its future use; +4. In case this is related to a paper, please attach a link; +5. Attach any additional information (drawings, screenshots, etc.) you think may help. + +If your issue is well written we're already 80% of the way there by the time you +post it. + +## Submitting a pull request (PR) + +Before writing code, we strongly advise you to search through the existing PRs or +issues to make sure that nobody is already working on the same thing. If you are +unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to be able to contribute to +🤗 Accelerate. `git` is not the easiest tool to use but it has the greatest +manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro +Git](https://git-scm.com/book/en/v2) is a very good reference. + +Follow these steps to start contributing: + +1. Fork the [repository](https://github.com/huggingface/accelerate) by + clicking on the 'Fork' button on the repository's page. This creates a copy of the code + under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote. The following command + assumes you have your public SSH key uploaded to GitHub. See the following guide for more + [information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository). + + ```bash + $ git clone git@github.com:/accelerate.git + $ cd accelerate + $ git remote add upstream https://github.com/huggingface/accelerate.git + ``` + +3. Create a new branch to hold your development changes, and do this for every new PR you work on. + + Start by synchronizing your `main` branch with the `upstream/main` branch (ore details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)): + + ```bash + $ git checkout main + $ git fetch upstream + $ git merge upstream/main + ``` + + Once your `main` branch is synchronized, create a new branch from it: + + ```bash + $ git checkout -b a-descriptive-name-for-my-changes + ``` + + **Do not** work on the `main` branch. + +4. Set up a development environment by running the following command in a conda or a virtual environment you've created for working on this library: + + ```bash + $ pip install -e ".[dev]" + ``` + + This will install all testing and linting/code quality dependencies for the library (see `quality`, `test_dev`, + `test_prod` targets in [`setup.py`](./setup.py)). + + (If accelerate was already installed in the virtual environment, remove + it with `pip uninstall accelerate` before reinstalling it in editable + mode with the `-e` flag). + + Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using + the provided Dev Container. Documentation on how to get started with dev containers is available [here](https://code.visualstudio.com/docs/remote/containers). + +5. Develop the features on your branch. + + As you work on the features, you should make sure that the test suite + passes. You should run the tests impacted by your changes like this (see + below an explanation regarding the environment variable): + + ```bash + $ pytest tests/.py + ``` + + > For the following commands leveraging the `make` utility, we recommend using the WSL system when running on + > Windows. More information [here](https://docs.microsoft.com/en-us/windows/wsl/about). + + You can also run the full suite with the following command. + + ```bash + $ make test + ``` + + `accelerate` relies on `ruff` to format its source code + consistently. After you make changes, apply automatic style corrections and code verifications + that can't be automated in one go with: + + This target is also optimized to only work with files modified by the PR you're working on. + + If you prefer to run the checks one after the other, the following command apply the + style corrections: + + ```bash + $ make style + ``` + + `accelerate` also uses a few custom scripts to check for coding mistakes. Quality + control runs in CI, however you can also run the same checks with: + + ```bash + $ make quality + ``` + + You can also set up [`pre-commit`](https://pre-commit.com/) to run these checks + automatically as Git commit hooks. + + ```bash + $ pip install pre-commit + $ pre-commit install + ``` + + Once you're happy with your changes, add changed files using `git add` and + make a commit with `git commit` to record your changes locally: + + ```bash + $ git add modified_file.py + $ git commit + ``` + + Please write [good commit messages](https://chris.beams.io/posts/git-commit/). + + It is a good idea to sync your copy of the code with the original + repository regularly. This way you can quickly account for changes: + + ```bash + $ git fetch upstream + $ git rebase upstream/main + ``` + + Push the changes to your account using: + + ```bash + $ git push -u origin a-descriptive-name-for-my-changes + ``` + +6. Once you are satisfied (**and the checklist below is happy too**), go to the + webpage of your fork on GitHub. Click on 'Pull request' to send your changes + to the project maintainers for review. + +7. It's ok if maintainers ask you for changes. It happens to core contributors + too! So everyone can see the changes in the Pull request, work in your local + branch and push the changes to your fork. They will automatically appear in + the pull request. + + +### Checklist + +1. The title of your pull request should be a summary of its contribution; +2. If your pull request addresses an issue, please mention the issue number in + the pull request description to make sure they are linked (and people + consulting the issue know you are working on it); +3. To indicate a work in progress please prefix the title with `[WIP]`, or mark + the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate + it from PRs ready to be merged; +4. Make sure existing tests pass; +5. Add high-coverage tests. No quality testing = no merge. + +See an example of a good PR here: https://github.com/huggingface/accelerate/pull/255 + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests folder](https://github.com/huggingface/accelerate/tree/main/tests). + +We use `pytest` in order to run the tests. From the root of the +repository, here's how to run tests with `pytest` for the library: + +```bash +$ python -m pytest -sv ./tests +``` + +In fact, that's how `make test` is implemented (sans the `pip install` line)! + +You can specify a smaller set of tests in order to test only the feature +you're working on. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/Dockerfile b/tasks/tasksmith-5d12db5414d2/environment/source/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5a3c922d33c43968d2d0ca57a1547b27e1bb5016 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/Dockerfile @@ -0,0 +1,7 @@ +FROM python:3.12-slim-bookworm +WORKDIR /workspace +RUN python -m pip install --no-cache-dir certifi==2026.7.22 charset-normalizer==3.5.1 click==8.5.0 filelock==3.32.3 fsspec==2026.7.0 hf-xet==1.6.0 huggingface_hub==0.36.2 idna==3.19 iniconfig==2.3.0 Jinja2==3.1.6 MarkupSafe==3.0.3 mpmath==1.3.0 networkx==3.6.1 numpy==2.5.3 packaging==26.3 parameterized==0.9.0 pluggy==1.6.0 psutil==7.2.2 Pygments==2.21.0 pytest==8.4.2 PyYAML==6.0.3 regex==2024.11.6 requests==2.32.3 safetensors==0.8.0 setuptools==78.1.0 sympy==1.14.0 tokenizers==0.21.4 torch==2.11.0+cpu transformers==4.47.0 tqdm==4.70.1 typing_extensions==4.16.0 urllib3==2.4.0 wheel==0.48.0 --extra-index-url https://download.pytorch.org/whl/cpu +COPY . /workspace +RUN python -m pip install --no-cache-dir -e . +RUN rm -rf /workspace/.git /root/.cache/pip +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/LICENSE b/tasks/tasksmith-5d12db5414d2/environment/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/Makefile b/tasks/tasksmith-5d12db5414d2/environment/source/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..7d01bb8873fb02ddda383aa01608d5219a473d78 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/Makefile @@ -0,0 +1,72 @@ +.PHONY: quality style test docs utils + +check_dirs := . + +# Check that source code meets quality standards + +extra_quality_checks: + python utils/check_copies.py + python utils/check_dummies.py + python utils/check_repo.py + doc-builder style src/accelerate docs/source --max_len 119 + +# this target runs checks on all files +quality: + ruff check $(check_dirs) + ruff format --check $(check_dirs) + doc-builder style src/accelerate docs/source --max_len 119 --check_only + +# Format source code automatically and check is there are any problems left that need manual fixing +style: + ruff check $(check_dirs) --fix + ruff format $(check_dirs) + doc-builder style src/accelerate docs/source --max_len 119 + +# Run tests for the library +test_big_modeling: + python -m pytest -s -v ./tests/test_big_modeling.py ./tests/test_modeling_utils.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_big_modeling.log",) + +test_core: + python -m pytest -s -v ./tests/ --ignore=./tests/test_examples.py --ignore=./tests/deepspeed --ignore=./tests/test_big_modeling.py \ + --ignore=./tests/fsdp --ignore=./tests/test_cli.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_core.log",) + +test_cli: + python -m pytest -s -v ./tests/test_cli.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_cli.log",) + +test_deepspeed: + python -m pytest -s -v ./tests/deepspeed $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_deepspeed.log",) + +test_fsdp: + python -m pytest -s -v ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_fsdp.log",) + +# Since the new version of pytest will *change* how things are collected, we need `deepspeed` to +# run after test_core and test_cli +test: + $(MAKE) test_core + $(MAKE) test_cli + $(MAKE) test_big_modeling + $(MAKE) test_deepspeed + $(MAKE) test_fsdp + +test_examples: + python -m pytest -s -v ./tests/test_examples.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_examples.log",) + +# Broken down example tests for the CI runners +test_integrations: + python -m pytest -s -v ./tests/deepspeed ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_integrations.log",) + +test_example_differences: + python -m pytest -s -v ./tests/test_examples.py::ExampleDifferenceTests $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_example_diff.log",) + +test_checkpoint_epoch: + python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_epoch.log",) + +test_checkpoint_step: + python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_step" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_step.log",) + +# Same as test but used to install only the base dependencies +test_prod: + $(MAKE) test_core + +test_rest: + python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "not by_step and not by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_rest.log",) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/README.md b/tasks/tasksmith-5d12db5414d2/environment/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fc64f02e4fe4f570b155472720320cf165d1ede7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/README.md @@ -0,0 +1,277 @@ + + +

+
+ +
+

+ +

+ + License + Documentation + GitHub release + Contributor Covenant +

+ +

+

Run your *raw* PyTorch training script on any kind of device +

+ +

+ +

+ +## Easy to integrate + +🤗 Accelerate was created for PyTorch users who like to write the training loop of PyTorch models but are reluctant to write and maintain the boilerplate code needed to use multi-GPUs/TPU/fp16. + +🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged. + +Here is an example: + +```diff + import torch + import torch.nn.functional as F + from datasets import load_dataset ++ from accelerate import Accelerator + ++ accelerator = Accelerator() +- device = 'cpu' ++ device = accelerator.device + + model = torch.nn.Transformer().to(device) + optimizer = torch.optim.Adam(model.parameters()) + + dataset = load_dataset('my_dataset') + data = torch.utils.data.DataLoader(dataset, shuffle=True) + ++ model, optimizer, data = accelerator.prepare(model, optimizer, data) + + model.train() + for epoch in range(10): + for source, targets in data: + source = source.to(device) + targets = targets.to(device) + + optimizer.zero_grad() + + output = model(source) + loss = F.cross_entropy(output, targets) + +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() +``` + +As you can see in this example, by adding 5-lines to any standard PyTorch training script you can now run on any kind of single or distributed node setting (single CPU, single GPU, multi-GPUs and TPUs) as well as with or without mixed precision (fp8, fp16, bf16). + +In particular, the same code can then be run without modification on your local machine for debugging or your training environment. + +🤗 Accelerate even handles the device placement for you (which requires a few more changes to your code, but is safer in general), so you can even simplify your training loop further: + +```diff + import torch + import torch.nn.functional as F + from datasets import load_dataset ++ from accelerate import Accelerator + +- device = 'cpu' ++ accelerator = Accelerator() + +- model = torch.nn.Transformer().to(device) ++ model = torch.nn.Transformer() + optimizer = torch.optim.Adam(model.parameters()) + + dataset = load_dataset('my_dataset') + data = torch.utils.data.DataLoader(dataset, shuffle=True) + ++ model, optimizer, data = accelerator.prepare(model, optimizer, data) + + model.train() + for epoch in range(10): + for source, targets in data: +- source = source.to(device) +- targets = targets.to(device) + + optimizer.zero_grad() + + output = model(source) + loss = F.cross_entropy(output, targets) + +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() +``` + +Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples). + +## Launching script + +🤗 Accelerate also provides an optional CLI tool that allows you to quickly configure and test your training environment before launching the scripts. No need to remember how to use `torch.distributed.run` or to write a specific launcher for TPU training! +On your machine(s) just run: + +```bash +accelerate config +``` + +and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing + +```bash +accelerate launch my_script.py --args_to_my_script +``` + +For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo): + +```bash +accelerate launch examples/nlp_example.py +``` + +This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience. + +You can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`. + +For example, here is how to launch on two GPUs: + +```bash +accelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py +``` + +To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli). + +Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/) + +## Launching multi-CPU run using MPI + +🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well. +Once you have MPI setup on your cluster, just run: +```bash +accelerate config +``` +Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun. +Then, use `accelerate launch` with your script like: +```bash +accelerate launch examples/nlp_example.py +``` +Alternatively, you can use mpirun directly, without using the CLI like: +```bash +mpirun -np 2 python examples/nlp_example.py +``` + +## Launching training using DeepSpeed + +🤗 Accelerate supports training on single/multiple GPUs using DeepSpeed. To use it, you don't need to change anything in your training code; you can set everything using just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`. + +```python +from accelerate import Accelerator, DeepSpeedPlugin + +# deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it +# Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed +deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2) +accelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin) + +# How to save your 🤗 Transformer? +accelerator.wait_for_everyone() +unwrapped_model = accelerator.unwrap_model(model) +unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model)) +``` + +Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue. + +## Launching your training from a notebook + +🤗 Accelerate also provides a `notebook_launcher` function you can use in a notebook to launch a distributed training. This is especially useful for Colab or Kaggle notebooks with a TPU backend. Just define your training loop in a `training_function` then in your last cell, add: + +```python +from accelerate import notebook_launcher + +notebook_launcher(training_function) +``` + +An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb) + +## Why should I use 🤗 Accelerate? + +You should use 🤗 Accelerate when you want to easily run your training scripts in a distributed environment without having to renounce full control over your training loop. This is not a high-level framework above PyTorch, just a thin wrapper so you don't have to learn a new library. In fact, the whole API of 🤗 Accelerate is in one class, the `Accelerator` object. + +## Why shouldn't I use 🤗 Accelerate? + +You shouldn't use 🤗 Accelerate if you don't want to write a training loop yourself. There are plenty of high-level libraries above PyTorch that will offer you that, 🤗 Accelerate is not one of them. + +## Frameworks using 🤗 Accelerate + +If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around its capabilities, some frameworks and libraries that are built on top of 🤗 Accelerate are listed below: + +* [Amphion](https://github.com/open-mmlab/Amphion) is a toolkit for Audio, Music, and Speech Generation. Its purpose is to support reproducible research and help junior researchers and engineers get started in the field of audio, music, and speech generation research and development. +* [Animus](https://github.com/Scitator/animus) is a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them within [IExperiment](https://github.com/Scitator/animus/blob/main/animus/core.py#L76). +* [Catalyst](https://github.com/catalyst-team/catalyst#getting-started) is a PyTorch framework for Deep Learning Research and Development. It focuses on reproducibility, rapid experimentation, and codebase reuse so you can create something new rather than write yet another train loop. Catalyst provides a [Runner](https://catalyst-team.github.io/catalyst/api/core.html#runner) to connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic. +* [fastai](https://github.com/fastai/fastai#installing) is a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides a [Learner](https://docs.fast.ai/learner.html#Learner) to handle the training, fine-tuning, and inference of deep learning algorithms. +* [Finetuner](https://github.com/jina-ai/finetuner) is a service that enables models to create higher-quality embeddings for semantic search, visual similarity search, cross-modal text<->image search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses. +* [InvokeAI](https://github.com/invoke-ai/InvokeAI) is a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products. +* [Kornia](https://kornia.readthedocs.io/en/latest/get-started/introduction.html) is a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides a [Trainer](https://kornia.readthedocs.io/en/latest/x.html#kornia.x.Trainer) with the specific purpose to train and fine-tune the supported deep learning algorithms within the library. +* [Open Assistant](https://projects.laion.ai/Open-Assistant/) is a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so. +* [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centered around a general-purpose [Trainer](https://pytorch-accelerated.readthedocs.io/en/latest/trainer.html), that places a huge emphasis on simplicity and transparency; enabling users to understand exactly what is going on under the hood, but without having to write and maintain the boilerplate themselves! +* [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion. +* [torchkeras](https://github.com/lyhue1991/torchkeras) is a simple tool for training pytorch model just in a keras style, a dynamic and beautiful plot is provided in notebook to monitor your loss or metric. +* [transformers](https://github.com/huggingface/transformers) as a tool for helping train state-of-the-art machine learning models in PyTorch, Tensorflow, and JAX. (Accelerate is the backend for the PyTorch side). + + +## Installation + +This repository is tested on Python 3.8+ and PyTorch 1.10.0+ + +You should install 🤗 Accelerate in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). + +First, create a virtual environment with the version of Python you're going to use and activate it. + +Then, you will need to install PyTorch: refer to the [official installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows: + +```bash +pip install accelerate +``` + +## Supported integrations + +- CPU only +- multi-CPU on one node (machine) +- multi-CPU on several nodes (machines) +- single GPU +- multi-GPU on one node (machine) +- multi-GPU on several nodes (machines) +- TPU +- FP16/BFloat16 mixed precision +- FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/) +- DeepSpeed support (Experimental) +- PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental) +- Megatron-LM support (Experimental) + +## Citing 🤗 Accelerate + +If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry. + +```bibtex +@Misc{accelerate, + title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.}, + author = {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan}, + howpublished = {\url{https://github.com/huggingface/accelerate}}, + year = {2022} +} +``` diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/Makefile b/tasks/tasksmith-5d12db5414d2/environment/source/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..8879933e6cda150267451c9e7d07dd22b7b0d3f1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/Makefile @@ -0,0 +1,19 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SOURCEDIR = source +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/README.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4c089297dfc6f0ae4cf6022d17b4694b81db288a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/README.md @@ -0,0 +1,267 @@ + + +# 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 ".[docs]" +``` + +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 accelerate docs/source/ --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 accelerate docs/source/ +``` + +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/accelerate/blob/main/docs/source/_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: + +[ Section A ] +``` +and of course, if you moved it to another file, then: + +``` +Sections that were moved: + +[ Section A ] +``` + +Use the relative style to link to the new file so that the versioned docs continue to work. + + +## Writing Documentation - Specification + +The `huggingface/accelerate` 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. + +### 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.gather\`\]. This will be converted into a link with +`utils.gather` 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.gather\`\] will generate a link with `gather` 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 (more than 119 characters in total), another indentation is necessary +before writing the description after the argument. + +Finally, to maintain uniformity if any *one* description is too long to fit on one line, the +rest of the parameters should follow suit and have an indention before their description. + +Here's an example showcasing everything so far: + +``` + Args: + gradient_accumulation_steps (`int`, *optional*, default to 1): + The number of steps that should pass before gradients are accumulated. A number > 1 should be combined with `Accelerator.accumulate`. + cpu (`bool`, *optional*): + Whether or not to force the script to execute on CPU. Will ignore GPU available if set to `True` and force the execution on one process only. +``` + +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 ... and has a description longer than 119 chars. + a (`float`, *optional*, defaults to 1): + This argument is used to ... and has a description longer than 119 chars. +``` + +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: + + +```` +```python +# first line of code +# second line +# etc +``` +```` + +#### 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: + +``` + 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: + +``` + 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). +``` + +## 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. + +## Writing documentation examples + +The syntax for Example docstrings can look as follows: + +``` + Example: + + ```python + >>> import time + >>> from accelerate import Accelerator + >>> accelerator = Accelerator() + >>> if accelerator.is_main_process: + ... time.sleep(2) + >>> else: + ... print("I'm waiting for the main process to finish its sleep...") + >>> accelerator.wait_for_everyone() + >>> # Should print on every process at the same time + >>> print("Everyone is here") + ``` +``` + +The docstring should give a minimal, clear example of how the respective function +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. \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/_toctree.yml b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..14955def60dd2a87de04a560b72cf32ad15a4582 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/_toctree.yml @@ -0,0 +1,123 @@ +- sections: + - local: index + title: 🤗 Accelerate + - local: basic_tutorials/install + title: Installation + - local: quicktour + title: Quicktour + title: Getting started +- sections: + - local: basic_tutorials/overview + title: Overview + - local: basic_tutorials/migration + title: Add Accelerate to your code + - local: basic_tutorials/execution + title: Execution process + - local: basic_tutorials/tpu + title: TPU training + - local: basic_tutorials/launch + title: Launching distributed code + - local: basic_tutorials/notebook + title: Launching distributed training from Jupyter Notebooks + title: Tutorials +- sections: + - isExpanded: true + sections: + - local: usage_guides/explore + title: Start Here! + - local: usage_guides/model_size_estimator + title: Model memory estimator + - local: usage_guides/quantization + title: Model quantization + - local: usage_guides/tracking + title: Experiment trackers + - local: usage_guides/profiler + title: Profiler + - local: usage_guides/checkpoint + title: Save and load training states + - local: basic_tutorials/troubleshooting + title: Troubleshoot + - local: usage_guides/training_zoo + title: Example Zoo + title: Accelerate + - isExpanded: true + sections: + - local: usage_guides/gradient_accumulation + title: Gradient accumulation + - local: usage_guides/local_sgd + title: Local SGD + - local: usage_guides/low_precision_training + title: Low precision (FP8) training + - local: usage_guides/deepspeed + title: DeepSpeed + - local: usage_guides/ddp_comm_hook + title: DDP Communication Hooks + - local: usage_guides/fsdp + title: Fully Sharded Data Parallelism + - local: usage_guides/megatron_lm + title: Megatron-LM + - local: usage_guides/sagemaker + title: Amazon SageMaker + - local: usage_guides/mps + title: Apple M1 GPUs + - local: usage_guides/ipex + title: IPEX training with CPU + title: Training + - isExpanded: true + sections: + - local: usage_guides/big_modeling + title: Big Model Inference + - local: usage_guides/distributed_inference + title: Distributed inference + title: Inference + title: How to guides +- sections: + - local: concept_guides/internal_mechanism + title: 🤗 Accelerate's internal mechanism + - local: concept_guides/big_model_inference + title: Loading big models into memory + - local: concept_guides/performance + title: Comparing performance across distributed setups + - local: concept_guides/deferring_execution + title: Executing and deferring jobs + - local: concept_guides/gradient_synchronization + title: Gradient synchronization + - local: concept_guides/fsdp_and_deepspeed + title: FSDP vs DeepSpeed + - local: concept_guides/low_precision_training + title: How training in low-precision environments is possible (FP8) + - local: concept_guides/training_tpu + title: TPU best practices + title: Concepts and fundamentals +- sections: + - local: package_reference/accelerator + title: Accelerator + - local: package_reference/state + title: Stateful configuration classes + - local: package_reference/cli + title: The Command Line + - local: package_reference/torch_wrappers + title: Torch wrapper classes + - local: package_reference/tracking + title: Experiment trackers + - local: package_reference/launchers + title: Distributed launchers + - local: package_reference/deepspeed + title: DeepSpeed utilities + - local: package_reference/logging + title: Logging + - local: package_reference/big_modeling + title: Working with large models + - local: package_reference/inference + title: Distributed inference with big models + - local: package_reference/kwargs + title: Kwargs handlers + - local: package_reference/fp8 + title: FP8 Functionality + - local: package_reference/utilities + title: Utility functions and classes + - local: package_reference/megatron_lm + title: Megatron-LM Utilities + - local: package_reference/fsdp + title: Fully Sharded Data Parallelism Utilities + title: "Reference" diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/execution.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/execution.md new file mode 100644 index 0000000000000000000000000000000000000000..4874f4439938ef18997f2cfb78f55c83fae70965 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/execution.md @@ -0,0 +1,128 @@ + + +# Execution process + +When working with distributed training systems, it is important to manage how and when processes are executed across GPUs. Some processes are completed faster than others, and some processes shouldn't begin if others haven't finished yet. Accelerate provides tools for orchestrating when processes are executed to ensure everything remains synchronized across all devices. + +This tutorial will teach you how to execute a process on only one machine and how to delay execution until all processes have reached a certain point. + +## Execute on one process + +Certain code only needs to be run once on a given machine, such as printing a log statement or only displaying one progress bar on the local main process. + + + + +You should use `accelerator.is_local_main_process` to indicate code that should only be executed once. + +```py +from tqdm.auto import tqdm + +progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) +``` + +You could also wrap a statement with `accelerator.is_local_main_process`. + +> [!TIP] +> For standalone `print` statements that aren't wrapped in `accelerator.is_local_main_process`, replace `print` with Accelerate's [`~Accelerator.print`] method to only print once per process. + +```py +if accelerator.is_local_main_process: + print("Accelerate is the best") +``` + + + + +For a function that should only be executed once, use [`~Accelerator.on_local_main_process`]. + +```py +@accelerator.on_local_main_process +def do_my_thing(): + "Something done once per server" + do_thing_once_per_server() +``` + + + + +You could also direct Accelerate to execute code once across *all processes* regardless of the number of machines. This is useful if you're uploading a final model to the Hub. + + + + +You should use `accelerator.is_main_process` to indicate code that should only be executed once across all processes. + +```py +if accelerator.is_main_process: + repo.push_to_hub() +``` + + + + +For a function that should only be executed once across all processes, use [`~Accelerator.on_main_process`]. + +```py +@accelerator.on_main_process +def do_my_thing(): + "Something done once per server" + do_thing_once() +``` + + + + +## Execute on a specific process + +Accelerate can also help you execute functions that should only be executed on a specific process or a local process index. + + + + +Use the [`~Accelerator.on_process`] method and specify the process index to execute a function on. + +```py +@accelerator.on_process(process_index=0) +def do_my_thing(): + "Something done on process index 0" + do_thing_on_index_zero() +``` + + + + +Use the [`~Accelerator.on_local_process`] method and specify the local process index to execute a function on. + +```py +@accelerator.on_local_process(local_process_idx=0) +def do_my_thing(): + "Something done on process index 0 on each server" + do_thing_on_index_zero_on_each_server() +``` + + + + +## Defer execution + +When you run your script on several GPUs at the same time, some code may be executed faster than others. You might need to wait for all processes to reach a certain point before executing the next set of instructions. For instance, you shouldn’t save a model before making sure every process is done with training. + +To do this, add [`~Accelerator.wait_for_everyone`] in your code. This blocks all processes that have finished first from continuing until all remaining processes have reached the same point (this has no effect if you're running on a single GPU or CPU). + +```py +accelerator.wait_for_everyone() +``` diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/install.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/install.md new file mode 100644 index 0000000000000000000000000000000000000000..d3e59516886add081d2e27121a08a26ed5874dad --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/install.md @@ -0,0 +1,102 @@ + + +# Installation and Configuration + +Before you start, you will need to setup your environment, install the appropriate packages, and configure 🤗 Accelerate. 🤗 Accelerate is tested on **Python 3.8+**. + +## Installing 🤗 Accelerate + +🤗 Accelerate is available on pypi and conda, as well as on GitHub. Details to install from each are below: + +### pip + +To install 🤗 Accelerate from pypi, perform: + +```bash +pip install accelerate +``` + +### conda + +🤗 Accelerate can also be installed with conda with: + +```bash +conda install -c conda-forge accelerate +``` + +### Source + +New features are added every day that haven't been released yet. To try them out yourself, install +from the GitHub repository: + +```bash +pip install git+https://github.com/huggingface/accelerate +``` + +If you're working on contributing to the library or wish to play with the source code and see live +results as you run the code, an editable version can be installed from a locally-cloned version of the +repository: + +```bash +git clone https://github.com/huggingface/accelerate +cd accelerate +pip install -e . +``` + +## Configuring 🤗 Accelerate + +After installing, you need to configure 🤗 Accelerate for how the current system is setup for training. +To do so run the following and answer the questions prompted to you: + +```bash +accelerate config +``` + +To write a barebones configuration that doesn't include options such as DeepSpeed configuration or running on TPUs, you can quickly run: + +```bash +python -c "from accelerate.utils import write_basic_config; write_basic_config(mixed_precision='fp16')" +``` +🤗 Accelerate will automatically utilize the maximum number of GPUs available and set the mixed precision mode. + +To check that your configuration looks fine, run: + +```bash +accelerate env +``` + +An example output is shown below, which describes two GPUs on a single machine with no mixed precision being used: + +```bash +- `Accelerate` version: 0.11.0.dev0 +- Platform: Linux-5.10.0-15-cloud-amd64-x86_64-with-debian-11.3 +- Python version: 3.7.12 +- Numpy version: 1.19.5 +- PyTorch version (GPU?): 1.12.0+cu102 (True) +- `Accelerate` default config: + - compute_environment: LOCAL_MACHINE + - distributed_type: MULTI_GPU + - mixed_precision: no + - use_cpu: False + - num_processes: 2 + - machine_rank: 0 + - num_machines: 1 + - main_process_ip: None + - main_process_port: None + - main_training_function: main + - deepspeed_config: {} + - fsdp_config: {} +``` \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/launch.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/launch.md new file mode 100644 index 0000000000000000000000000000000000000000..dfcab07b7b47ccbcc2a326a31e835fd963638f7e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/launch.md @@ -0,0 +1,232 @@ + + +# Launching your 🤗 Accelerate scripts + +In the previous tutorial, you were introduced to how to modify your current training script to use 🤗 Accelerate. +The final version of that code is shown below: + +```python +from accelerate import Accelerator + +accelerator = Accelerator() + +model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler +) + +for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() +``` + +But how do you run this code and have it utilize the special hardware available to it? + +First, you should rewrite the above code into a function, and make it callable as a script. For example: + +```diff + from accelerate import Accelerator + ++ def main(): + accelerator = Accelerator() + + model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler + ) + + for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() + ++ if __name__ == "__main__": ++ main() +``` + +Next, you need to launch it with `accelerate launch`. + + + + It's recommended you run `accelerate config` before using `accelerate launch` to configure your environment to your liking. + Otherwise 🤗 Accelerate will use very basic defaults depending on your system setup. + + + + +## Using accelerate launch + +🤗 Accelerate has a special CLI command to help you launch your code in your system through `accelerate launch`. +This command wraps around all of the different commands needed to launch your script on various platforms, without you having to remember what each of them is. + + + + If you are familiar with launching scripts in PyTorch yourself such as with `torchrun`, you can still do this. It is not required to use `accelerate launch`. + + + +You can launch your script quickly by using: + +```bash +accelerate launch {script_name.py} --arg1 --arg2 ... +``` + +Just put `accelerate launch` at the start of your command, and pass in additional arguments and parameters to your script afterward like normal! + +Since this runs the various torch spawn methods, all of the expected environment variables can be modified here as well. +For example, here is how to use `accelerate launch` with a single GPU: + +```bash +CUDA_VISIBLE_DEVICES="0" accelerate launch {script_name.py} --arg1 --arg2 ... +``` + +You can also use `accelerate launch` without performing `accelerate config` first, but you may need to manually pass in the right configuration parameters. +In this case, 🤗 Accelerate will make some hyperparameter decisions for you, e.g., if GPUs are available, it will use all of them by default without the mixed precision. +Here is how you would use all GPUs and train with mixed precision disabled: + +```bash +accelerate launch --multi_gpu {script_name.py} {--arg1} {--arg2} ... +``` + +Or by specifying a number of GPUs to use: + +```bash +accelerate launch --num_processes=2 {script_name.py} {--arg1} {--arg2} ... +``` + +To get more specific you should pass in the needed parameters yourself. For instance, here is how you +would also launch that same script on two GPUs using mixed precision while avoiding all of the warnings: + +```bash +accelerate launch --multi_gpu --mixed_precision=fp16 --num_processes=2 {script_name.py} {--arg1} {--arg2} ... +``` + +For a complete list of parameters you can pass in, run: + +```bash +accelerate launch -h +``` + + + + Even if you are not using 🤗 Accelerate in your code, you can still use the launcher for starting your scripts! + + + +For a visualization of this difference, that earlier `accelerate launch` on multi-gpu would look something like so with `torchrun`: + +```bash +MIXED_PRECISION="fp16" torchrun --nproc_per_node=2 --num_machines=1 {script_name.py} {--arg1} {--arg2} ... +``` + +You can also launch your script utilizing the launch CLI as a python module itself, enabling the ability to pass in other python-specific +launching behaviors. To do so, use `accelerate.commands.launch` instead of `accelerate launch`: + +```bash +python -m accelerate.commands.launch --num_processes=2 {script_name.py} {--arg1} {--arg2} +``` + +If you want to execute the script with any other python flags, you can pass them in as well similar to `-m`, such as +the below example enabling unbuffered stdout and stderr: + +```bash +python -u -m accelerate.commands.launch --num_processes=2 {script_name.py} {--arg1} {--arg2} +``` + + + + You can run your code on CPU as well! This is helpful for debugging and testing purposes on toy models and datasets. + +```bash +accelerate launch --cpu {script_name.py} {--arg1} {--arg2} +``` + + + +## Why you should always use `accelerate config` + +Why is it useful to the point you should **always** run `accelerate config`? + +Remember that earlier call to `accelerate launch` as well as `torchrun`? +Post configuration, to run that script with the needed parts you just need to use `accelerate launch` outright, without passing anything else in: + +```bash +accelerate launch {script_name.py} {--arg1} {--arg2} ... +``` + + +## Custom Configurations + +As briefly mentioned earlier, `accelerate launch` should be mostly used through combining set configurations +made with the `accelerate config` command. These configs are saved to a `default_config.yaml` file in your cache folder for 🤗 Accelerate. +This cache folder is located at (with decreasing order of priority): + +- The content of your environment variable `HF_HOME` suffixed with `accelerate`. +- If it does not exist, the content of your environment variable `XDG_CACHE_HOME` suffixed with + `huggingface/accelerate`. +- If this does not exist either, the folder `~/.cache/huggingface/accelerate`. + +To have multiple configurations, the flag `--config_file` can be passed to the `accelerate launch` command paired +with the location of the custom yaml. + +An example yaml may look something like the following for two GPUs on a single machine using `fp16` for mixed precision: +```yaml +compute_environment: LOCAL_MACHINE +deepspeed_config: {} +distributed_type: MULTI_GPU +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: fp16 +num_machines: 1 +num_processes: 2 +use_cpu: false +``` + +Launching a script from the location of that custom yaml file looks like the following: +```bash +accelerate launch --config_file {path/to/config/my_config_file.yaml} {script_name.py} {--arg1} {--arg2} ... +``` + +## Multi-node training +Multi-node training with 🤗Accelerate is similar to [multi-node training with torchrun](https://pytorch.org/tutorials/intermediate/ddp_series_multinode.html). The simplest way to launch a multi-node training run is to do the following: + +- Copy your codebase and data to all nodes. (or place them on a shared filesystem) +- Setup your python packages on all nodes. +- Run `accelerate config` on the main single node first. After specifying the number of nodes, you will be asked to specify the rank of each node (this will be 0 for the main/master node), along with the IP address and port for the main process. This is required for the worker nodes to communicate with the main process. Afterwards, you can copy or send this config file across all of your nodes, changing the `machine_rank` to 1, 2,3, etc. to avoid having to run the command (or just follow their directions directly for launching with `torchrun` as well) + +Once you have done this, you can start your multi-node training run by running `accelerate launch` (or `torchrun`) on all nodes. + + + It is required that the command be ran on all nodes for everything to start, not just running it from the main node. You can use something like SLURM or a different process executor to wrap around this requirement and call everything from a single command. + + + + + It is recommended to use the intranet IP of your main node over the public IP for better latency. This is the `192.168.x.x` or the `172.x.x.x` address you see when you run `hostname -I` on the main node. + + + +To get a better idea about multi-node training, check out our example for [multi-node training with FSDP](https://huggingface.co/blog/ram-efficient-pytorch-fsdp). diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/migration.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/migration.md new file mode 100644 index 0000000000000000000000000000000000000000..8fb2c32f981caa08170f2eb773fdbdcc428aff04 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/migration.md @@ -0,0 +1,227 @@ + + +# Add Accelerate to your code + +Each distributed training framework has their own way of doing things which can require writing a lot of custom code to adapt it to your PyTorch training code and training environment. Accelerate offers a friendly way to interface with these distributed training frameworks without having to learn the specific details of each one. Accelerate takes care of those details for you, so you can focus on the training code and scale it to any distributed training environment. + +In this tutorial, you'll learn how to adapt your existing PyTorch code with Accelerate and get you on your way toward training on distributed systems with ease! You'll start with a basic PyTorch training loop (it assumes all the training objects like `model` and `optimizer` have been setup already) and progressively integrate Accelerate into it. + +```python +device = "cuda" +model.to(device) + +for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) + loss.backward() + optimizer.step() + scheduler.step() +``` + +## Accelerator + +The [`Accelerator`] is the main class for adapting your code to work with Accelerate. It knows about the distributed setup you're using such as the number of different processes and your hardware type. This class also provides access to many of the necessary methods for enabling your PyTorch code to work in any distributed training environment and for managing and executing processes across devices. + +That's why you should always start by importing and creating an [`Accelerator`] instance in your script. + +```python +from accelerate import Accelerator + +accelerator = Accelerator() +``` + +The [`Accelerator`] also knows which device to move your PyTorch objects to, so it is recommended to let Accelerate handle this for you. + +```diff +- device = "cuda" ++ device = accelerator.device + model.to(device) +``` + +## Prepare PyTorch objects + +Next, you need to prepare your PyTorch objects (model, optimizer, scheduler, etc.) for distributed training. The [`~Accelerator.prepare`] method takes care of placing your model in the appropriate container (like single GPU or multi-GPU) for your training setup, adapting the optimizer and scheduler to use Accelerate's [`~optimizer.AcceleratedOptimizer`] and [`~scheduler.AcceleratedScheduler`], and creating a new dataloader that can be sharded across processes. + +> [!TIP] +> Accelerate only prepares objects that inherit from their respective PyTorch classes such as `torch.optim.Optimizer`. + +The PyTorch objects are returned in the same order they're sent. + +```py +model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler +) +``` + +## Training loop + +Finally, remove the `to(device)` calls to the inputs and targets in the training loop because Accelerate's DataLoader classes automatically places them on the right device. You should also replace the usual `backward()` pass with Accelerate's [`~Accelerator.backward`] method which scales the gradients for you and uses the appropriate `backward()` method depending on your distributed setup (for example, DeepSpeed or Megatron). + +```diff +- inputs = inputs.to(device) +- targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) +- loss.backward() ++ accelerator.backward(loss) +``` + +Put everything together and your new Accelerate training loop should now look like this! + +```python +from accelerate import Accelerator +accelerator = Accelerator() + +device = accelerator.device +model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler +) + +for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() +``` + +## Training features + +Accelerate offers additional features - like gradient accumulation, gradient clipping, mixed precision training and more - you can add to your script to improve your training run. Let's explore these three features. + +### Gradient accumulation + +Gradient accumulation enables you to train on larger batch sizes by accumulating the gradients over multiple batches before updating the weights. This can be useful for getting around memory limitations. To enable this feature in Accelerate, specify the `gradient_accumulation_steps` parameter in the [`Accelerator`] class and add the [`~Accelerator.accumulate`] context manager to your script. + +```diff ++ accelerator = Accelerator(gradient_accumulation_steps=2) + model, optimizer, training_dataloader = accelerator.prepare(model, optimizer, training_dataloader) + + for input, label in training_dataloader: ++ with accelerator.accumulate(model): + predictions = model(input) + loss = loss_function(predictions, label) + accelerator.backward(loss) + optimizer.step() + scheduler.step() + optimizer.zero_grad() +``` + +### Gradient clipping + +Gradient clipping is a technique to prevent "exploding gradients", and Accelerate offers: + +* [`~Accelerator.clip_grad_value_`] to clip gradients to a minimum and maximum value +* [`~Accelerator.clip_grad_norm_`] for normalizing gradients to a certain value + +### Mixed precision + +Mixed precision accelerates training by using a lower precision data type like fp16 (half-precision) to calculate the gradients. For the best performance with Accelerate, the loss should be computed inside your model (like in Transformers models) because computations outside of the model are computed in full precision. + +Set the mixed precision type to use in the [`Accelerator`], and then use the [`~Accelerator.autocast`] context manager to automatically cast the values to the specified data type. + +> [!WARNING] +> Accelerate enables automatic mixed precision, so [`~Accelerator.autocast`] is only needed if there are other mixed precision operations besides those performed on loss by [`~Accelerator.backward`] which already handles the scaling. + +```diff ++ accelerator = Accelerator(mixed_precision="fp16") ++ with accelerator.autocast(): + loss = complex_loss_function(outputs, target): +``` + +## Save and load + +Accelerate can also save and load a *model* once training is complete or you can also save the model and optimizer *state* which could be useful for resuming training. + +### Model + +Once all processes are complete, unwrap the model with the [`~Accelerator.unwrap_model`] method before saving it because the [`~Accelerator.prepare`] method wrapped your model into the proper interface for distributed training. If you don't unwrap the model, saving the model state dictionary also saves any potential extra layers from the larger model and you won't be able to load the weights back into your base model. + +You should use the [`~Accelerator.save_model`] method to unwrap and save the model state dictionary. This method can also save a model into sharded checkpoints or into the [safetensors](https://hf.co/docs/safetensors/index) format. + + + + +```py +accelerator.wait_for_everyone() +accelerator.save_model(model, save_directory) +``` + + + +For models from the [Transformers](https://hf.co/docs/transformers/index) library, save the model with the [`~transformers.PreTrainedModel.save_pretrained`] method so that it can be reloaded with the [`~transformers.PreTrainedModel.from_pretrained`] method. + +```py +from transformers import AutoModel + +unwrapped_model = accelerator.unwrap_model(model) +unwrapped_model.save_pretrained( + "path/to/my_model_directory", + is_main_process=accelerator.is_main_process, + save_function=accelerator.save, +) + +model = AutoModel.from_pretrained("path/to/my_model_directory") +``` + + + +To load your weights, use the [`~Accelerator.unwrap_model`] method to unwrap the model first before loading the weights. All model parameters are references to tensors, so this loads your weights inside `model`. + +```py +unwrapped_model = accelerator.unwrap_model(model) +path_to_checkpoint = os.path.join(save_directory,"pytorch_model.bin") +unwrapped_model.load_state_dict(torch.load(path_to_checkpoint)) +``` + + + + +Set `safe_serialization=True` to save the model in the safetensor format. + +```py +accelerator.wait_for_everyone() +accelerator.save_model(model, save_directory, max_shard_size="1GB", safe_serialization=True) +``` + +To load a sharded checkpoint or a safetensor formatted checkpoint, use the [`~accelerate.load_checkpoint_in_model`] method. This method allows you to load a checkpoint onto a specific device. + +```py +load_checkpoint_in_model(unwrapped_model, save_directory, device_map={"":device}) +``` + + + + +### State + +During training, you may want to save the current state of the model, optimizer, random generators, and potentially learning rate schedulers so they can be restored in the *same script*. You should add the [`~Accelerator.save_state`] and [`~Accelerator.load_state`] methods to your script to save and load states. + +To further customize where and how states are saved through [`~Accelerator.save_state`], use the [`~utils.ProjectConfiguration`] class. For example, if `automatic_checkpoint_naming` is enabled, each saved checkpoint is stored at `Accelerator.project_dir/checkpoints/checkpoint_{checkpoint_number}`. + +Any other stateful items to be stored should be registered with the [`~Accelerator.register_for_checkpointing`] method so they can be saved and loaded. Every object passed to this method to be stored must have a `load_state_dict` and `state_dict` function. + + + +If you have [`torchdata>=0.8.0`](https://github.com/pytorch/data/tree/main) installed, you can additionally pass `use_stateful_dataloader=True` into your [`~utils.DataLoaderConfiguration`]. This extends Accelerate's DataLoader classes with a `load_state_dict` and `state_dict` function, and makes it so `Accelerator.save_state` and `Accelerator.load_state` also track how far into the training dataset it has read when persisting the model. + + diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/notebook.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/notebook.md new file mode 100644 index 0000000000000000000000000000000000000000..805704116f39a61abd4fdf12f792243947026c9c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/notebook.md @@ -0,0 +1,476 @@ + + +# Launching Multi-GPU Training from a Jupyter Environment + +This tutorial teaches you how to fine tune a computer vision model with 🤗 Accelerate from a Jupyter Notebook on a distributed system. +You will also learn how to setup a few requirements needed for ensuring your environment is configured properly, your data has been prepared properly, and finally how to launch training. + + + + This tutorial is also available as a Jupyter Notebook [here](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_cv_example.ipynb) + + + +## Configuring the Environment + +Before any training can be performed, a 🤗 Accelerate config file must exist in the system. Usually this can be done by running the following in a terminal and answering the prompts: + +```bash +accelerate config +``` + +However, if general defaults are fine and you are *not* running on a TPU, 🤗Accelerate has a utility to quickly write your GPU configuration into a config file via [`utils.write_basic_config`]. + +The following code will restart Jupyter after writing the configuration, as CUDA code was called to perform this. + + + + CUDA can't be initialized more than once on a multi-GPU system. It's fine to debug in the notebook and have calls to CUDA, but in order to finally train a full cleanup and restart will need to be performed. + + + +```python +import os +from accelerate.utils import write_basic_config + +write_basic_config() # Write a config file +os._exit(00) # Restart the notebook +``` + +## Preparing the Dataset and Model + +Next you should prepare your dataset. As mentioned at earlier, great care should be taken when preparing the `DataLoaders` and model to make sure that **nothing** is put on *any* GPU. + +If you do, it is recommended to put that specific code into a function and call that from within the notebook launcher interface, which will be shown later. + +Make sure the dataset is downloaded based on the directions [here](https://github.com/huggingface/accelerate/tree/main/examples#simple-vision-example) + +```python +import os, re, torch, PIL +import numpy as np + +from torch.optim.lr_scheduler import OneCycleLR +from torch.utils.data import DataLoader, Dataset +from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor + +from accelerate import Accelerator +from accelerate.utils import set_seed +from timm import create_model +``` + +First you need to create a function to extract the class name based on a filename: + +```python +import os + +data_dir = "../../images" +fnames = os.listdir(data_dir) +fname = fnames[0] +print(fname) +``` + +```python out +beagle_32.jpg +``` + +In the case here, the label is `beagle`. Using regex you can extract the label from the filename: + +```python +import re + + +def extract_label(fname): + stem = fname.split(os.path.sep)[-1] + return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0] +``` + +```python +extract_label(fname) +``` + +And you can see it properly returned the right name for our file: + +```python out +"beagle" +``` + +Next a `Dataset` class should be made to handle grabbing the image and the label: + +```python +class PetsDataset(Dataset): + def __init__(self, file_names, image_transform=None, label_to_id=None): + self.file_names = file_names + self.image_transform = image_transform + self.label_to_id = label_to_id + + def __len__(self): + return len(self.file_names) + + def __getitem__(self, idx): + fname = self.file_names[idx] + raw_image = PIL.Image.open(fname) + image = raw_image.convert("RGB") + if self.image_transform is not None: + image = self.image_transform(image) + label = extract_label(fname) + if self.label_to_id is not None: + label = self.label_to_id[label] + return {"image": image, "label": label} +``` + +Now to build the dataset. Outside the training function you can find and declare all the filenames and labels and use them as references inside the +launched function: + +```python +fnames = [os.path.join("../../images", fname) for fname in fnames if fname.endswith(".jpg")] +``` + +Next gather all the labels: + +```python +all_labels = [extract_label(fname) for fname in fnames] +id_to_label = list(set(all_labels)) +id_to_label.sort() +label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)} +``` + +Next, you should make a `get_dataloaders` function that will return your built dataloaders for you. As mentioned earlier, if data is automatically +sent to the GPU or a TPU device when building your `DataLoaders`, they must be built using this method. + +```python +def get_dataloaders(batch_size: int = 64): + "Builds a set of dataloaders with a batch_size" + random_perm = np.random.permutation(len(fnames)) + cut = int(0.8 * len(fnames)) + train_split = random_perm[:cut] + eval_split = random_perm[cut:] + + # For training a simple RandomResizedCrop will be used + train_tfm = Compose([RandomResizedCrop((224, 224), scale=(0.5, 1.0)), ToTensor()]) + train_dataset = PetsDataset([fnames[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id) + + # For evaluation a deterministic Resize will be used + eval_tfm = Compose([Resize((224, 224)), ToTensor()]) + eval_dataset = PetsDataset([fnames[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id) + + # Instantiate dataloaders + train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4) + eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size * 2, num_workers=4) + return train_dataloader, eval_dataloader +``` + +Finally, you should import the scheduler to be used later: + +```python +from torch.optim.lr_scheduler import CosineAnnealingLR +``` + +## Writing the Training Function + +Now you can build the training loop. [`notebook_launcher`] works by passing in a function to call that will be ran across the distributed system. + +Here is a basic training loop for the animal classification problem: + + + + The code has been split up to allow for explanations on each section. A full version that can be copy and pasted will be available at the end + + + + +```python +def training_loop(mixed_precision="fp16", seed: int = 42, batch_size: int = 64): + set_seed(seed) + accelerator = Accelerator(mixed_precision=mixed_precision) +``` + +First you should set the seed and create an [`Accelerator`] object as early in the training loop as possible. + + + + If training on the TPU, your training loop should take in the model as a parameter and it should be instantiated + outside of the training loop function. See the [TPU best practices](../concept_guides/training_tpu) + to learn why + + + +Next you should build your dataloaders and create your model: + +```python + train_dataloader, eval_dataloader = get_dataloaders(batch_size) + model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) +``` + + + + You build the model here so that the seed also controls the new weight initialization + + + +As you are performing transfer learning in this example, the encoder of the model starts out frozen so the head of the model can be +trained only initially: + +```python + for param in model.parameters(): + param.requires_grad = False + for param in model.get_classifier().parameters(): + param.requires_grad = True +``` + +Normalizing the batches of images will make training a little faster: + +```python + mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None] + std = torch.tensor(model.default_cfg["std"])[None, :, None, None] +``` + +To make these constants available on the active device, you should set it to the Accelerator's device: + +```python + mean = mean.to(accelerator.device) + std = std.to(accelerator.device) +``` + +Next instantiate the rest of the PyTorch classes used for training: + +```python + optimizer = torch.optim.Adam(params=model.parameters(), lr=3e-2 / 25) + lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=3e-2, epochs=5, steps_per_epoch=len(train_dataloader)) +``` + +Before passing everything to [`~Accelerator.prepare`]. + + + + There is no specific order to remember, you just need to unpack the objects in the same order you gave them to the prepare method. + + + +```python + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) +``` + +Now train the model: + +```python + for epoch in range(5): + model.train() + for batch in train_dataloader: + inputs = (batch["image"] - mean) / std + outputs = model(inputs) + loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() +``` + +The evaluation loop will look slightly different compared to the training loop. The number of elements passed as well as the overall +total accuracy of each batch will be added to two constants: + +```python + model.eval() + accurate = 0 + num_elems = 0 +``` + +Next you have the rest of your standard PyTorch loop: + +```python + for batch in eval_dataloader: + inputs = (batch["image"] - mean) / std + with torch.no_grad(): + outputs = model(inputs) + predictions = outputs.argmax(dim=-1) +``` + +Before finally the last major difference. + +When performing distributed evaluation, the predictions and labels need to be passed through +[`~Accelerator.gather`] so that all of the data is available on the current device and a properly calculated metric can be achieved: + +```python + accurate_preds = accelerator.gather(predictions) == accelerator.gather(batch["label"]) + num_elems += accurate_preds.shape[0] + accurate += accurate_preds.long().sum() +``` + +Now you just need to calculate the actual metric for this problem, and you can print it on the main process using [`~Accelerator.print`]: + +```python + eval_metric = accurate.item() / num_elems + accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") +``` + +A full version of this training loop is available below: + +```python +def training_loop(mixed_precision="fp16", seed: int = 42, batch_size: int = 64): + set_seed(seed) + # Initialize accelerator + accelerator = Accelerator(mixed_precision=mixed_precision) + # Build dataloaders + train_dataloader, eval_dataloader = get_dataloaders(batch_size) + + # Instantiate the model (you build the model here so that the seed also controls new weight initaliziations) + model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) + + # Freeze the base model + for param in model.parameters(): + param.requires_grad = False + for param in model.get_classifier().parameters(): + param.requires_grad = True + + # You can normalize the batches of images to be a bit faster + mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None] + std = torch.tensor(model.default_cfg["std"])[None, :, None, None] + + # To make these constants available on the active device, set it to the accelerator device + mean = mean.to(accelerator.device) + std = std.to(accelerator.device) + + # Instantiate the optimizer + optimizer = torch.optim.Adam(params=model.parameters(), lr=3e-2 / 25) + + # Instantiate the learning rate scheduler + lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=3e-2, epochs=5, steps_per_epoch=len(train_dataloader)) + + # Prepare everything + # There is no specific order to remember, you just need to unpack the objects in the same order you gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now you train the model + for epoch in range(5): + model.train() + for batch in train_dataloader: + inputs = (batch["image"] - mean) / std + outputs = model(inputs) + loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + accurate = 0 + num_elems = 0 + for batch in eval_dataloader: + inputs = (batch["image"] - mean) / std + with torch.no_grad(): + outputs = model(inputs) + predictions = outputs.argmax(dim=-1) + accurate_preds = accelerator.gather(predictions) == accelerator.gather(batch["label"]) + num_elems += accurate_preds.shape[0] + accurate += accurate_preds.long().sum() + + eval_metric = accurate.item() / num_elems + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") +``` + +## Using the notebook_launcher + +All that's left is to use the [`notebook_launcher`]. + +You pass in the function, the arguments (as a tuple), and the number of processes to train on. (See the [documentation](../package_reference/launchers) for more information) + +```python +from accelerate import notebook_launcher +``` + +```python +args = ("fp16", 42, 64) +notebook_launcher(training_loop, args, num_processes=2) +``` + +In the case of running on multiple nodes, you need to set up a Jupyter session at each node and run the launching cell at the same time. + +For an environment containing 2 nodes (computers) with 8 GPUs each and the main computer with an IP address of "172.31.43.8", it would look like so: + +```python +notebook_launcher(training_loop, args, master_addr="172.31.43.8", node_rank=0, num_nodes=2, num_processes=8) +``` + +And in the second Jupyter session on the other machine: + + + + Notice how the `node_rank` has changed + + + +```python +notebook_launcher(training_loop, args, master_addr="172.31.43.8", node_rank=1, num_nodes=2, num_processes=8) +``` + +In the case of running on the TPU, it would look like so: + +```python +model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) + +args = (model, "fp16", 42, 64) +notebook_launcher(training_loop, args, num_processes=8) +``` + +To launch the training process with elasticity, enabling fault tolerance, you can use the `elastic_launch` feature provided by PyTorch. This requires setting additional parameters such as `rdzv_backend` and `max_restarts`. Here is an example of how to use `notebook_launcher` with elastic capabilities: + +```python +notebook_launcher( + training_loop, + args, + num_processes=2, + max_restarts=3 +) +``` + +As it's running it will print the progress as well as state how many devices you ran on. This tutorial was ran with two GPUs: + +```python out +Launching training on 2 GPUs. +epoch 0: 88.12 +epoch 1: 91.73 +epoch 2: 92.58 +epoch 3: 93.90 +epoch 4: 94.71 +``` + +And that's it! + +Please note that [`notebook_launcher`] ignores the 🤗 Accelerate config file, to launch based on the config use: + +```bash +accelerate launch +``` + +## Debugging + +A common issue when running the `notebook_launcher` is receiving a CUDA has already been initialized issue. This usually stems +from an import or prior code in the notebook that makes a call to the PyTorch `torch.cuda` sublibrary. To help narrow down what went wrong, +you can launch the `notebook_launcher` with `ACCELERATE_DEBUG_MODE=yes` in your environment and an additional check +will be made when spawning that a regular process can be created and utilize CUDA without issue. (Your CUDA code can still be ran afterwards). + +## Conclusion + +This notebook showed how to perform distributed training from inside of a Jupyter Notebook. Some key notes to remember: + +- Make sure to save any code that use CUDA (or CUDA imports) for the function passed to [`notebook_launcher`] +- Set the `num_processes` to be the number of devices used for training (such as number of GPUs, CPUs, TPUs, etc) +- If using the TPU, declare your model outside the training loop function diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/overview.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6a62e72da091d0066b7c30540e58ad3998210b98 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/overview.md @@ -0,0 +1,24 @@ + + +# Overview + +Welcome to the 🤗 Accelerate tutorials! These introductory guides will help catch you up to speed on working with 🤗 Accelerate. +You'll learn how to modify your code to have it work with the API seamlessly, how to launch your script properly, +and more! + +These tutorials assume some basic knowledge of Python and familiarity with the PyTorch framework. + +If you have any questions about 🤗 Accelerate, feel free to join and ask the community on our [forum](https://discuss.huggingface.co/c/accelerate/18). \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/tpu.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/tpu.md new file mode 100644 index 0000000000000000000000000000000000000000..f4780e3fe5f555b35d3d867fe0da071b49eb3c6a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/tpu.md @@ -0,0 +1,38 @@ + + +# TPU training + +A [TPU (Tensor Processing Unit)](https://cloud.google.com/tpu/docs/intro-to-tpu) is a type of hardware specifically designed for training models efficiently. Accelerate supports TPU training, but there are a few things you should be aware of, namely graph compilation. This tutorial briefly discusses compilation, and for more details, take a look at the [Training on TPUs with Accelerate](../concept_guides/training_tpu) guide. + +## Compilation + +A TPU creates a graph of all the operations in the training step such as the forward pass, backward pass and optimizer step. This is why the first training step always takes a while because building and compiling this graph takes time. But once compilation is complete, it is cached and all subsequent steps are much faster. + +The key is to avoid compiling your code again or else training is super slow. This means all your operations must be exactly the same: + +* all tensors in your batches must have the same length (for example, no dynamic padding for NLP tasks) +* your code must be static (for example, no layers with for loops that have different lengths depending on the input such as a LSTM) + +## Weight tying + +A common language model design is to tie the weights of the embedding and softmax layers. However, moving the model to a TPU (either yourself or passing it to the [`~Accelerator.prepare`] method) breaks the weight tying and you'll need to retie the weights. + +To add special behavior (like weight tying) in your script for TPUs, set [`~Accelerator.distributed_type`] to `DistributedType.TPU` first. Then you can use the [`~transformers.PreTrainedModel.tie_weights`] method to tie the weights. + +```py +if accelerator.distributed_type == DistributedType.TPU: + model.tie_weights() +``` diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/troubleshooting.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..6752bffc692d780885fab180d35a2fba1540b586 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/basic_tutorials/troubleshooting.md @@ -0,0 +1,211 @@ + + +# Troubleshoot + +This guide provides solutions to some issues you might encounter when using Accelerate. Not all errors are covered because Accelerate is an active library that is continuously evolving and there are many different use cases and distributed training setups. If the solutions described here don't help with your specific error, please take a look at the [Ask for help](#ask-for-help) section to learn where and how to get help. + +## Logging + +Logging can help you identify where an error is coming from. In a distributed setup with multiple processes, logging can be a challenge, but Accelerate provides the [`~accelerate.logging`] utility to ensure logs are synchronized. + +To troubleshoot an issue, use [`~accelerate.logging`] instead of the standard Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging) module. Set the verbosity level (`INFO`, `DEBUG`, `WARNING`, `ERROR`, `CRITICAL`) with the `log_level` parameter, and then you can either: + +1. Export the `log_level` as the `ACCELERATE_LOG_LEVEL` environment variable. +2. Pass the `log_level` directly to `get_logger`. + +For example, to set `log_level="INFO"`: + +```py +from accelerate.logging import get_logger + +logger = get_logger(__name__, log_level="DEBUG") +``` + +By default, the log is called on main processes only. To call it on all processes, pass `main_process_only=False`. +If a log should be called on all processes and in order, also pass `in_order=True`. + +```py +from accelerate.logging import get_logger + +logger = get_logger(__name__, log_level="DEBUG") +# log all processes +logger.debug("thing_to_log", main_process_only=False) +# log all processes in order +logger.debug("thing_to_log", main_process_only=False, in_order=True) +``` + +## Hanging code and timeout errors + +There can be many reasons why your code is hanging. Let's take a look at how to solve some of the most common issues that can cause your code to hang. + +### Mismatched tensor shapes + +Mismatched tensor shapes is a common issue that can cause your code to hang for a significant amount of time on a distributed setup. + +When running scripts in a distributed setup, functions such as [`Accelerator.gather`] and [`Accelerator.reduce`] are necessary to grab tensors across devices to collectively perform operations on them. These (and other) functions rely on `torch.distributed` to perform a `gather` operation, which requires tensors to have the **exact same shape** across all processes. When the tensor shapes don't match, your code hangs and you'll eventually hit a timeout exception. + +You can use Accelerate's operational debug mode to immediately catch this issue. We recommend enabling this mode during the `accelerate config` setup, but you can also enable it from the CLI, as an environment variable, or by manually editing the `config.yaml` file. + + + + +```bash +accelerate launch --debug {my_script.py} --arg1 --arg2 +``` + + + + +If enabling debug mode as an environment variable, you don't need to call `accelerate launch`. + +```bash +ACCELERATE_DEBUG_MODE="1" torchrun {my_script.py} --arg1 --arg2 +``` + + + + +Add `debug: true` to your `config.yaml` file. + +```yaml +compute_environment: LOCAL_MACHINE +debug: true +``` + + + + +Once you enable debug mode, you should get a traceback that points to the tensor shape mismatch issue. + +```py +Traceback (most recent call last): + File "/home/zach_mueller_huggingface_co/test.py", line 18, in + main() + File "/home/zach_mueller_huggingface_co/test.py", line 15, in main + broadcast_tensor = broadcast(tensor) + File "/home/zach_mueller_huggingface_co/accelerate/src/accelerate/utils/operations.py", line 303, in wrapper +accelerate.utils.operations.DistributedOperationException: + +Cannot apply desired operation due to shape mismatches. All shapes across devices must be valid. + +Operation: `accelerate.utils.operations.broadcast` +Input shapes: + - Process 0: [1, 5] + - Process 1: [1, 2, 5] +``` + +### Early stopping + +For early stopping in distributed training, if each process has a specific stopping condition (e.g. validation loss), it may not be synchronized across all processes. As a result, a break can happen on process 0 but not on process 1 which will cause your code to hang indefinitely until a timeout occurs. + +If you have early stopping conditionals, use the `set_breakpoint` and `check_breakpoint` methods to make sure all the processes +are ended correctly. + +```py +# Assume `should_do_breakpoint` is a custom defined function that returns a conditional, +# and that conditional might be true only on process 1 +if should_do_breakpoint(loss): + accelerator.set_breakpoint() + +# Later in the training script when we need to check for the breakpoint +if accelerator.check_breakpoint(): + break +``` + +### Low kernel versions on Linux + +On Linux with kernel version < 5.5, hanging processes have been reported. To avoid this problem, upgrade your system to a later kernel version. + +### MPI + +If your distributed CPU training job using MPI is hanging, ensure that you have +[passwordless SSH](https://www.open-mpi.org/faq/?category=rsh#ssh-keys) setup (using keys) between the nodes. This means +that for all nodes in your hostfile, you should to be able to SSH from one node to another without being prompted for a password. + +Next, try to run the `mpirun` command as a sanity check. For example, the command below should print out the +hostnames for each of the nodes. + +```bash +mpirun -f hostfile -n {number of nodes} -ppn 1 hostname +``` + +## CUDA Out-of-Memory + +One of the most frustrating errors when it comes to running training scripts is hitting "CUDA Out-of-Memory". The entire script needs to be restarted and any progress is lost. + +To address this problem, Accelerate provides the [`find_executable_batch_size`] utility that is heavily based on [toma](https://github.com/BlackHC/toma). +This utility retries code that fails due to OOM (out-of-memory) conditions and automatically lowers batch sizes. For each OOM condition, the algorithm decreases the batch size by half and retries the code until it succeeds. + +To use [`find_executable_batch_size`], restructure your training function to include an inner function with `find_executable_batch_size` and build your dataloaders inside it. At a minimum, this only takes 4 new lines of code. + + + +The inner function **must** take batch size as the first parameter, but we do not pass one to it when called. The wrapper will handles this for you. Any object (models, optimizers) that consumes CUDA memory and is passed to the [`Accelerator`] also **must** be declared inside the inner function. + + + +```diff +def training_function(args): + accelerator = Accelerator() + ++ @find_executable_batch_size(starting_batch_size=args.batch_size) ++ def inner_training_loop(batch_size): ++ nonlocal accelerator # Ensure they can be used in our context ++ accelerator.free_memory() # Free all lingering references + model = get_model() + model.to(accelerator.device) + optimizer = get_optimizer() + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + lr_scheduler = get_scheduler( + optimizer, + num_training_steps=len(train_dataloader)*num_epochs + ) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + train(model, optimizer, train_dataloader, lr_scheduler) + validate(model, eval_dataloader) ++ inner_training_loop() +``` + +## Non-reproducible results between device setups + +If you changed the device setup and observe different model performance, it is likely you didn't update your script when moving from one setup to another. Even if you're using the same script with the same batch size, the results will still be different on a TPU, multi-GPU, and single GPU. + +For example, if you were training on a single GPU with a batch size of 16 and you move to a dual GPU setup, you need to change the batch size to 8 to have the same effective batch size. This is because when training with Accelerate, the batch size passed to the dataloader is the **batch size per GPU**. + +To make sure you can reproduce the results between the setups, make sure to use the same seed, adjust the batch size accordingly, and consider scaling the learning rate. + +For more details and a quick reference for batch sizes, check out the [Comparing performance between different device setups](../concept_guides/performance) guide. + +## Performance issues on different GPUs + +If your multi-GPU setup consists of different GPUs, you may encounter some performance issues: + +- There may be an imbalance in GPU memory between the GPUs. In this case, the GPU with the smaller memory will limit the batch size or the size of the model that can be loaded onto the GPUs. +- If you are using GPUs with different performance profiles, the performance will be driven by the slowest GPU you are using because the other GPUs will have to wait for it to complete its workload. + +Vastly different GPUs within the same setup can lead to performance bottlenecks. + +## Ask for help + +If none of the solutions and advice here helped resolve your issue, you can always reach out to the community and Accelerate team for help. + +- Ask for help on the Hugging Face forums by posting your question in the [🤗 Accelerate category](https://discuss.huggingface.co/c/accelerate/18). Make sure to write a descriptive post with relevant context about your setup and reproducible code to maximize the likelihood that your problem is solved! + +- Post a question on [Discord](http://hf.co/join/discord), and let the team and the community help you. + +- Create an Issue on the 🤗 Accelerate [GitHub repository](https://github.com/huggingface/accelerate/issues) if you think you've found a bug related to the library. Include context regarding the bug and details about your distributed setup to help us better figure out what's wrong and how we can fix it. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/big_model_inference.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/big_model_inference.md new file mode 100644 index 0000000000000000000000000000000000000000..b2d8ab038ae0f4abdf985ff099dd1d27a0684869 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/big_model_inference.md @@ -0,0 +1,341 @@ + + +# Handling big models for inference + +When loading a pre-trained model in PyTorch, the usual workflow looks like this: + +```py +import torch + +my_model = ModelClass(...) +state_dict = torch.load(checkpoint_file) +my_model.load_state_dict(state_dict) +``` + +In plain English, those steps are: +1. Create the model with randomly initialized weights +2. Load the model weights (in a dictionary usually called a state dict) from the disk +3. Load those weights inside the model + +While this works very well for regularly sized models, this workflow has some clear limitations when we deal with a huge model: in step 1, we load a full version of the model in RAM, and spend some time randomly initializing the weights (which will be discarded in step 3). In step 2, we load another full version of the model in RAM, with the pre-trained weights. If you're loading a model with 6 billion parameters, this means you will need 24GB of RAM for each copy of the model, so 48GB in total (half of it to load the model in FP16). + + + +This API is quite new and still in its experimental stage. While we strive to provide a stable API, it's possible some small parts of the public API will change in the future. + + + +## How the Process Works: A Quick Overview + + + +## How the Process Works: Working with Code + +### Instantiating an empty model + +The first tool 🤗 Accelerate introduces to help with big models is a context manager [`init_empty_weights`] that helps you initialize a model without using any RAM so that step 1 can be done on models of any size. Here is how it works: + +```py +from accelerate import init_empty_weights + +with init_empty_weights(): + my_model = ModelClass(...) +``` + +For instance: + +```py +with init_empty_weights(): + model = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) +``` + +initializes an empty model with a bit more than 100B parameters. Behind the scenes, this relies on the meta device introduced in PyTorch 1.9. During the initialization under the context manager, each time a parameter is created, it is instantly moved to that device. + + + + You can't move a model initialized like this on CPU or another device directly, since it doesn't have any data. It's also very likely that a forward pass with that empty model will fail, as not all operations are supported on the meta device. + + + +### Sharded checkpoints + +It's possible your model is so big that even a single copy won't fit in RAM. That doesn't mean it can't be loaded: if you have one or several GPUs, this is more memory available to store your model. In this case, it's better if your checkpoint is split into several smaller files that we call checkpoint shards. + +🤗 Accelerate will handle sharded checkpoints as long as you follow the following format: your checkpoint should be in a folder, with several files containing the partial state dicts, and there should be an index in the JSON format that contains a dictionary mapping parameter names to the file containing their weights. You can easily shard your model with [`~Accelerator.save_model`]. For instance, we could have a folder containing: + +```bash +first_state_dict.bin +index.json +second_state_dict.bin +``` + +with index.json being the following file: + +``` +{ + "linear1.weight": "first_state_dict.bin", + "linear1.bias": "first_state_dict.bin", + "linear2.weight": "second_state_dict.bin", + "linear2.bias": "second_state_dict.bin" +} +``` + +and `first_state_dict.bin` containing the weights for `"linear1.weight"` and `"linear1.bias"`, `second_state_dict.bin` the ones for `"linear2.weight"` and `"linear2.bias"` + +### Loading weights + +The second tool 🤗 Accelerate introduces is a function [`load_checkpoint_and_dispatch`], that will allow you to load a checkpoint inside your empty model. This supports full checkpoints (a single file containing the whole state dict) as well as sharded checkpoints. It will also automatically dispatch those weights across the devices you have available (GPUs, CPU RAM), so if you are loading a sharded checkpoint, the maximum RAM usage will be the size of the biggest shard. + +If you want to use big model inference with 🤗 Transformers models, check out this [documentation](https://huggingface.co/docs/transformers/main/en/main_classes/model#large-model-loading). + +Here is how we can use this to load the [GPT2-1.5B](https://huggingface.co/marcsun13/gpt2-xl-linear-sharded) model. + +Let's download the sharded version of this model. + +```bash +pip install huggingface_hub +``` + +```py +from huggingface_hub import snapshot_download +checkpoint = "marcsun13/gpt2-xl-linear-sharded" +weights_location = snapshot_download(repo_id=checkpoint) +``` + +In order to initialize the model, we will use the library minGPT. + +```bash +git clone https://github.com/karpathy/minGPT.git +pip install minGPT/ +``` + +```py +from accelerate import init_empty_weights +from mingpt.model import GPT + +model_config = GPT.get_default_config() +model_config.model_type = 'gpt2-xl' +model_config.vocab_size = 50257 +model_config.block_size = 1024 + +with init_empty_weights(): + model = GPT(model_config) +``` + +Then, load the checkpoint we just downloaded with: + +```py +from accelerate import load_checkpoint_and_dispatch + +model = load_checkpoint_and_dispatch( + model, checkpoint=weights_location, device_map="auto", no_split_module_classes=['Block'] +) +``` + +By passing `device_map="auto"`, we tell 🤗 Accelerate to determine automatically where to put each layer of the model depending on the available resources: +- first, we use the maximum space available on the GPU(s) +- if we still need space, we store the remaining weights on the CPU +- if there is not enough RAM, we store the remaining weights on the hard drive as memory-mapped tensors + + +#### `no_split_module_classes` + +This parameter will indicate that some of the modules with the name `"Block"` should not be split across different devices. You should set here all blocks that +include a residual connection of some kind. + + +#### The `device_map` + +You can see the `device_map` that 🤗 Accelerate picked by accessing the `hf_device_map` attribute of your model: + +```py +model.hf_device_map +``` + +```python out +{'transformer.wte': 0, + 'transformer.wpe': 0, + 'transformer.drop': 0, + 'transformer.h.0': 0, + ... + 'transformer.h.21': 0, + 'transformer.h.22': 1, + 'transformer.h.23': 1, + 'transformer.h.24': 1, + ... + 'transformer.h.47': 1, + 'transformer.ln_f': 1, + 'lm_head': 1} + ``` + +It's fully possible to create your own device map for the layers to use as well, specifying the GPU device to use (a number), `"cpu"`, or `"disk"` and pass this in: + +```python +device_map = { + "transformer.wte": "cpu", + "transformer.wpe": 0, + "transformer.drop": "cpu", + "transformer.h.0": "disk" +} + +model = load_checkpoint_and_dispatch( + model, checkpoint=weights_location, device_map=device_map +) + +``` + +### Run the model + +Now that we have done this, our model lies across several devices, and maybe the hard drive. But it can still be used as a regular PyTorch model: + +```py +from mingpt.bpe import BPETokenizer +tokenizer = BPETokenizer() +inputs = tokenizer("Hello, my name is").to(0) + +outputs = model.generate(x1, max_new_tokens=10, do_sample=False)[0] +tokenizer.decode(outputs.cpu().squeeze()) +``` + +Behind the scenes, 🤗 Accelerate added hooks to the model, so that: +- at each layer, the inputs are put on the right device (so even if your model is spread across several GPUs, it works) +- for the weights offloaded on the CPU, they are put on a GPU just before the forward pass and cleaned up just after +- for the weights offloaded on the hard drive, they are loaded in RAM then put on a GPU just before the forward pass and cleaned up just after + +This way, your model can run for inference even if it doesn't fit on one of the GPUs or the CPU RAM! + + + + This only supports the inference of your model, not training. Most of the computation happens behind `torch.no_grad()` context managers to avoid spending some GPU memory with intermediate activations. + + + +### Designing a device map + +You can let 🤗 Accelerate handle the device map computation by setting `device_map` to one of the supported options (`"auto"`, `"balanced"`, `"balanced_low_0"`, `"sequential"`) or create one yourself if you want more control over where each layer should go. + + + + You can derive all sizes of the model (and thus compute a `device_map`) on a model that is on the meta device. + + + +All the options will produce the same result when you don't have enough GPU memory to accommodate the whole model (which is to fit everything that can on the GPU, then offload weights on the CPU or even on the disk if there is not enough RAM). + +When you have more GPU memory available than the model size, here is the difference between each option: +- `"auto"` and `"balanced"` evenly split the model on all available GPUs, making it possible for you to use a batch size greater than 1. +- `"balanced_low_0"` evenly splits the model on all GPUs except the first one, and only puts on GPU 0 what does not fit on the others. This option is great when you need to use GPU 0 for some processing of the outputs, like when using the `generate` function for Transformers models +- `"sequential"` will fit what it can on GPU 0, then move on GPU 1 and so forth (so won't use the last GPUs if it doesn't need to). + + + + The options `"auto"` and `"balanced"` produce the same results for now, but the behavior of `"auto"` might change in the future if we find a strategy that makes more sense, while `"balanced"` will stay stable. + + + +First note that you can limit the memory used on each GPU by using the `max_memory` argument (available in [`infer_auto_device_map`] and in all functions using it). When setting `max_memory`, you should pass along a dictionary containing the GPU identifiers (for instance `0`, `1` etc.) and the `"cpu"` key for the maximum RAM you want to use for CPU offload. The values can either be an integer (in bytes) or a string representing a number with its unit, such as `"10GiB"` or `"10GB"`. + +Here is an example where we don't want to use more than 10GiB on each of the two GPUs and no more than 30GiB of CPU RAM for the model weights: + +```python +from accelerate import infer_auto_device_map + +device_map = infer_auto_device_map(my_model, max_memory={0: "10GiB", 1: "10GiB", "cpu": "30GiB"}) +``` + + + + When a first allocation happens in PyTorch, it loads CUDA kernels which take about 1-2GB of memory depending on the GPU. Therefore you always have less usable memory than the actual size of the GPU. To see how much memory is actually used do `torch.ones(1).cuda()` and look at the memory usage. + + Therefore when you create memory maps with `max_memory` make sure to adjust the available memory accordingly to avoid out-of-memory errors. + + + +Additionally, if you do some additional operations with your outputs without placing them back on the CPU (for instance inside the `generate` method of Transformers) and if you placed your inputs on a GPU, that GPU will consume more memory than the others (Accelerate always place the output back to the device of the input). Therefore if you would like to optimize the maximum batch size and you have many GPUs, give the first GPU less memory. For example, with BLOOM-176B on 8x80 A100 setup, the close-to-ideal map is: + +```python +max_memory = {0: "30GIB", 1: "46GIB", 2: "46GIB", 3: "46GIB", 4: "46GIB", 5: "46GIB", 6: "46GIB", 7: "46GIB"} +``` +as you can see we gave the remaining 7 GPUs ~50% more memory than GPU 0. + +If you opt to fully design the `device_map` yourself, it should be a dictionary with keys being module names of your model and values being a valid device identifier (for instance an integer for the GPUs) or `"cpu"` for CPU offload, `"disk"` for disk offload. The keys need to cover the whole model, you can then define your device map as you wish: for instance, if your model has two blocks (let's say `block1` and `block2`) which each contain three linear layers (let's say `linear1`, `linear2` and `linear3`), a valid device map can be: + +```python +device_map = {"block1": 0, "block2": 1} +``` + +another one that is valid could be: + +```python +device_map = {"block1": 0, "block2.linear1": 0, "block2.linear2": 1, "block2.linear3": 1} +``` + +On the other hand, this one is not valid as it does not cover every parameter of the model: + +```python +device_map = {"block1": 0, "block2.linear1": 1, "block2.linear2": 1} +``` + + + + To be the most efficient, make sure your device map puts the parameters on the GPUs in a sequential manner (e.g. don't put one of the first weights on GPU 0, then weights on GPU 1 and the last weight back to GPU 0) to avoid making many transfers of data between the GPUs. + + + +## CPU offload only + +If you want to offload your model on CPU, you can use [`cpu_offload`]. As a result, all parameters of the model will be offloaded and only one copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that state dict and put on the execution device and passed as they are needed, then offloaded again. + +```python +cpu_offload(model, execution_device) +``` + +You can also use [`cpu_offload_with_hook`]. This function will offloads a model on the CPU and puts it back to an execution device when executed. The difference with [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when the `offload` method of the returned `hook` is called. Furthermore, [`cpu_offload_with_hook`] is more performant but less memory saving. It is useful for pipelines running a model in a loop: + +```python +model_1, hook_1 = cpu_offload_with_hook(model_1, execution_device) +model_2, hook_2 = cpu_offload_with_hook(model_2, execution_device, prev_module_hook=hook_1) +model_3, hook_3 = cpu_offload_with_hook(model_3, execution_device, prev_module_hook=hook_2) + +hid_1 = model_1(input) +for i in range(50): + # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop. + hid_2 = model_2(hid_1) +# model2 is offloaded to the CPU just before this forward. +hid_3 = model_3(hid_3) + +# For model3, you need to manually call the hook offload method. +hook_3.offload() +``` + +## Disk offload only + +To perform disk offload, you can use [`disk_offload`]. As a result, all parameters of the model will be offloaded as memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and put on the execution device passed as they are needed, then offloaded again. + +```python +disk_offload(model, offload_dir, execution_device) +``` + +## Limits and further development + +We are aware of the current limitations in the API: + +- [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) tries to maximize GPU and CPU RAM it sees available when you execute it. While PyTorch is very good at managing GPU RAM efficiently (and giving it back when not needed), it's not entirely true with Python and CPU RAM. Therefore, an automatically computed device map might be too intense on the CPU. Move a few modules to the disk device if you get crashes due to a lack of RAM. +- [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) attributes devices sequentially (to avoid moving things back and forth) so if your first layer is bigger than the size of the GPU you have, it will end up with everything on the CPU/Disk. +- [`load_checkpoint_and_dispatch`] and [`load_checkpoint_in_model`] do not perform any check on the correctness of your state dict compared to your model at the moment (this will be fixed in a future version), so you may get some weird errors if trying to load a checkpoint with mismatched or missing keys. +- The model parallelism used when your model is split on several GPUs is naive and not optimized, meaning that only one GPU works at a given time and the other sits idle. +- When weights are offloaded on the CPU/hard drive, there is no pre-fetching (yet, we will work on this for future versions) which means the weights are put on the GPU when they are needed and not before. +- Hard-drive offloading might be very slow if the hardware you run on does not have fast communication between disk and CPU (like NVMes). diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/deferring_execution.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/deferring_execution.md new file mode 100644 index 0000000000000000000000000000000000000000..f90b38e6a8bf49ade32765e4011f967d124fa235 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/deferring_execution.md @@ -0,0 +1,130 @@ + + +# Deferring Executions + +When you run your usual script, instructions are executed in order. Using 🤗 Accelerate to deploy your script on several +GPUs at the same time introduces a complication: while each process executes all instructions in order, some may be +faster than others. + +You might need to wait for all processes to have reached a certain point before executing a given instruction. For +instance, you shouldn't save a model before being sure every process is done with training, and you wouldn't want to +continue training before all the model weights have been loaded in. To do this, just write the following line in your code: + +``` +accelerator.wait_for_everyone() +``` + +This instruction will block all the processes that arrive first until all the other processes have reached that +point (if you run your script on just one GPU or CPU, this won't do anything). + +A few example cases of when to use this utility are listed below: + + + + Some of these are utilized with the [`~Accelerator.main_process_first`] context manager, which utilizes [`~Accelerator.wait_for_everyone`] to + run a particular set of code on the main process beforehand before triggering and launching the other processes + + + +## Downloading a Dataset + +When downloading a dataset, you should download it first on the main process and then load the cached dataset afterward + + + + `load_dataset` will perform a lock under the hood to stop multiple downloads from happening at once, but if you are downloading something + not using this library you should use this method. + + + +```python +with accelerator.main_process_first(): + datasets = load_dataset("glue", "mrpc") +``` + +Under the hood this is the same as calling: + +```python +# First do something on the main process +if accelerator.is_main_process: + datasets = load_dataset("glue", "mrpc") +else: + accelerator.wait_for_everyone() + +# And then send it to the rest of them +if not accelerator.is_main_process: + datasets = load_dataset("glue", "mrpc") +else: + accelerator.wait_for_everyone() +``` + +## Saving the `state_dict` + +When saving the `state_dict` of the model, since you would normally save one file on just the main process +you should specify that: + +```python +if accelerator.is_main_process: + model = accelerator.unwrap_model(model) + torch.save(model.state_dict(), "weights.pth") +``` + +## Loading in the `state_dict` + +When loading in the `state_dict` to a model, optimizer, or scheduler, you should wait +for all workers to have the weights loaded in before moving on to training + +```python +with accelerator.main_process_first(): + state = torch.load("weights.pth") + model.load_state_dict(state) +``` + +## Applying a multi-worker CPU operation + +Applying a `map()` operation on multiple workers, such as tokenizing should be done on the +main process first, and then propagated to each one. + +```python +datasets = load_dataset("glue", "mrpc") + +with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) +``` + +## Applying checks such as Early Stopping + +To have a check that works with a flag set by a particular process, the `set_trigger` and `check_trigger` API should be used. Useful examples +for doing so can include situations such as using early stopping and monitoring the loss (as each loss slightly differs on each process). + +Call [`Accelerator.set_trigger`] when your condition has been met, and [`Accelerator.check_trigger`] when checking if that condition has been met in any process: + +```python +for (x,y) in data_loader: + logits = model(x) + loss = loss_func(logits, y) + # Assume `should_do_early_stopping` is a custom defined function that returns a conditional + if should_do_early_stopping(loss): + accelerator.set_trigger() + + # Later in the training script when we need to check for the breakpoint + if accelerator.check_trigger(): + break +``` \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/fsdp_and_deepspeed.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/fsdp_and_deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..6665eb8885cb0ded847a2ef3446dd850efb2fca6 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/fsdp_and_deepspeed.md @@ -0,0 +1,192 @@ + + +# Moving between FSDP And DeepSpeed + +🤗 Accelerate offers flexibilty of training frameworks, by integrating two extremely powerful tools for distributed training, namely [Pytorch FSDP](../usage_guides/fsdp) and [Microsoft DeepSpeed](../usage_guides/deepspeed). The aim of this tutorial is to draw parallels, as well as to outline potential differences, to empower the user to switch seamlessly between these two frameworks. + + + + To switch between the frameworks, we recommend launching code 🤗 `accelerate launch` passing in the correct config file with `--config_file`, or passing in the respective arguments directly for [FSDP and DeepSpeed](../package_reference/cli#accelerate-launch) . + + Example 🤗 Accelerate configurations can be found here for [DeepSpeed](../usage_guides/deepspeed#accelerate-deepspeed-plugin) and [FSDP](../usage_guides/fsdp#how-it-works-out-of-the-box), or in the [example zoo under "Launch Configurations"](../usage_guides/explore) + + + + + +This tutorial is for single-node, multi-GPU, scenarios only. + + + +## Configuring Functionalities + +Model tensors are split into different GPUs in an attempt to scale up model sizes; this is termed *sharding* in FSDP, and *partitioning* in DeepSpeed. FSDP sharding and DeepSpeed ZeRO (partitioning) stages are configured by `--fsdp_sharding_strategy`, and `--zero_stage`, respectively. In particular, FSDP `FULL_SHARD` maps to DeepSpeed ZeRO stage `3`; see this [comprehensive mapping between FSDP sharding and DeepSpeed ZeRO settings](../usage_guides/fsdp#mapping-between-fsdp-sharding-strategies-and-deepspeed-zero-stages). The below table summarizes and groups similar settings: + +Group | Framework | Configuration | Example | Restrictions (if any) +--|--|--|--|-- +sharding / partitioning | FSDP
DeepSpeed | `--fsdp_sharding_strategy`
`--zero_stage` | `1` (`FULL_SHARD`)
`3` | +offload | FSDP
DeepSpeed | `--fsdp_offload_params`
`--offload_param_device`
`--offload_optimizer_device` | `true`
`cpu`
`cpu` | all or nothing

+model loading | FSDP
DeepSpeed | `--fsdp_cpu_ram_efficient_loading`
`--zero3_init_flag` | `true`
`true` |
only ZeRO 3 +efficient checkpointing | FSDP
DeepSpeed | `--fsdp_state_dict_type`
`--zero3_save_16bit_model` | `SHARDED_STATE_DICT`
`true` |
only ZeRO 3 +weights prefetching | FSDP

DeepSpeed | `--fsdp_forward_prefetch`
`--fsdp_backward_prefetch`
None | `true`
`BACKWARD_PRE` |

+model | FSDP

DeepSpeed | `--fsdp_auto_wrap_policy`
`--fsdp_transformer_layer_cls_to_wrap`
None | `TRANSFORMER_BASED_WRAP`
|
Usually not needed
Transparent to user. +parameters summoning | FSDP
DeepSpeed | `--fsdp_use_orig_params`
None | `true` | required for `torch.compile`
Transparent to user +parameters syncing | FSDP
DeepSpeed | `--fsdp_sync_module_states`
None | `true` | +training | FSDP
DeepSpeed | None
`--gradient_accumulation_steps`
`--gradient_clipping` |
`auto`
`auto` | Transparent to user + +For detailed descriptions of the above, refer to [🤗 `Accelerate` launch documentation](../package_reference/cli#accelerate-launch). + + + + To access other DeepSpeed configurations, such as mixed precision settings, + you need to pass in a `--deepspeed_config_file`, see the [documentation](../usage_guides/deepspeed#deepspeed-config-file). + + DeepSpeed can be also configured via [`DeepSpeedPlugin`], e.g., `DeepSpeedPlugin.zero_stage` is equivalent of `--zero_stage`, and `DeepSpeedPlugin.hf_ds_config` can be used to pass `--deepeed_config_file.` + + + + + + FSDP can be also configured via [`FullyShardedDataParallelPlugin`], e.g., `FullyShardedDataParallelPlugin.sharding_strategy` is equivalent of `--fsdp_sharding_strategy`. + + + +### Checkpointing + +Do note that while FSDP can be configured via `--fsdp_state_dict_type` to save either full / sharded checkpoints. + + + + For DeepSpeed Zero3, one could pass a `--zero3_save_16bit_model true`, which conveniently consolidates the model to a single rank and saves; this is the FSDP equivalent of `fsdp_state_dict_type: FULL_STATE_DICT`. + + + + + + For large models, consolidating the model to a single rank can be very slow. + + + + + + For quicker checkpointing, for FSDP use `fsdp_state_dict_type: SHARDED_STATE_DICT`, and for DeepSpeed Zero3 [use the `zero_to_fp32.py` script to post-convert sharded checkpoints](https://www.deepspeed.ai/tutorials/zero/#extracting-weights). + + + + +### Offloading + +FSDP only allows *all-or-nothing* offload (i.e., either offload parameters, gradients, and optimizer, or keep them all in GPU), but DeepSpeed can offload parameters and optimizer differently. Furthermore, DeepSpeed also supports [offloading to NVME](https://www.deepspeed.ai/docs/config-json/#parameter-offloading). + +### Prefetching + +FSDP allows two prefetching configurations `--fsdp_forward_prefetch` and `--fsdp_backward_prefetch` to improve overlap of comms / computation at a cost of extra memory, see [FSDP documentation](https://pytorch.org/docs/stable/fsdp.html). +For DeepSpeed, the prefetching will be turned on when needed, and it turns on depending on certain hyper-params like `stage3_param_persistence_threshold`, `stage3_max_reuse_distance`, etc, [that can be configured for Zero3](https://www.deepspeed.ai/docs/config-json/#parameter-offloading); 🤗 `accelerate` may set these hyper-params automatically if you don't set those explicitly in the deepspeed config file. + + + + For FSDP set `fsdp_backward_prefetch: BACKWARD_PRE` for improved throughputs if memory allows. + + + +### Model Loading + +While FSDP require an explicit `--fsdp_cpu_ram_efficient_loading true` to activate efficient model loading, 🤗 `transformers` will activate the similar feature whenever DeepSpeed Zero3 is used. + + + + For FSDP, whenever setting `--fsdp_cpu_ram_efficient_loading true`, 🤗 `accelerate` will automatically set `sync_module_states` to true. + For RAM efficient loading the weights will be loaded only in a singe rank, and thus requires `sync_module_states` to broadcast weights to other ranks. + + + +### Model + +FSDP requires an explicit `--fsdp_auto_wrap_policy` for the algorithm to decide how to schedule the all-gather and reduce-scatter operations. But for DeepSpeed this is transparent to the user. + + + + For FSDP, simply set `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP`. With the latest [`transformers`] versions, we try our best to figure out the suitable `fsdp_transformer_layer_cls_to_wrap` for HF transformers models. However, if you get an error regarding it, please specify this. + + + +### Parameters Summoning + +FSDP requires an explicit `--fsdp_use_orig_params` flag if using `torch.compile`, see [the pytorch documenation](https://pytorch.org/docs/stable/fsdp.html#module-torch.distributed.fsdp). For DeepSpeed this is transparent to the user. + + + + For FSDP, when using `torch.compile` please set `fsdp_use_orig_params: True`. + + + + +## Training + +Deepspeed requires explicit `--gradient_accumulation_steps` and `--gradient_clipping` flags. For FSDP this is transparent to the user. + + + + When using DeepSpeed, set `gradient_accumulation_steps: "auto"` and `gradient_clipping: "auto"` to automatically pick up values set in the [`Accelerator`] or [`TrainingArguments`] (if using `transformers`). + + + + +## On Differences in Data Precision Handling + +To discuss the how data precision is handled in both FSDP and Deepspeed, it is instructive to first give an overview of how model parameters are handled in these frameworks. Before the model / optimizer parameters are distributed across GPUs, parameter preparation is involved to first "flatten" them to one-dimensional [`torch.Tensor`](https://pytorch.org/docs/stable/tensors.html#torch-tensor). The implementation of FSDP / DeepSpeed varies in the respect of the `dtype` in which these "flattened" parameters are stored, and there are ramifications with regards to how [`torch.Optimizer`](https://pytorch.org/docs/stable/optim.html#module-torch.optim) allocate their `dtype`s. The table below outlines the processes for both frameworks; the "Local" column indicates the process occurring at a per-gpu level, therefore any memory overheads by upcasting should be understood to be amortized by the number of gpus used. + + + + As a rule of thumb, for stable training with automatic mixed precision, all the trainable parameters have to be in `torch.float32`. + + + +Process | Local | Framework | Details +--|--|--|-- +Loading, i.e., [`AutoModel.from_pretrained(..., torch_dtype=torch_dtype)`] | +Preparation, i.e., creation of "flat params" | ✅ | FSDP
DeepSpeed | created in `torch_dtype`.
disregards `torch_dtype`, created in `float32`. +Optimizer initialization | ✅ | FSDP
DeepSpeed | creates parameters in `torch_dtype`
creates parameters in `float32` +Training Step, i.e, forward, backward, reduction | | FSDP
DeepSpeed | follows [`MixedPrecision`](https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.MixedPrecision)
follows `deepspeed_config_file` mixed precision settings. +Optimizer (Pre-Step) | ✅ | FSDP
DeepSpeed | upcasting (if any) to `torch_dtype`
upcasted to `float32` +Optimizer (Actual Step) | ✅ | FSDP
DeepSpeed | occurs in `torch_dtype`
occurs in `float32`. + + + + Therefore when using DeepSpeed a small number of GPUs, be aware of potentially significant memory overheads due to the upcasting during preperation. + + + + + + With FSDP, in the absence of mixed precision, it is possible to operate the [`torch.Optimizer`](https://pytorch.org/docs/stable/optim.html#module-torch.optim) in low precision `torch_dtype`, which may be helpful when using small number of GPUs. + + + + + + With mixed precision, FSDP and DeepSpeed will upcast in the model preparation step (c.f. table above). But do note that FSDP will then save checkpoints in the upcasted precision; Deepspeed may still save low precision checkpoints if `--zero3_save_16bit_model` is specified. + + + + +To clarify the above table consider the concrete examples below; the optimizer pre- and actual step combined for brevity. With FSDP it is possible to operate in the two modes shown below, but DeepSpeed can only operate in one. + +Framework | Model Loading (`torch_dtype`) | Mixed Precision | Preparation (Local) | Training | Optimizer (Local) +--|--|--|--|--|-- +FSDP | bf16 | default (none) | bf16 | bf16 | bf16 +FSDP | bf16 | bf16 | fp32 | bf16 | fp32 +DeepSpeed | bf16 | bf16 | fp32 | bf16 | fp32 diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/gradient_synchronization.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/gradient_synchronization.md new file mode 100644 index 0000000000000000000000000000000000000000..d90ac29fd23ce3e805983e614ff35e8a50f2c832 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/gradient_synchronization.md @@ -0,0 +1,184 @@ + + +# Gradient Synchronization + +PyTorch's distributed module operates by communicating back and forth between all of the GPUs in your system. +This communication takes time, and ensuring all processes know the states of each other happens at particular triggerpoints +when using the `ddp` module. + +These triggerpoints are added to the PyTorch model, specifically their `forward()` and `backward()` methods. +This happens when the model is wrapped with `DistributedDataParallel`: +```python +import torch.nn as nn +from torch.nn.parallel import DistributedDataParallel + +model = nn.Linear(10, 10) +ddp_model = DistributedDataParallel(model) +``` +In 🤗 Accelerate this conversion happens automatically when calling [`~Accelerator.prepare`] and passing in your model. + +```diff ++ from accelerate import Accelerator ++ accelerator = Accelerator() + import torch.nn as nn +- from torch.nn.parallel import DistributedDataParallel + + model = nn.Linear(10,10) ++ model = accelerator.prepare(model) +``` + +## The slowdown in gradient accumulation + +You now understand that PyTorch adds hooks to the `forward` and `backward` method of your PyTorch model when +training in a distributed setup. But how does this risk slowing down your code? + +In DDP (distributed data parallel), the specific order in which processes are performed and ran are expected +at specific points and these must also occur at roughly the same time before moving on. + +The most direct example is when you update model parameters through +`optimizer.step()`. +Without gradient accumulation, all instances of the model need to have updated +their gradients computed, collated, and updated before moving on to the next +batch of data. +When performing gradient accumulation, you accumulate `n` loss gradients and +skip `optimizer.step()` until `n` batches have been reached. As all training +processes only need to synchronize by the time `optimizer.step()` is called, +without any modification to your training step, this needless inter-process +communication can cause a significant slowdown. + + How can you avoid this overhead? + +## Solving the slowdown problem + +Since you are skipping model parameter updates when training on these batches, their gradients do not need to be synchronized until the point where `optimizer.step()` is actually called. +PyTorch cannot automagically tell when you need to do this, but they do provide a tool to help through the [`no_sync`](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html#torch.nn.parallel.DistributedDataParallel.no_sync) context manager +that is added to your model after converting it to DDP. + +Under this context manager, PyTorch will skip synchronizing the gradients when +`.backward()` is called, and the first call to `.backward()` outside this +context manager will trigger the synchronization. See an example below: +```python +ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer) + +for index, batch in enumerate(dataloader): + inputs, targets = batch + # Trigger gradient synchronization on the last batch + if index != (len(dataloader) - 1): + with ddp_model.no_sync(): + # Gradients only accumulate + outputs = ddp_model(inputs) + loss = loss_func(outputs) + accelerator.backward(loss) + else: + # Gradients finally sync + outputs = ddp_model(inputs) + loss = loss_func(outputs) + accelerator.backward(loss) + optimizer.step() +``` + +In 🤗 Accelerate to make this an API that can be called no matter the training device (though it may not do anything if you are not in a distributed system!), +`ddp_model.no_sync` gets replaced with [`~Accelerator.no_sync`] and operates the same way: + +```diff + ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer) + + for index, batch in enumerate(dataloader): + inputs, targets = batch + # Trigger gradient synchronization on the last batch + if index != (len(dataloader)-1): +- with ddp_model.no_sync(): ++ with accelerator.no_sync(model): + # Gradients only accumulate + outputs = ddp_model(inputs) + loss = loss_func(outputs, targets) + accelerator.backward(loss) + else: + # Gradients finally sync + outputs = ddp_model(inputs) + loss = loss_func(outputs) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + +As you may expect, the [`~Accelerator.accumulate`] function wraps around this conditional check by keeping track of the current batch number, leaving you with the final +gradient accumulation API: + +```python +ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer) + +for batch in dataloader: + with accelerator.accumulate(model): + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + +As a result, you should either use *`accelerator.accumulate` or `accelerator.no_sync`* when it comes to API choice. + +## Just how much of a slowdown is there, and easy mistakes you can make + +To set up a realistic example, consider the following setup: + +* Two single-GPU T4 nodes and one node with two GPUs +* Each GPU is a T4, and are hosted on GCP +* The script used is a modification of the [NLP Example](https://github.com/muellerzr/timing_experiments/blob/main/baseline.py) script +* Batch size per GPU is 16, and gradients are accumulated every 4 steps + +All scripts are available in [this repository](https://github.com/muellerzr/timing_experiments). + +If not careful about gradient synchronization and GPU communication, a *large* amount of time can be wasted +from when these GPUs communicate to each other during unnecessary periods. + +By how much? + +Reference: +- Baseline: uses no synchronization practices discussed here +- `no_sync` improperly: `no_sync` only around the `backward` call, not the `forward` +- `no_sync`: using the `no_sync` pattern properly +- `accumulate`: using [`~Accelerator.accumulate`] properly + +Below are the average seconds per batch iterating over 29 batches of data for each setup on both a single node and on the dual-node setup: + +| | Baseline | `no_sync` improperly | `no_sync` | `accumulate`| +| :---------: | :-------: | :------------------: | :-------: | :---------: | +| Multi-Node | 2±0.01s | 2.13±0.08s | **0.91±0.11s** | **0.91±0.11s** | +| Single Node | 0.50±0.01s | 0.50±0.01s | **0.41±0.015s** | **0.41±0.015s** | + +As you can see, if you are not careful about how you set up your gradient synchronization, you can get upwards of more than a 2x slowdown during training! + +If you are worried about making sure everything is done properly, we highly recommend utilizing the [`~Accelerator.accumulate`] function and passing in +`gradient_accumulation_steps` or `gradient_accumulation_plugin` to the [`Accelerator`] object so Accelerate can handle this for you. + +### `no_sync` requires additional GPU memory when using FSDP + +Be aware that not syncing gradients can have adverse effects while performing FSDP training. As it has been warned in `torch`, the [`no_sync` context manager for FSDP](https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.FullyShardedDataParallel.no_sync) will require additional memory. + +Therefore in memory intensive situations while using FSDP, we recommend to set `sync_each_batch` to `True` in the [`~utils.GradientAccumulationPlugin`] to disable `no_sync`. + +See the example below where we fine-tune Mixtral (47B parameters) on 8 A100-80GB GPUs. We see that even for a modest `gradient_accumulation_steps=2` we quickly go out-of-memory (OOM) if `no_sync` is enabled. Again, this is due to additional memory overheads due to FSDP's `no_sync`. However, if `no_sync` is disabled via `sync_each_batch=True`, then the memory consumption for `gradient_accumulation_steps=16` reverts to that of `gradient_accumulation_steps=1`. + +| Model | `no_sync` (accum=1) | `no_sync` (accum=2) | `no_sync` disabled (accum=16) +| :-------------: | :-----------------: | :-----------------: | :-----------------: +mixtral 8x7B | 69G | OOM | 69G + +> [!WARNING] +> Disabling `no_sync` means there _will be slowdown_ due the extra data syncs, as explained by the earlier sections of this guide. \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/internal_mechanism.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/internal_mechanism.md new file mode 100644 index 0000000000000000000000000000000000000000..2410d882bb52acc4371b01af7ec588d1d4c92d37 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/internal_mechanism.md @@ -0,0 +1,78 @@ + + +# 🤗 Accelerate's internal mechanisms + +Internally, 🤗 Accelerate works by first analyzing the environment in which the script is launched to determine which +kind of distributed setup is used, how many different processes there are and which one the current script is in. All +that information is stored in the [`~AcceleratorState`]. + +This class is initialized the first time you instantiate an [`~Accelerator`] as well as performing any +specific initialization your distributed setup needs. Its state is then uniquely shared through all instances of +[`~state.AcceleratorState`]. (The same can also be done with the [`PartialState`], a more barebones version it inherits) + +Then, when calling [`~Accelerator.prepare`], the library: + +- wraps your model(s) in the container adapted for the distributed setup, +- wraps your optimizer(s) in an [`~optimizer.AcceleratedOptimizer`], +- wraps your scheduler(s) in an [`~scheduler.AcceleratedScheduler`] +- creates a new version of your dataloader(s) in a [`~data_loader.DataLoaderShard`] or [`~data_loader.DataLoaderDispatcher`] + +While the model(s), optimizer(s), and scheduler(s) are just put in simple wrappers, the dataloader(s) are re-created. This is mostly +because PyTorch does not let the user change the `batch_sampler` of a dataloader once it's been created and the +library handles the sharding of your data between processes by changing that `batch_sampler` to yield every other +`num_processes` batches (if enabled). + +The [`~data_loader.DataLoaderShard`] subclasses `DataLoader` to add the following functionality: + +- it synchronizes the appropriate random number generator of all processes at each new iteration, to ensure any + randomization (like shuffling) is done the exact same way across processes. +- it puts the batches on the proper device before yielding them (unless you have opted out of + `device_placement=True`). + +The [`~data_loader.DataLoaderDispatcher`] subclasses differs from the [`~data_loader.DataLoaderShard`] in that when iterating through the `DataLoader`, the data is all starting from process 0 and *then* split and sent off to each process rather than it happening at the dataset level. + +The random number generator synchronization will by default synchronize: + +- the `generator` attribute of a given sampler (like the PyTorch `RandomSampler`) for PyTorch >= 1.6 +- the main random number generator in PyTorch <=1.5.1 + +You can choose which random number generator(s) to synchronize with the `rng_types` argument of the main +[`Accelerator`]. In PyTorch >= 1.6, it is recommended to rely on a local `generator` to avoid +setting the same seed in the main random number generator in all processes. + + + + Synchronization of the main torch (or CUDA or XLA) random number generator will affect any other potential random + artifacts you could have in your dataset (like random data augmentation) in the sense that all processes will get + the same random numbers from the torch random modules (so will apply the same random data augmentation if it's + controlled by torch). + + + + + + The randomization part of your custom sampler, batch sampler or iterable dataset should be done using a local + `torch.Generator` object (in PyTorch >= 1.6), see the traditional `RandomSampler`, as an example. + + + + + +If you have [`torchdata>=0.8.0`](https://github.com/pytorch/data/tree/main) installed, and you have passed `use_stateful_dataloader=True` into your [`~utils.DataLoaderConfiguration`], these classes will directly inherit from `StatefulDataLoader` instead, and maintain a `state_dict`. + + + +For more details about the internals, see the [Internals page](package_reference/torch_wrappers). diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/low_precision_training.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/low_precision_training.md new file mode 100644 index 0000000000000000000000000000000000000000..2d8df0ca4e747b8d7cc42c04284b3d6a5ca2bf8d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/low_precision_training.md @@ -0,0 +1,74 @@ + + +# Low Precision Training Methods + +The release of new kinds of hardware led to the emergence of new training paradigms that better utilize them. Currently, this is in the form of training +in 8-bit precision using packages such as [TransformersEngine](https://github.com/NVIDIA/TransformerEngine) (TE) or [MS-AMP](https://github.com/Azure/MS-AMP/tree/main). + +For an introduction to the topics discussed today, we recommend reviewing the [low-precision usage guide](../usage_guides/low_precision_training) as this documentation will reference it regularly. + +## A Quick Chart + +Below is a quick chart from the MS-AMP documentation showing the different bit-precisions for each solution during training: + +Optimization Level | Computation(GEMM) | Comm | Weight | Master Weight | Weight Gradient | Optimizer States +-- | -- | -- | -- | -- | -- | -- +FP16 AMP | FP16 | FP32 | FP32 | N/A | FP32 | FP32+FP32 +Nvidia TE | FP8 | FP32 | FP32 | N/A | FP32 | FP32+FP32 +MS-AMP O1 | FP8 | FP8 | FP16 | N/A | FP8 | FP32+FP32 +MS-AMP O2 | FP8 | FP8 | FP16 | N/A | FP8 | FP8+FP16 +MS-AMP O3 | FP8 | FP8 | FP8 | FP16 | FP8 | FP8+FP16 + +## `TransformersEngine` + +`TransformersEngine` is the first solution to trying to train in 8-bit floating point. It works by using drop-in replacement layers for certain ones in a model that utilizes their FP8-engine to reduce the number of bits (such as 32 to 8) without degrading the final accuracy of the model. + +Specifically, 🤗 Accelerate will find and replace the following layers with `TransformersEngine` versions: + +* `nn.LayerNorm` for `te.LayerNorm` +* `nn.Linear` for `te.Linear` + +As a result we wind up with a model that has most of its layers in BF16, while some layers are in FP8 reducing some of the memory. + +Anecdotally, we have noticed that performance gains don't really start showing when using `TransformerEngine` until a large majority of the layers +in the model are made up of those two layers to replace. As a result, only larger models have shown performance improvements when the number of parameters is around and upwards of a few billion. + +The `TransformerEngine` can receive many different arguments that customize how it performs FP8 calculations and what they do. A full list of the arguments is available below: + +* `margin`: The margin to use for the gradient scaling. +* `interval`: The interval to use for how often the scaling factor is recomputed. +* `fp8_format``: The format to use for the FP8 recipe. Must be one of `HYBRID` or `E4M3`. (Generally `HYBRID` for training, `E4M3` for evaluation) +* `amax_history_len`: The length of the history to use for the scaling factor computation +* `amax_compute_algo`: The algorithm to use for the scaling factor computation. Must be one of `max` or `most_recent`. +* `override_linear_precision`: Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. + +You can customize each of these as part of [`utils.FP8RecipeKwargs`] to help optimize performance of your models. + +If we notice in the chart mentioned earlier, TE simply casts the computation layers into FP8, while everything else is in FP32. As a result this winds up utilizing the most memory but does so with the benefit of guaranteeing the least amount of loss in end accuracy during training. + +## `MS-AMP` + +MS-AMP takes a different approach to `TransformersEngine` by providing three different optimization levels to convert more operations in FP8 or FP16. + +* The base optimization level (`O1`), passes communications of the weights (such as in DDP) in FP8, stores the weights of the model in FP16, and leaves the optimizer states in FP32. The main benefit of this optimization level is that we can reduce the communication bandwidth by essentially half. Additionally, more GPU memory is saved due to 1/2 of everything being cast in FP8, and the weights being cast to FP16. Notably, both the optimizer states remain in FP32. + +* The second optimization level (`O2`) improves upon this by also reducing the precision of the optimizer states. One is in FP8 while the other is in FP16. Generally it's been shown that this will only provide a net-gain of no degraded end accuracy, increased training speed, and reduced memory as now every state is either in FP16 or FP8. + +* Finally, MS-AMP has a third optimization level (`O3`) which helps during DDP scenarios such as DeepSpeed. The weights of the model in memory are fully cast to FP8, and the master weights are now stored in FP16. This fully reduces memory by the highest factor as now not only is almost everything in FP8, only two states are left in FP16. Currently, only DeepSpeed versions up through 0.9.2 are supported, so this capability is not included in the 🤗 Accelerate integration + +## Combining the two + +More experiments need to be performed but it's been noted that combining both MS-AMP and TransformersEngine can lead to the highest throughput by relying on NVIDIA's optimized FP8 operators and utilizing how MS-AMP reduces the memory overhead. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/performance.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/performance.md new file mode 100644 index 0000000000000000000000000000000000000000..8b11200536580b26c129ac2089b6ae5f37978cdd --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/performance.md @@ -0,0 +1,103 @@ + + +# Comparing performance between different device setups + +Evaluating and comparing the performance from different setups can be quite tricky if you don't know what to look for. +For example, you cannot run the same script with the same batch size across TPU, multi-GPU, and single-GPU with Accelerate +and expect your results to line up. + +But why? + +There are three reasons for this that this tutorial will cover: + +1. **Setting the right seeds** +2. **Observed Batch Sizes** +3. **Learning Rates** + +## Setting the Seed + +While this issue has not come up as much, make sure to use [`utils.set_seed`] to fully set the seed in all distributed cases so training will be reproducible: + +```python +from accelerate.utils import set_seed + +set_seed(42) +``` + +Why is this important? Under the hood this will set **5** different seed settings: + +```python + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + # ^^ safe to call this function even if cuda is not available + if is_torch_xla_available(): + xm.set_rng_state(seed) +``` + +The random state, numpy's state, torch, torch's cuda state, and if TPUs are available torch_xla's cuda state. + +## Observed Batch Sizes + +When training with Accelerate, the batch size passed to the dataloader is the **batch size per GPU**. What this entails is +a batch size of 64 on two GPUs is truly a batch size of 128. As a result, when testing on a single GPU this needs to be accounted for, +as well as similarly for TPUs. + +The below table can be used as a quick reference to try out different batch sizes: + + + +In this example, there are two GPUs for "Multi-GPU" and a TPU pod with 8 workers + + + +| Single GPU Batch Size | Multi-GPU Equivalent Batch Size | TPU Equivalent Batch Size | +|-----------------------|---------------------------------|---------------------------| +| 256 | 128 | 32 | +| 128 | 64 | 16 | +| 64 | 32 | 8 | +| 32 | 16 | 4 | + +## Learning Rates + +As noted in multiple sources[[1](https://aws.amazon.com/blogs/machine-learning/scalable-multi-node-deep-learning-training-using-gpus-in-the-aws-cloud/)][[2](https://docs.nvidia.com/clara/clara-train-sdk/pt/model.html#classification-models-multi-gpu-training)], the learning rate should be scaled *linearly* based on the number of devices present. The below +snippet shows doing so with Accelerate: + + + +Since users can have their own learning rate schedulers defined, we leave this up to the user to decide if they wish to scale their +learning rate or not. + + + +```python +learning_rate = 1e-3 +accelerator = Accelerator() +learning_rate *= accelerator.num_processes + +optimizer = AdamW(params=model.parameters(), lr=learning_rate) +``` + +You will also find that `accelerate` will step the learning rate based on the number of processes being trained on. This is because +of the observed batch size noted earlier. So in the case of 2 GPUs, the learning rate will be stepped twice as often as a single GPU +to account for the batch size being twice as large (if no changes to the batch size on the single GPU instance are made). + +## Gradient Accumulation and Mixed Precision + +When using gradient accumulation and mixed precision, due to how gradient averaging works (accumulation) and the precision loss (mixed precision), +some degradation in performance is expected. This will be explicitly seen when comparing the batch-wise loss between different compute +setups. However, the overall loss, metric, and general performance at the end of training should be _roughly_ the same. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/training_tpu.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/training_tpu.md new file mode 100644 index 0000000000000000000000000000000000000000..45c10f0384fdfcc272a2103a314b2bfb61632a44 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/concept_guides/training_tpu.md @@ -0,0 +1,167 @@ + + +# Training on TPUs with 🤗 Accelerate + +Training on TPUs can be slightly different from training on multi-gpu, even with 🤗 Accelerate. This guide aims to show you +where you should be careful and why, as well as the best practices in general. + +## Training in a Notebook + +The main carepoint when training on TPUs comes from the [`notebook_launcher`]. As mentioned in the [notebook tutorial](../usage_guides/notebook), you need to +restructure your training code into a function that can get passed to the [`notebook_launcher`] function and be careful about not declaring any tensors on the GPU. + +While on a TPU that last part is not as important, a critical part to understand is that when you launch code from a notebook you do so through a process called **forking**. +When launching from the command-line, you perform **spawning**, where a python process is not currently running and you *spawn* a new process in. Since your Jupyter notebook is already +utilizing a python process, you need to *fork* a new process from it to launch your code. + +Where this becomes important is in regard to declaring your model. On forked TPU processes, it is recommended that you instantiate your model *once* and pass this into your +training function. This is different than training on GPUs where you create `n` models that have their gradients synced and back-propagated at certain moments. Instead, one +model instance is shared between all the nodes and it is passed back and forth. This is important especially when training on low-resource TPUs such as those provided in Kaggle kernels or +on Google Colaboratory. + +Below is an example of a training function passed to the [`notebook_launcher`] if training on CPUs or GPUs: + + + + This code snippet is based off the one from the `simple_nlp_example` notebook found [here](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb) with slight + modifications for the sake of simplicity + + + +```python +def training_function(): + # Initialize accelerator + accelerator = Accelerator() + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2) + train_dataloader, eval_dataloader = create_dataloaders( + train_batch_size=hyperparameters["train_batch_size"], eval_batch_size=hyperparameters["eval_batch_size"] + ) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=hyperparameters["learning_rate"]) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader + ) + + num_epochs = hyperparameters["num_epochs"] + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + + optimizer.step() + optimizer.zero_grad() +``` + +```python +from accelerate import notebook_launcher + +notebook_launcher(training_function) +``` + + + + The `notebook_launcher` will default to 8 processes if 🤗 Accelerate has been configured for a TPU + + + +If you use this example and declare the model *inside* the training loop, then on a low-resource system you will potentially see an error +like: + +``` +ProcessExitedException: process 0 terminated with signal SIGSEGV +``` + +This error is *extremely* cryptic but the basic explanation is you ran out of system RAM. You can avoid this entirely by reconfiguring the training function to +accept a single `model` argument, and declare it in an outside cell: + +```python +# In another Jupyter cell +model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2) +``` + +```diff ++ def training_function(model): + # Initialize accelerator + accelerator = Accelerator() +- model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2) + train_dataloader, eval_dataloader = create_dataloaders( + train_batch_size=hyperparameters["train_batch_size"], eval_batch_size=hyperparameters["eval_batch_size"] + ) + ... +``` + +And finally calling the training function with: + +```diff + from accelerate import notebook_launcher +- notebook_launcher(training_function) ++ notebook_launcher(training_function, (model,)) +``` + + + + The above workaround is only needed when launching a TPU instance from a Jupyter Notebook on a low-resource server such as Google Colaboratory or Kaggle. If + using a script or launching on a much beefier server declaring the model beforehand is not needed. + + + +## Mixed Precision and Global Variables + +As mentioned in the [mixed precision tutorial](../usage_guides/mixed_precision), 🤗 Accelerate supports fp16 and bf16, both of which can be used on TPUs. +That being said, ideally `bf16` should be utilized as it is extremely efficient to use. + +There are two "layers" when using `bf16` and 🤗 Accelerate on TPUs, at the base level and at the operation level. + +At the base level, this is enabled when passing `mixed_precision="bf16"` to `Accelerator`, such as: +```python +accelerator = Accelerator(mixed_precision="bf16") +``` +By default, this will cast `torch.float` and `torch.double` to `bfloat16` on TPUs. +The specific configuration being set is an environmental variable of `XLA_USE_BF16` is set to `1`. + +There is a further configuration you can perform which is setting the `XLA_DOWNCAST_BF16` environmental variable. If set to `1`, then +`torch.float` is `bfloat16` and `torch.double` is `float32`. + +This is performed in the `Accelerator` object when passing `downcast_bf16=True`: +```python +accelerator = Accelerator(mixed_precision="bf16", downcast_bf16=True) +``` + +Using downcasting instead of bf16 everywhere is good for when you are trying to calculate metrics, log values, and more where raw bf16 tensors would be unusable. + +## Training Times on TPUs + +As you launch your script, you may notice that training seems exceptionally slow at first. This is because TPUs +first run through a few batches of data to see how much memory to allocate before finally utilizing this configured +memory allocation extremely efficiently. + +If you notice that your evaluation code to calculate the metrics of your model takes longer due to a larger batch size being used, +it is recommended to keep the batch size the same as the training data if it is too slow. Otherwise the memory will reallocate to this +new batch size after the first few iterations. + + + + Just because the memory is allocated does not mean it will be used or that the batch size will increase when going back to your training dataloader. + + diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/accelerate_logo.png b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/accelerate_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..c8d2659132eb4b4b6c0e5438335477720e89198e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/accelerate_logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ab00c5c1a233390ec3161c39b7c2d529043f1eddc7f66954392f614d5d7a81d +size 12653 diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/course_banner.png b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/course_banner.png new file mode 100644 index 0000000000000000000000000000000000000000..95093b20769aabaffc86b26e7d92ebf1022a41be --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/course_banner.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:809c043430c67617f0f1b1551f51cee564a4b3cce938d34b4eb478dc94a63280 +size 80305 diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/profile_export.png b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/profile_export.png new file mode 100644 index 0000000000000000000000000000000000000000..39fff39eaaf06a7daa2a5cba90b5c6d0b7aded5f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/imgs/profile_export.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f96bb5d988aefa89b480c40f83a11b543c185804e7c15f9574f14ff45514ec2e +size 107863 diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/index.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/index.md new file mode 100644 index 0000000000000000000000000000000000000000..0c08d5f60b70f46d745188ea03badb75f5d2bb30 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/index.md @@ -0,0 +1,74 @@ + + +# Accelerate + +🤗 Accelerate is a library that enables the same PyTorch code to be run across any distributed configuration by adding just four lines of code! In short, training and inference at scale made simple, efficient and adaptable. + +```diff ++ from accelerate import Accelerator ++ accelerator = Accelerator() + ++ model, optimizer, training_dataloader, scheduler = accelerator.prepare( ++ model, optimizer, training_dataloader, scheduler ++ ) + + for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) ++ accelerator.backward(loss) + optimizer.step() + scheduler.step() +``` + +Built on `torch_xla` and `torch.distributed`, 🤗 Accelerate takes care of the heavy lifting, so you don't have to write any custom code to adapt to these platforms. +Convert existing codebases to utilize [DeepSpeed](usage_guides/deepspeed), perform [fully sharded data parallelism](usage_guides/fsdp), and have automatic support for mixed-precision training! + + + + To get a better idea of this process, make sure to check out the [Tutorials](basic_tutorials/overview)! + + + + +This code can then be launched on any system through Accelerate's CLI interface: +```bash +accelerate launch {my_script.py} +``` + + diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/accelerator.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/accelerator.md new file mode 100644 index 0000000000000000000000000000000000000000..7d915a4ee60e5518f1f652f549476ed286e98e10 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/accelerator.md @@ -0,0 +1,26 @@ + + +# Accelerator + +The [`Accelerator`] is the main class for enabling distributed training on any type of training setup. Read the [Add Accelerator to your code](../basic_tutorials/migration) tutorial to learn more about how to add the [`Accelerator`] to your script. + +## Accelerator[[api]] + +[[autodoc]] Accelerator + +## Utilities + +[[autodoc]] accelerate.utils.gather_object diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/big_modeling.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/big_modeling.md new file mode 100644 index 0000000000000000000000000000000000000000..98383f702d99999aa3f2aa5493e4019802d3149b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/big_modeling.md @@ -0,0 +1,47 @@ + + +# Working with large models + +## Dispatching and Offloading Models + +[[autodoc]] big_modeling.init_empty_weights +[[autodoc]] big_modeling.cpu_offload +[[autodoc]] big_modeling.cpu_offload_with_hook +[[autodoc]] big_modeling.disk_offload +[[autodoc]] big_modeling.dispatch_model +[[autodoc]] big_modeling.load_checkpoint_and_dispatch +[[autodoc]] big_modeling.load_checkpoint_in_model +[[autodoc]] utils.infer_auto_device_map + +## Model Hooks + +### Hook Classes + +[[autodoc]] hooks.ModelHook +[[autodoc]] hooks.AlignDevicesHook +[[autodoc]] hooks.SequentialHook + +### Adding Hooks + +[[autodoc]] hooks.add_hook_to_module +[[autodoc]] hooks.attach_execution_device_hook +[[autodoc]] hooks.attach_align_device_hook +[[autodoc]] hooks.attach_align_device_hook_on_blocks + +### Removing Hooks + +[[autodoc]] hooks.remove_hook_from_module +[[autodoc]] hooks.remove_hook_from_submodules \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/cli.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/cli.md new file mode 100644 index 0000000000000000000000000000000000000000..1f3ec85827b90bff1fe886265727c5d7e85b37ef --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/cli.md @@ -0,0 +1,335 @@ + + +# The Command Line + +Below is a list of all the available commands 🤗 Accelerate with their parameters + +## accelerate config + +**Command**: + +`accelerate config` or `accelerate-config` + +Launches a series of prompts to create and save a `default_config.yml` configuration file for your training system. Should +always be ran first on your machine. + +**Usage**: + +```bash +accelerate config [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. +* `-h`, `--help` (`bool`) -- Show a help message and exit + +## accelerate config default + +**Command**: + +`accelerate config default` or `accelerate-config default` + +Create a default config file for Accelerate with only a few flags set. + +**Usage**: + +```bash +accelerate config default [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. + +* `-h`, `--help` (`bool`) -- Show a help message and exit +* `--mixed_precision {no,fp16,bf16}` (`str`) -- Whether or not to use mixed precision training. Choose between FP16 and BF16 (bfloat16) training. BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later. + +## accelerate config update + +**Command**: + +`accelerate config update` or `accelerate-config update` + +Update an existing config file with the latest defaults while maintaining the old configuration. + +**Usage**: + +```bash +accelerate config update [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to the config file to update. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. + +* `-h`, `--help` (`bool`) -- Show a help message and exit + + +## accelerate env + +**Command**: + +`accelerate env` or `accelerate-env` or `python -m accelerate.commands.env` + +Lists the contents of the passed 🤗 Accelerate configuration file. Should always be used when opening an issue on the [GitHub repository](https://github.com/huggingface/accelerate). + +**Usage**: + +```bash +accelerate env [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. +* `-h`, `--help` (`bool`) -- Show a help message and exit + +## accelerate launch + +**Command**: + +`accelerate launch` or `accelerate-launch` or `python -m accelerate.commands.launch` + +Launches a specified script on a distributed system with the right parameters. + +**Usage**: + +```bash +accelerate launch [arguments] {training_script} --{training_script-argument-1} --{training_script-argument-2} ... +``` + +**Positional Arguments**: + +- `{training_script}` -- The full path to the script to be launched in parallel +- `--{training_script-argument-1}` -- Arguments of the training script + +**Optional Arguments**: + +* `-h`, `--help` (`bool`) -- Show a help message and exit +* `--config_file CONFIG_FILE` (`str`)-- The config file to use for the default values in the launching script. +* `-m`, `--module` (`bool`) -- Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'. +* `--no_python` (`bool`) -- Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script. +* `--debug` (`bool`) -- Whether to print out the torch.distributed stack trace when something fails. +* `-q`, `--quiet` (`bool`) -- Silence subprocess errors from the launch stack trace to only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations). + + +The rest of these arguments are configured through `accelerate config` and are read in from the specified `--config_file` (or default configuration) for their +values. They can also be passed in manually. + +**Hardware Selection Arguments**: + +* `--cpu` (`bool`) -- Whether or not to force the training on the CPU. +* `--multi_gpu` (`bool`) -- Whether or not this should launch a distributed GPU training. +* `--tpu` (`bool`) -- Whether or not this should launch a TPU training. +* `--ipex` (`bool`) -- Whether or not this should launch an Intel Pytorch Extension (IPEX) training. + +**Resource Selection Arguments**: + +The following arguments are useful for fine-tuning how available hardware should be used + +* `--mixed_precision {no,fp16,bf16,fp8}` (`str`) -- Whether or not to use mixed precision training. Choose between FP16 and BF16 (bfloat16) training. BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later. +* `--num_processes NUM_PROCESSES` (`int`) -- The total number of processes to be launched in parallel. +* `--num_machines NUM_MACHINES` (`int`) -- The total number of machines used in this training. +* `--num_cpu_threads_per_process NUM_CPU_THREADS_PER_PROCESS` (`int`) -- The number of CPU threads per process. Can be tuned for optimal performance. +* `--enable_cpu_affinity` (`bool`) -- Whether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware. + +**Training Paradigm Arguments**: + +The following arguments are useful for selecting which training paradigm to use. + +* `--use_deepspeed` (`bool`) -- Whether or not to use DeepSpeed for training. +* `--use_fsdp` (`bool`) -- Whether or not to use FullyShardedDataParallel for training. +* `--use_megatron_lm` (`bool`) -- Whether or not to use Megatron-LM for training. +* `--use_xpu` (`bool`) -- Whether to use IPEX plugin to speed up training on XPU specifically. + +**Distributed GPU Arguments**: + +The following arguments are only useful when `multi_gpu` is passed or multi-gpu training is configured through `accelerate config`: + +* `--gpu_ids` (`str`) -- What GPUs (by id) should be used for training on this machine as a comma-seperated list +* `--same_network` (`bool`) -- Whether all machines used for multinode training exist on the same local network. +* `--machine_rank` (`int`) -- The rank of the machine on which this script is launched. +* `--main_process_ip` (`str`) -- The IP address of the machine of rank 0. +* `--main_process_port` (`int`) -- The port to use to communicate with the machine of rank 0. +* `-t`, `--tee` (`str`) -- Tee std streams into a log file and also to console. +* `--log_dir` (`str`) -- Base directory to use for log files when using torchrun/torch.distributed.run as launcher. Use with --tee to redirect std streams info log files. +* `--role` (`str`) -- User-defined role for the workers. +* `--rdzv_backend` (`str`) -- The rendezvous method to use, such as 'static' (the default) or 'c10d' +* `--rdzv_conf` (`str`) -- Additional rendezvous configuration (=,=,...). +* `--max_restarts` (`int`) -- Maximum number of worker group restarts before failing. +* `--monitor_interval` (`int`) -- Interval, in seconds, to monitor the state of workers. + +**TPU Arguments**: + +The following arguments are only useful when `tpu` is passed or TPU training is configured through `accelerate config`: + +* `--tpu_cluster` (`bool`) -- Whether to use a GCP TPU pod for training. +* `--tpu_use_sudo` (`bool`) -- Whether to use `sudo` when running the TPU training script in each pod. +* `--vm` (`str`) -- List of single Compute VM instance names. If not provided we assume usage of instance groups. For TPU pods. +* `--env` (`str`) -- List of environment variables to set on the Compute VM instances. For TPU pods. +* `--main_training_function` (`str`) -- The name of the main function to be executed in your script (only for TPU training). +* `--downcast_bf16` (`bool`) -- Whether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32. + +**DeepSpeed Arguments**: + +The following arguments are only useful when `use_deepspeed` is passed or `deepspeed` is configured through `accelerate config`: + +* `--deepspeed_config_file` (`str`) -- DeepSpeed config file. +* `--zero_stage` (`int`) -- DeepSpeed's ZeRO optimization stage. +* `--offload_optimizer_device` (`str`) -- Decides where (none|cpu|nvme) to offload optimizer states. +* `--offload_param_device` (`str`) -- Decides where (none|cpu|nvme) to offload parameters. +* `--offload_optimizer_nvme_path` (`str`) -- Decides Nvme Path to offload optimizer states. +* `--gradient_accumulation_steps` (`int`) -- No of gradient_accumulation_steps used in your training script. +* `--gradient_clipping` (`float`) -- Gradient clipping value used in your training script. +* `--zero3_init_flag` (`str`) -- Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with DeepSpeed ZeRO Stage-3. +* `--zero3_save_16bit_model` (`str`) -- Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. Only applicable with DeepSpeed ZeRO Stage-3. +* `--deepspeed_hostfile` (`str`) -- DeepSpeed hostfile for configuring multi-node compute resources. +* `--deepspeed_exclusion_filter` (`str`) -- DeepSpeed exclusion filter string when using mutli-node setup. +* `--deepspeed_inclusion_filter` (`str`) -- DeepSpeed inclusion filter string when using mutli-node setup. +* `--deepspeed_multinode_launcher` (`str`) -- DeepSpeed multi-node launcher to use. +* `--deepspeed_moe_layer_cls_names` (`str`) -- comma-separated list of transformer MoE layer class names (case-sensitive) to wrap, e.g, `MixtralSparseMoeBlock` `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` + +**Fully Sharded Data Parallelism Arguments**: + +The following arguments are only useful when `use_fsdp` is passed or Fully Sharded Data Parallelism is configured through `accelerate config`: + +* `--fsdp_offload_params` (`str`) -- Decides Whether (true|false) to offload parameters and gradients to CPU. +* `--fsdp_min_num_params` (`int`) -- FSDP's minimum number of parameters for Default Auto Wrapping. +* `--fsdp_sharding_strategy` (`int`) -- FSDP's Sharding Strategy. +* `--fsdp_auto_wrap_policy` (`str`) -- FSDP's auto wrap policy. +* `--fsdp_transformer_layer_cls_to_wrap` (`str`) -- Transformer layer class name (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`, `T5Block` ... +* `--fsdp_backward_prefetch_policy` (`str`) -- FSDP's backward prefetch policy. +* `--fsdp_state_dict_type` (`str`) -- FSDP's state dict type. +* `--fsdp_forward_prefetch` (`str`) -- FSDP forward prefetch. +* `--fsdp_use_orig_params` (`str`) -- If True, allows non-uniform `requires_grad` mixed in a FSDP unit. +* `--fsdp_cpu_ram_efficient_loading` (`str`) -- If true, only the first process loads the pretrained model checkoint while all other processes have empty weights. When using this, `--fsdp_sync_module_states` needs to True. +* `--fsdp_sync_module_states` (`str`) -- If true, each individually wrapped FSDP unit will broadcast module parameters from rank 0. +* `--fsdp_activation_checkpointing` (`bool`) -- Decides Whether intermediate activations are freed during the forward pass, and a checkpoint is left as a placeholder + +**Megatron-LM Arguments**: + +The following arguments are only useful when `use_megatron_lm` is passed or Megatron-LM is configured through `accelerate config`: + +* `--megatron_lm_tp_degree` (``) -- Megatron-LM's Tensor Parallelism (TP) degree. +* `--megatron_lm_pp_degree` (``) -- Megatron-LM's Pipeline Parallelism (PP) degree. +* `--megatron_lm_num_micro_batches` (``) -- Megatron-LM's number of micro batches when PP degree > 1. +* `--megatron_lm_sequence_parallelism` (``) -- Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. +* `--megatron_lm_recompute_activations` (``) -- Decides Whether (true|false) to enable Selective Activation Recomputation. +* `--megatron_lm_use_distributed_optimizer` (``) -- Decides Whether (true|false) to use distributed optimizer which shards optimizer state and gradients across Data Parallel (DP) ranks. +* `--megatron_lm_gradient_clipping` (``) -- Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). + +**FP8 Arguments**: + +* `--fp8_backend` (`str`) -- Choose a backend to train with FP8 (`te` or `msamp`) +* `--fp8_use_autocast_during_eval` (`bool`) -- Whether to use FP8 autocast during eval mode (useful only when `--fp8_backend=te` is passed). Generally better metrics are found when this is not passed. +* `--fp8_margin` (`int`) -- The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed). +* `--fp8_interval` (`int`) -- The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed). +* `--fp8_format` (`str`) -- The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed). +* `--fp8_amax_history_len` (`int`) -- The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed). +* `--fp8_amax_compute_algo` (`str`) -- The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed). +* `--fp8_override_linear_precision` (`Tuple[bool, bool, bool]`) -- Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. +* `--fp8_opt_level` (`str`) -- What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed) + +**AWS SageMaker Arguments**: + +The following arguments are only useful when training in SageMaker + +* `--aws_access_key_id AWS_ACCESS_KEY_ID` (`str`) -- The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job +* `--aws_secret_access_key AWS_SECRET_ACCESS_KEY` (`str`) -- The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job + +## accelerate estimate-memory + +**Command**: + +`accelerate estimate-memory` or `accelerate-estimate-memory` or `python -m accelerate.commands.estimate` + +Estimates the total vRAM a particular model hosted on the Hub needs to be loaded in with an estimate for training. Requires that `huggingface_hub` be installed. + + + + When performing inference, typically add ≤20% to the result as overall allocation [as referenced here](https://blog.eleuther.ai/transformer-math/). We will have more extensive estimations in the future that will automatically be included in the calculation. + + + +**Usage**: + +```bash +accelerate estimate-memory {MODEL_NAME} --library_name {LIBRARY_NAME} --dtypes {dtype_1} {dtype_2} ... +``` + +**Required Arguments**: + +* `MODEL_NAME` (`str`)-- The model name on the Hugging Face Hub + +**Optional Arguments**: + +* `--library_name {timm,transformers}` (`str`) -- The library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub +* `--dtypes {float32,float16,int8,int4}` (`[{float32,float16,int8,int4} ...]`) -- The dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4` +* `--trust_remote_code` (`bool`) -- Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be passed for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. + +## accelerate tpu-config + +`accelerate tpu-config` + +**Usage**: + +```bash +accelerate tpu-config [arguments] +``` + +**Optional Arguments**: +* `-h`, `--help` (`bool`) -- Show a help message and exit + +**Config Arguments**: + +Arguments that can be configured through `accelerate config`. + +* `--config_file` (`str`) -- Path to the config file to use for accelerate. +* `--tpu_name` (`str`) -- The name of the TPU to use. If not specified, will use the TPU specified in the config file. +* `--tpu_zone` (`str`) -- The zone of the TPU to use. If not specified, will use the zone specified in the config file. + +**TPU Arguments**: + +Arguments for options ran inside the TPU. + +* `--command_file` (`str`) -- The path to the file containing the commands to run on the pod on startup. +* `--command` (`str`) -- A command to run on the pod. Can be passed multiple times. +* `--install_accelerate` (`bool`) -- Whether to install accelerate on the pod. Defaults to False. +* `--accelerate_version` (`str`) -- The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub. +* `--debug` (`bool`) -- If set, will print the command that would be run instead of running it. + +## accelerate test + +`accelerate test` or `accelerate-test` + +Runs `accelerate/test_utils/test_script.py` to verify that 🤗 Accelerate has been properly configured on your system and runs. + +**Usage**: + +```bash +accelerate test [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. +* `-h`, `--help` (`bool`) -- Show a help message and exit diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/deepspeed.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..9e247f1ac4065cd68847807118a3012ba72f94cb --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/deepspeed.md @@ -0,0 +1,28 @@ + + +# Utilities for DeepSpeed + +[[autodoc]] utils.DeepSpeedPlugin + +[[autodoc]] utils.deepspeed.DummyOptim + +[[autodoc]] utils.deepspeed.DummyScheduler + +[[autodoc]] utils.deepspeed.DeepSpeedEngineWrapper + +[[autodoc]] utils.deepspeed.DeepSpeedOptimizerWrapper + +[[autodoc]] utils.deepspeed.DeepSpeedSchedulerWrapper diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/fp8.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/fp8.md new file mode 100644 index 0000000000000000000000000000000000000000..5b16e658cacdfcbb895f5dbfb389b438d5708863 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/fp8.md @@ -0,0 +1,28 @@ + + +# FP8 Functionality + +Below are functions and classes relative to the underlying FP8 implementation + +[[autodoc]] utils.FP8RecipeKwargs + +[[autodoc]] utils.convert_model + +[[autodoc]] utils.has_transformer_engine_layers + +[[autodoc]] utils.contextual_fp8_autocast + +[[autodoc]] utils.apply_fp8_autowrap diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/fsdp.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/fsdp.md new file mode 100644 index 0000000000000000000000000000000000000000..ca35ffc7735851385fc8f8aeaa7dd1e03154bed7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/fsdp.md @@ -0,0 +1,24 @@ + + +# Utilities for Fully Sharded Data Parallelism + +[[autodoc]] utils.enable_fsdp_ram_efficient_loading + +[[autodoc]] utils.disable_fsdp_ram_efficient_loading + +[[autodoc]] utils.merge_fsdp_weights + +[[autodoc]] utils.FullyShardedDataParallelPlugin diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/inference.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/inference.md new file mode 100644 index 0000000000000000000000000000000000000000..4347f98441e03da1b0ba02efc720b8a1a8a19da4 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/inference.md @@ -0,0 +1,20 @@ + + +# The inference API + +These docs refer to the [PiPPy](https://github.com/PyTorch/PiPPy) integration. + +[[autodoc]] inference.prepare_pippy diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/kwargs.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/kwargs.md new file mode 100644 index 0000000000000000000000000000000000000000..a45b6793f6f406072b18c54d18570b9bf1708892 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/kwargs.md @@ -0,0 +1,47 @@ + + +# Kwargs Handlers + +The following objects can be passed to the main [`Accelerator`] to customize how some PyTorch objects +related to distributed training or mixed precision are created. + +## AutocastKwargs + +[[autodoc]] AutocastKwargs + +## DistributedDataParallelKwargs + +[[autodoc]] DistributedDataParallelKwargs + +## FP8RecipeKwargs + +[[autodoc]] utils.FP8RecipeKwargs + +## ProfileKwargs + +[[autodoc]] utils.ProfileKwargs + +## GradScalerKwargs + +[[autodoc]] GradScalerKwargs + +## InitProcessGroupKwargs + +[[autodoc]] InitProcessGroupKwargs + +## KwargsHandler + +[[autodoc]] utils.KwargsHandler diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/launchers.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/launchers.md new file mode 100644 index 0000000000000000000000000000000000000000..a0335c8cf8996edbf1b1e7b77aaaa4b5d32797c0 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/launchers.md @@ -0,0 +1,22 @@ + + +# Launchers + +Functions for launching training on distributed processes. + + +[[autodoc]] accelerate.notebook_launcher +[[autodoc]] accelerate.debug_launcher \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/logging.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/logging.md new file mode 100644 index 0000000000000000000000000000000000000000..588913016e10d0a55de9e33be613e080d31f4658 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/logging.md @@ -0,0 +1,21 @@ + + +# Logging with Accelerate + +Refer to the [Troubleshooting guide](../usage_guides/troubleshooting#logging) or to the example below to learn +how to use 🤗 Accelerate's logger. + +[[autodoc]] logging.get_logger \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/megatron_lm.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/megatron_lm.md new file mode 100644 index 0000000000000000000000000000000000000000..d1874fdab1120a994d0e903dbd5e22fb06915d48 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/megatron_lm.md @@ -0,0 +1,32 @@ + + +# Utilities for Megatron-LM + +[[autodoc]] utils.MegatronLMPlugin + +[[autodoc]] utils.MegatronLMDummyScheduler + +[[autodoc]] utils.MegatronLMDummyDataLoader + +[[autodoc]] utils.AbstractTrainStep + +[[autodoc]] utils.GPTTrainStep + +[[autodoc]] utils.BertTrainStep + +[[autodoc]] utils.T5TrainStep + +[[autodoc]] utils.avg_losses_across_data_parallel_group diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/state.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/state.md new file mode 100644 index 0000000000000000000000000000000000000000..56c38dd461dc1ce4855dc6e866202d62bb9ccb0a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/state.md @@ -0,0 +1,28 @@ + + +# Stateful Classes + +Below are variations of a [singleton class](https://en.wikipedia.org/wiki/Singleton_pattern) in the sense that all +instances share the same state, which is initialized on the first instantiation. + +These classes are immutable and store information about certain configurations or +states. + +[[autodoc]] state.PartialState + +[[autodoc]] state.AcceleratorState + +[[autodoc]] state.GradientState \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/torch_wrappers.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/torch_wrappers.md new file mode 100644 index 0000000000000000000000000000000000000000..17350e3441f62e127351361dabebbee35764b2d9 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/torch_wrappers.md @@ -0,0 +1,37 @@ + + +# Wrapper classes for torch Dataloaders, Optimizers, and Schedulers + +The internal classes Accelerate uses to prepare objects for distributed training +when calling [`~Accelerator.prepare`]. + +## Datasets and DataLoaders + +[[autodoc]] data_loader.prepare_data_loader +[[autodoc]] data_loader.skip_first_batches + +[[autodoc]] data_loader.BatchSamplerShard +[[autodoc]] data_loader.IterableDatasetShard +[[autodoc]] data_loader.DataLoaderShard +[[autodoc]] data_loader.DataLoaderDispatcher + +## Optimizers + +[[autodoc]] optimizer.AcceleratedOptimizer + +## Schedulers + +[[autodoc]] scheduler.AcceleratedScheduler \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/tracking.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/tracking.md new file mode 100644 index 0000000000000000000000000000000000000000..6845ca4bc053a2c573f2166cb6e3f2e56633fc26 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/tracking.md @@ -0,0 +1,35 @@ + + +# Experiment Tracking + +## The Base Tracker Class + +[[autodoc]] tracking.GeneralTracker + +## Integrated Trackers + +[[autodoc]] tracking.TensorBoardTracker + - __init__ +[[autodoc]] tracking.WandBTracker + - __init__ +[[autodoc]] tracking.CometMLTracker + - __init__ +[[autodoc]] tracking.AimTracker + - __init__ +[[autodoc]] tracking.MLflowTracker + - __init__ +[[autodoc]] tracking.ClearMLTracker + - __init__ diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/utilities.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/utilities.md new file mode 100644 index 0000000000000000000000000000000000000000..2b7fa2c0b4acef148ecbe97cfe3c14fe338940b8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/package_reference/utilities.md @@ -0,0 +1,246 @@ + + +# Helpful Utilities + +Below are a variety of utility functions that 🤗 Accelerate provides, broken down by use-case. + +## Constants + +Constants used throughout 🤗 Accelerate for reference + +The following are constants used when utilizing [`Accelerator.save_state`] + +`utils.MODEL_NAME`: `"pytorch_model"` +`utils.OPTIMIZER_NAME`: `"optimizer"` +`utils.RNG_STATE_NAME`: `"random_states"` +`utils.SCALER_NAME`: `"scaler.pt` +`utils.SCHEDULER_NAME`: `"scheduler` + +The following are constants used when utilizing [`Accelerator.save_model`] + +`utils.WEIGHTS_NAME`: `"pytorch_model.bin"` +`utils.SAFE_WEIGHTS_NAME`: `"model.safetensors"` +`utils.WEIGHTS_INDEX_NAME`: `"pytorch_model.bin.index.json"` +`utils.SAFE_WEIGHTS_INDEX_NAME`: `"model.safetensors.index.json"` + +## Data Classes + +These are basic dataclasses used throughout 🤗 Accelerate and they can be passed in as parameters. + +### Standalone + +These are standalone dataclasses used for checks, such as the type of distributed system being used + +[[autodoc]] utils.ComputeEnvironment + +[[autodoc]] utils.DistributedType + +[[autodoc]] utils.DynamoBackend + +[[autodoc]] utils.LoggerType + +[[autodoc]] utils.PrecisionType + +[[autodoc]] utils.RNGType + +[[autodoc]] utils.SageMakerDistributedType + +### Kwargs + +These are configurable arguments for specific interactions throughout the PyTorch ecosystem that Accelerate handles under the hood. + +[[autodoc]] utils.AutocastKwargs + +[[autodoc]] utils.DistributedDataParallelKwargs + +[[autodoc]] utils.FP8RecipeKwargs + +[[autodoc]] utils.GradScalerKwargs + +[[autodoc]] utils.InitProcessGroupKwargs + +[[autodoc]] utils.KwargsHandler + +## Plugins + +These are plugins that can be passed to the [`Accelerator`] object. While they are defined elsewhere in the documentation, +for convenience all of them are available to see here: + +[[autodoc]] utils.DeepSpeedPlugin + +[[autodoc]] utils.FullyShardedDataParallelPlugin + +[[autodoc]] utils.GradientAccumulationPlugin + +[[autodoc]] utils.MegatronLMPlugin + +[[autodoc]] utils.TorchDynamoPlugin + +## Configurations + +These are classes which can be configured and passed through to the appropriate integration + +[[autodoc]] utils.BnbQuantizationConfig + +[[autodoc]] utils.DataLoaderConfiguration + +[[autodoc]] utils.ProjectConfiguration + +## Environmental Variables + +These are environmental variables that can be enabled for different use cases + +* `ACCELERATE_DEBUG_MODE` (`str`): Whether to run accelerate in debug mode. More info available [here](../usage_guides/debug.md). + + + + +## Data Manipulation and Operations + +These include data operations that mimic the same `torch` ops but can be used on distributed processes. + +[[autodoc]] utils.broadcast + +[[autodoc]] utils.broadcast_object_list + +[[autodoc]] utils.concatenate + +[[autodoc]] utils.convert_outputs_to_fp32 + +[[autodoc]] utils.convert_to_fp32 + +[[autodoc]] utils.gather + +[[autodoc]] utils.gather_object + +[[autodoc]] utils.listify + +[[autodoc]] utils.pad_across_processes + +[[autodoc]] utils.recursively_apply + +[[autodoc]] utils.reduce + +[[autodoc]] utils.send_to_device + +[[autodoc]] utils.slice_tensors + +## Environment Checks + +These functionalities check the state of the current working environment including information about the operating system itself, what it can support, and if particular dependencies are installed. + +[[autodoc]] utils.is_bf16_available + +[[autodoc]] utils.is_ipex_available + +[[autodoc]] utils.is_mps_available + +[[autodoc]] utils.is_npu_available + +[[autodoc]] utils.is_torch_version + +[[autodoc]] utils.is_torch_xla_available + +[[autodoc]] utils.is_xpu_available + +## Environment Manipulation + +[[autodoc]] utils.patch_environment + +[[autodoc]] utils.clear_environment + +[[autodoc]] utils.write_basic_config + +When setting up 🤗 Accelerate for the first time, rather than running `accelerate config` [~utils.write_basic_config] can be used as an alternative for quick configuration. + +[[autodoc]] utils.set_numa_affinity + +[[autodoc]] utils.environment.override_numa_affinity + +## Memory + +[[autodoc]] utils.find_executable_batch_size + +## Modeling + +These utilities relate to interacting with PyTorch models + +[[autodoc]] utils.calculate_maximum_sizes + +[[autodoc]] utils.compute_module_sizes + +[[autodoc]] utils.extract_model_from_parallel + +[[autodoc]] utils.get_balanced_memory + +[[autodoc]] utils.get_max_layer_size + +[[autodoc]] utils.infer_auto_device_map + +[[autodoc]] utils.load_checkpoint_in_model + +[[autodoc]] utils.load_offloaded_weights + +[[autodoc]] utils.load_state_dict + +[[autodoc]] utils.offload_state_dict + +[[autodoc]] utils.retie_parameters + +[[autodoc]] utils.set_module_tensor_to_device + +[[autodoc]] utils.shard_checkpoint + + +## Parallel + +These include general utilities that should be used when working in parallel. + +[[autodoc]] utils.extract_model_from_parallel + +[[autodoc]] utils.save + +[[autodoc]] utils.wait_for_everyone + + +## Random + +These utilities relate to setting and synchronizing of all the random states. + +[[autodoc]] utils.set_seed + +[[autodoc]] utils.synchronize_rng_state + +[[autodoc]] utils.synchronize_rng_states + + +## PyTorch XLA + +These include utilities that are useful while using PyTorch with XLA. + +[[autodoc]] utils.install_xla + +## Loading model weights + +These include utilities that are useful to load checkpoints. + +[[autodoc]] utils.load_checkpoint_in_model + +## Quantization + +These include utilities that are useful to quantize model. + +[[autodoc]] utils.load_and_quantize_model diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/quicktour.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/quicktour.md new file mode 100644 index 0000000000000000000000000000000000000000..fd571c861b34b7e967b65794b9d42080d7647fce --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/quicktour.md @@ -0,0 +1,188 @@ + + +# Quicktour + +There are many ways to launch and run your code depending on your training environment ([torchrun](https://pytorch.org/docs/stable/elastic/run.html), [DeepSpeed](https://www.deepspeed.ai/), etc.) and available hardware. Accelerate offers a unified interface for launching and training on different distributed setups, allowing you to focus on your PyTorch training code instead of the intricacies of adapting your code to these different setups. This allows you to easily scale your PyTorch code for training and inference on distributed setups with hardware like GPUs and TPUs. Accelerate also provides Big Model Inference to make loading and running inference with really large models that usually don't fit in memory more accessible. + +This quicktour introduces the three main features of Accelerate: + +* a unified command line launching interface for distributed training scripts +* a training library for adapting PyTorch training code to run on different distributed setups +* Big Model Inference + +## Unified launch interface + +Accelerate automatically selects the appropriate configuration values for any given distributed training framework (DeepSpeed, FSDP, etc.) through a unified configuration file generated from the [`accelerate config`](package_reference/cli#accelerate-config) command. You could also pass the configuration values explicitly to the command line which is helpful in certain situations like if you're using SLURM. + + +But in most cases, you should always run [`accelerate config`](package_reference/cli#accelerate-config) first to help Accelerate learn about your training setup. + +```bash +accelerate config +``` + +The [`accelerate config`](package_reference/cli#accelerate-config) command creates and saves a default_config.yaml file in Accelerates cache folder. This file stores the configuration for your training environment, which helps Accelerate correctly launch your training script based on your machine. + +After you've configured your environment, you can test your setup with [`accelerate test`](package_reference/cli#accelerate-test), which launches a short script to test the distributed environment. + +```bash +accelerate test +``` + +> [!TIP] +> Add `--config_file` to the `accelerate test` or `accelerate launch` command to specify the location of the configuration file if it is saved in a non-default location like the cache. + +Once your environment is setup, launch your training script with [`accelerate launch`](package_reference/cli#accelerate-launch)! + +```bash +accelerate launch path_to_script.py --args_for_the_script +``` + +To learn more, check out the [Launch distributed code](basic_tutorials/launch) tutorial for more information about launching your scripts. + +We also have a [configuration zoo](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates) which showcases a number of premade **minimal** example configurations for a variety of setups you can run. + +## Adapt training code + +The next main feature of Accelerate is the [`Accelerator`] class which adapts your PyTorch code to run on different distributed setups. + +You only need to add a few lines of code to your training script to enable it to run on multiple GPUs or TPUs. + +```diff ++ from accelerate import Accelerator ++ accelerator = Accelerator() + ++ device = accelerator.device ++ model, optimizer, training_dataloader, scheduler = accelerator.prepare( ++ model, optimizer, training_dataloader, scheduler ++ ) + + for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch +- inputs = inputs.to(device) +- targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) ++ accelerator.backward(loss) + optimizer.step() + scheduler.step() +``` + +1. Import and instantiate the [`Accelerator`] class at the beginning of your training script. The [`Accelerator`] class initializes everything necessary for distributed training, and it automatically detects your training environment (a single machine with a GPU, a machine with several GPUs, several machines with multiple GPUs or a TPU, etc.) based on how the code was launched. + +```python +from accelerate import Accelerator + +accelerator = Accelerator() +``` + +2. Remove calls like `.cuda()` on your model and input data. The [`Accelerator`] class automatically places these objects on the appropriate device for you. + +> [!WARNING] +> This step is *optional* but it is considered best practice to allow Accelerate to handle device placement. You could also deactivate automatic device placement by passing `device_placement=False` when initializing the [`Accelerator`]. If you want to explicitly place objects on a device with `.to(device)`, make sure you use `accelerator.device` instead. For example, if you create an optimizer before placing a model on `accelerator.device`, training fails on a TPU. + +> [!WARNING] +> Accelerate does not use non-blocking transfers by default for its automatic device placement, which can result in potentially unwanted CUDA synchronizations. You can enable non-blocking transfers by passing a [`~utils.dataclasses.DataLoaderConfiguration`] with `non_blocking=True` set as the `dataloader_config` when initializing the [`Accelerator`]. As usual, non-blocking transfers will only work if the dataloader also has `pin_memory=True` set. Be wary that using non-blocking transfers from GPU to CPU may cause incorrect results if it results in CPU operations being performed on non-ready tensors. + +```py +device = accelerator.device +``` + +3. Pass all relevant PyTorch objects for training (optimizer, model, dataloader(s), learning rate scheduler) to the [`~Accelerator.prepare`] method as soon as they're created. This method wraps the model in a container optimized for your distributed setup, uses Accelerates version of the optimizer and scheduler, and creates a sharded version of your dataloader for distribution across GPUs or TPUs. + +```python +model, optimizer, train_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, lr_scheduler +) +``` + +4. Replace `loss.backward()` with [`~Accelerator.backward`] to use the correct `backward()` method for your training setup. + +```py +accelerator.backward(loss) +``` + +Read [Accelerate’s internal mechanisms](concept_guides/internal_mechanism) guide to learn more details about how Accelerate adapts your code. + +### Distributed evaluation + +To perform distributed evaluation, pass your validation dataloader to the [`~Accelerator.prepare`] method: + +```python +validation_dataloader = accelerator.prepare(validation_dataloader) +``` + +Each device in your distributed setup only receives a part of the evaluation data, which means you should group your predictions together with the [`~Accelerator.gather_for_metrics`] method. This method requires all tensors to be the same size on each process, so if your tensors have different sizes on each process (for instance when dynamically padding to the maximum length in a batch), you should use the [`~Accelerator.pad_across_processes`] method to pad you tensor to the largest size across processes. Note that the tensors needs to be 1D and that we concatenate the tensors along the first dimension. + +```python +for inputs, targets in validation_dataloader: + predictions = model(inputs) + # Gather all predictions and targets + all_predictions, all_targets = accelerator.gather_for_metrics((predictions, targets)) + # Example of use with a *Datasets.Metric* + metric.add_batch(all_predictions, all_targets) +``` + +For more complex cases (e.g. 2D tensors, don't want to concatenate tensors, dict of 3D tensors), you can pass `use_gather_object=True` in `gather_for_metrics`. This will return the list of objects after gathering. Note that using it with GPU tensors is not well supported and inefficient. + +> [!TIP] +> Data at the end of a dataset may be duplicated so the batch can be equally divided among all workers. The [`~Accelerator.gather_for_metrics`] method automatically removes the duplicated data to calculate a more accurate metric. + +## Big Model Inference + +Accelerate's Big Model Inference has two main features, [`~accelerate.init_empty_weights`] and [`~accelerate.load_checkpoint_and_dispatch`], to load large models for inference that typically don't fit into memory. + +> [!TIP] +> Take a look at the [Handling big models for inference](concept_guides/big_model_inference) guide for a better understanding of how Big Model Inference works under the hood. + +### Empty weights initialization + +The [`~accelerate.init_empty_weights`] context manager initializes models of any size by creating a *model skeleton* and moving and placing parameters each time they're created to PyTorch's [**meta**](https://pytorch.org/docs/main/meta.html) device. This way, not all weights are immediately loaded and only a small part of the model is loaded into memory at a time. + +For example, loading an empty [Mixtral-8x7B](https://huggingface.co/mistralai/Mixtral-8x7B-Instruct-v0.1) model takes significantly less memory than fully loading the models and weights on the CPU. + +```py +from accelerate import init_empty_weights +from transformers import AutoConfig, AutoModelForCausalLM + +config = AutoConfig.from_pretrained("mistralai/Mixtral-8x7B-Instruct-v0.1") +with init_empty_weights(): + model = AutoModelForCausalLM.from_config(config) +``` + +### Load and dispatch weights + +The [`~accelerate.load_checkpoint_and_dispatch`] function loads full or sharded checkpoints into the empty model, and automatically distribute weights across all available devices. + +The `device_map` parameter determines where to place each model layer, and specifiying `"auto"` places them on the GPU first, then the CPU, and finally the hard drive as memory-mapped tensors if there's still not enough memory. Use the `no_split_module_classes` parameter to indicate which modules shouldn't be split across devices (typically those with a residual connection). + +```py +from accelerate import load_checkpoint_and_dispatch + +model = load_checkpoint_and_dispatch( + model, checkpoint="mistralai/Mixtral-8x7B-Instruct-v0.1", device_map="auto", no_split_module_classes=['Block'] +) +``` + +## Next steps + +Now that you've been introduced to the main Accelerate features, your next steps could include: + +* Check out the [tutorials](basic_tutorials/overview) for a gentle walkthrough of Accelerate. This is especially useful if you're new to distributed training and the library. +* Dive into the [guides](usage_guides/explore) to see how to use Accelerate for specific use-cases. +* Deepen your conceptual understanding of how Accelerate works internally by reading the [concept guides](concept_guides/internal_mechanism). +* Look up classes and commands in the [API reference](package_reference/accelerator) to see what parameters and options are available. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/big_modeling.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/big_modeling.md new file mode 100644 index 0000000000000000000000000000000000000000..2c95ecf18b5bc1416c67f40afa405e50db0bc02d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/big_modeling.md @@ -0,0 +1,150 @@ + + +# Handling big models for inference + +One of the biggest advancements 🤗 Accelerate provides is the concept of [large model inference](../concept_guides/big_model_inference) wherein you can perform *inference* on models that cannot fully fit on your graphics card. + +This tutorial will be broken down into two parts showcasing how to use both 🤗 Accelerate and 🤗 Transformers (a higher API-level) to make use of this idea. + +## Using 🤗 Accelerate + +For these tutorials, we'll assume a typical workflow for loading your model in such that: + +```py +import torch + +my_model = ModelClass(...) +state_dict = torch.load(checkpoint_file) +my_model.load_state_dict(state_dict) +``` + +Note that here we assume that `ModelClass` is a model that takes up more video-card memory than what can fit on your device (be it `mps` or `cuda`). + +The first step is to init an empty skeleton of the model which won't take up any RAM using the [`init_empty_weights`] context manager: + +```py +from accelerate import init_empty_weights +with init_empty_weights(): + my_model = ModelClass(...) +``` + +With this `my_model` currently is "parameterless", hence leaving the smaller footprint than what one would normally get loading this onto the CPU directly. + +Next we need to load in the weights to our model so we can perform inference. + +For this we will use [`load_checkpoint_and_dispatch`], which as the name implies will load a checkpoint inside your empty model and dispatch the weights for each layer across all the devices you have available (GPU/MPS and CPU RAM). + +To determine how this `dispatch` can be performed, generally specifying `device_map="auto"` will be good enough as 🤗 Accelerate +will attempt to fill all the space in your GPU(s), then loading them to the CPU, and finally if there is not enough RAM it will be loaded to the disk (the absolute slowest option). + + + +For more details on designing your own device map, see this section of the [concept guide](../concept_guides/big_model_inference#designing-a-device-map) + + + +See an example below: + +```py +from accelerate import load_checkpoint_and_dispatch + +model = load_checkpoint_and_dispatch( + model, checkpoint=checkpoint_file, device_map="auto" +) +``` + + + + If there are certain "chunks" of layers that shouldn't be split, you can pass them in as `no_split_module_classes`. Read more about it [here](../concept_guides/big_model_inference#loading-weights) + + + + + + Also to save on memory (such as if the `state_dict` will not fit in RAM), a model's weights can be divided and split into multiple checkpoint files. Read more about it [here](../concept_guides/big_model_inference#sharded-checkpoints) + + + +Now that the model is dispatched fully, you can perform inference as normal with the model: + +```py +input = torch.randn(2,3) +input = input.to("cuda") +output = model(input) +``` + +What will happen now is each time the input gets passed through a layer, it will be sent from the CPU to the GPU (or disk to CPU to GPU), the output is calculated, and then the layer is pulled back off the GPU going back down the line. While this adds some overhead to the inference being performed, through this method it is possible to run **any size model** on your system, as long as the largest layer is capable of fitting on your GPU. + + + + Multiple GPUs can be utilized, however this is considered "model parallelism" and as a result only one GPU will be active at a given moment, waiting for the prior one to send it the output. You should launch your script normally with `python` + and not need `torchrun`, `accelerate launch`, etc. + + + +For a visual representation of this, check out the animation below: + + + +### Complete Example + +Below is the full example showcasing what we performed above: + +```py +import torch +from accelerate import init_empty_weights, load_checkpoint_and_dispatch + +with init_empty_weights(): + model = MyModel(...) + +model = load_checkpoint_and_dispatch( + model, checkpoint=checkpoint_file, device_map="auto" +) + +input = torch.randn(2,3) +input = input.to("cuda") +output = model(input) +``` + +## Using 🤗 Transformers, 🤗 Diffusers, and other 🤗 Open Source Libraries + +Libraries that support 🤗 Accelerate big model inference include all of the earlier logic in their `from_pretrained` constructors. + +These operate by specifying a string representing the model to download from the [🤗 Hub](https://hf.co/models) and then denoting `device_map="auto"` along with a few extra parameters. + +As a brief example, we will look at using `transformers` and loading in Big Science's T0pp model. + +```py +from transformers import AutoModelForSeq2SeqLM + +model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto") +``` + +After loading the model in, the initial steps from before to prepare a model have all been done and the model is fully +ready to make use of all the resources in your machine. Through these constructors, you can also save *more* memory by +specifying the precision the model is loaded into as well, through the `torch_dtype` parameter, such as: + +```py +from transformers import AutoModelForSeq2SeqLM + +model = AutoModelForSeq2SeqLM.from_pretrained("bigscience/T0pp", device_map="auto", torch_dtype=torch.float16) +``` + +To learn more about this, check out the 🤗 Transformers documentation available [here](https://huggingface.co/docs/transformers/main/en/main_classes/model#large-model-loading). + +## Where to go from here + +For a much more detailed look at big model inference, be sure to check out the [Conceptual Guide on it](../concept_guides/big_model_inference) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/checkpoint.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/checkpoint.md new file mode 100644 index 0000000000000000000000000000000000000000..b8943b421da778e1576341976ff84b886544ef41 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/checkpoint.md @@ -0,0 +1,96 @@ + + +# Checkpointing + +When training a PyTorch model with 🤗 Accelerate, you may often want to save and continue a state of training. Doing so requires +saving and loading the model, optimizer, RNG generators, and the GradScaler. Inside 🤗 Accelerate are two convenience functions to achieve this quickly: +- Use [`~Accelerator.save_state`] for saving everything mentioned above to a folder location +- Use [`~Accelerator.load_state`] for loading everything stored from an earlier `save_state` + +To further customize where and how states are saved through [`~Accelerator.save_state`] the [`~utils.ProjectConfiguration`] class can be used. For example +if `automatic_checkpoint_naming` is enabled each saved checkpoint will be located then at `Accelerator.project_dir/checkpoints/checkpoint_{checkpoint_number}`. + +It should be noted that the expectation is that those states come from the same training script, they should not be from two separate scripts. + +- By using [`~Accelerator.register_for_checkpointing`], you can register custom objects to be automatically stored or loaded from the two prior functions, +so long as the object has a `state_dict` **and** a `load_state_dict` functionality. This could include objects such as a learning rate scheduler. + + +Below is a brief example using checkpointing to save and reload a state during training: + +```python +from accelerate import Accelerator +import torch + +accelerator = Accelerator(project_dir="my/save/path") + +my_scheduler = torch.optim.lr_scheduler.StepLR(my_optimizer, step_size=1, gamma=0.99) +my_model, my_optimizer, my_training_dataloader = accelerator.prepare(my_model, my_optimizer, my_training_dataloader) + +# Register the LR scheduler +accelerator.register_for_checkpointing(my_scheduler) + +# Save the starting state +accelerator.save_state() + +device = accelerator.device +my_model.to(device) + +# Perform training +for epoch in range(num_epochs): + for batch in my_training_dataloader: + my_optimizer.zero_grad() + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = my_model(inputs) + loss = my_loss_function(outputs, targets) + accelerator.backward(loss) + my_optimizer.step() + my_scheduler.step() + +# Restore the previous state +accelerator.load_state("my/save/path/checkpointing/checkpoint_0") +``` + +## Restoring the state of the DataLoader + +After resuming from a checkpoint, it may also be desirable to resume from a particular point in the active `DataLoader` if +the state was saved during the middle of an epoch. You can use [`~Accelerator.skip_first_batches`] to do so. + +```python +from accelerate import Accelerator + +accelerator = Accelerator(project_dir="my/save/path") + +train_dataloader = accelerator.prepare(train_dataloader) +accelerator.load_state("my_state") + +# Assume the checkpoint was saved 100 steps into the epoch +skipped_dataloader = accelerator.skip_first_batches(train_dataloader, 100) + +# After the first iteration, go back to `train_dataloader` + +# First epoch +for batch in skipped_dataloader: + # Do something + pass + +# Second epoch +for batch in train_dataloader: + # Do something + pass +``` diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/ddp_comm_hook.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/ddp_comm_hook.md new file mode 100644 index 0000000000000000000000000000000000000000..9e903212af403f397125ee8c2e5e288d6ec7e128 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/ddp_comm_hook.md @@ -0,0 +1,325 @@ + + +# DDP Communication Hooks + +Distributed Data Parallel (DDP) communication hooks provide a generic interface to control how gradients are communicated across workers by overriding the vanilla allreduce in `DistributedDataParallel`. A few built-in communication hooks are provided, and users can easily apply any of these hooks to optimize communication. + + +- **FP16 Compression Hook**: Compresses gradients by casting them to half-precision floating-point format (`torch.float16`), reducing communication overhead. +- **BF16 Compression Hook**: Similar to FP16, but uses the Brain Floating Point format (`torch.bfloat16`), which can be more efficient on certain hardware. +- **PowerSGD Hook**: An advanced gradient compression algorithm that provides high compression rates and can accelerate bandwidth-bound distributed training. + +In this tutorial, you will see how to quickly set up DDP communication hooks and perform training with the utilities provided in 🤗 Accelerate, which can be as simple as adding just one new line of code! This demonstrates how to use DDP communication hooks to optimize gradient communication in distributed training with the 🤗 Accelerate library. + +## FP16 Compression Hook + + + + +```python +import torch +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.distributed.algorithms.ddp_comm_hooks import default_hooks + +class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(10, 10) + + def forward(self, x): + return self.layer(x) + +model = MyModel() +model = DDP(model, device_ids=[torch.cuda.current_device()]) +model.register_comm_hook(state=None, hook=default_hooks.fp16_compress_hook) + +# Training loop +for data, targets in data_loader: + outputs = model(data) + loss = criterion(outputs, targets) + loss.backward() + optimizer.step() + optimizer.zero_grad() +``` + + + + +```python +from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs +import torch + +class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(10, 10) + + def forward(self, x): + return self.layer(x) + +# DDP Communication Hook setup +ddp_kwargs = DistributedDataParallelKwargs(comm_hook=DDPCommunicationHookType.FP16) +accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) + +model = MyModel() +optimizer = torch.optim.Adam(model.parameters()) +data_loader = DataLoader(dataset, batch_size=16) + +model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) + +# Training loop +for data, targets in data_loader: + outputs = model(data) + loss = criterion(outputs, targets) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + + + + +### BF16 Compression Hook + + + +BF16 Compression Hook API is experimental, and it requires NCCL version later than 2.9.6. + + + + + + +```python +import torch +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.distributed.algorithms.ddp_comm_hooks import default_hooks + +class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(10, 10) + + def forward(self, x): + return self.layer(x) + +model = MyModel() +model = DDP(model, device_ids=[torch.cuda.current_device()]) +model.register_comm_hook(state=None, hook=default_hooks.bf16_compress_hook) + +# Training loop +for data, targets in data_loader: + outputs = model(data) + loss = criterion(outputs, targets) + loss.backward() + optimizer.step() + optimizer.zero_grad() +``` + + + + +```python +from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs +import torch + +class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(10, 10) + + def forward(self, x): + return self.layer(x) + +# DDP Communication Hook setup +ddp_kwargs = DistributedDataParallelKwargs(comm_hook=DDPCommunicationHookType.BF16) +accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) + +model = MyModel() +optimizer = torch.optim.Adam(model.parameters()) +data_loader = DataLoader(dataset, batch_size=16) + +model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) + +# Training loop +for data, targets in data_loader: + outputs = model(data) + loss = criterion(outputs, targets) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + + + + +### PowerSGD Hook + + + +PowerSGD typically requires extra memory of the same size as the model’s gradients to enable error feedback, which can compensate for biased compressed communication and improve accuracy. + + + + + + +```python +import torch +from torch.nn.parallel import DistributedDataParallel as DDP +from torch.distributed.algorithms.ddp_comm_hooks import powerSGD_hook + +class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(10, 10) + + def forward(self, x): + return self.layer(x) + +model = MyModel() +model = DDP(model, device_ids=[torch.cuda.current_device()]) +state = powerSGD_hook.PowerSGDState(process_group=None) +model.register_comm_hook(state=state, hook=powerSGD_hook.powerSGD_hook) + +# Training loop +for data, targets in data_loader: + outputs = model(data) + loss = criterion(outputs, targets) + loss.backward() + optimizer.step() + optimizer.zero_grad() +``` + + + + +```python +from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs +import torch + +class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(10, 10) + + def forward(self, x): + return self.layer(x) + +# DDP Communication Hook setup +ddp_kwargs = DistributedDataParallelKwargs(comm_hook=DDPCommunicationHookType.POWER_SGD) +accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) + +model = MyModel() +optimizer = torch.optim.Adam(model.parameters()) +data_loader = DataLoader(dataset, batch_size=16) + +model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) + +# Training loop +for data, targets in data_loader: + outputs = model(data) + loss = criterion(outputs, targets) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + + + + +## DDP Communication Hooks utilities + +There are two additional utilities for supporting optional functionalities with the communication hooks. + +### comm_wrapper + +`comm_wrapper` is an option to wrap a communication hook with additional functionality. For example, it can be used to combine FP16 compression with other communication strategies. Currently supported wrappers are `no`, `fp16`, and `bf16`. + +```python +from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs +import torch + +class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(10, 10) + + def forward(self, x): + return self.layer(x) + +# DDP Communication Hook setup +ddp_kwargs = DistributedDataParallelKwargs( + comm_hook=DDPCommunicationHookType.POWER_SGD, + comm_wrapper=DDPCommunicationHookType.FP16 +) +accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) + +model = MyModel() +optimizer = torch.optim.Adam(model.parameters()) +data_loader = DataLoader(dataset, batch_size=16) + +model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) + +# Training loop +for data, targets in data_loader: + outputs = model(data) + loss = criterion(outputs, targets) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + +### comm_state_option + +`comm_state_option` allows you to pass additional state information required by certain communication hooks. This is particularly useful for stateful hooks like `PowerSGD`, which require maintaining hyperparameters and internal states across training steps. Below is an example showcasing the use of `comm_state_option` with the `PowerSGD` hook. + +```python +from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs +import torch + +class MyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.layer = torch.nn.Linear(10, 10) + + def forward(self, x): + return self.layer(x) + +# DDP Communication Hook setup +ddp_kwargs = DistributedDataParallelKwargs( + comm_hook=DDPCommunicationHookType.POWER_SGD, + comm_state_option={"matrix_approximation_rank": 2} +) +accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) + +model = MyModel() +optimizer = torch.optim.Adam(model.parameters()) +data_loader = DataLoader(dataset, batch_size=16) + +model, optimizer, data_loader = accelerator.prepare(model, optimizer, data_loader) + +# Training loop +for data, targets in data_loader: + outputs = model(data) + loss = criterion(outputs, targets) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + +For more advanced usage and additional hooks, refer to the [PyTorch DDP Communication Hooks documentation](https://pytorch.org/docs/stable/ddp_comm_hooks.html). diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/deepspeed.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..ca071a7eca5f5aab851682ed24acdd6b34e453ee --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/deepspeed.md @@ -0,0 +1,738 @@ + + +# DeepSpeed + +[DeepSpeed](https://github.com/microsoft/DeepSpeed) implements everything described in the [ZeRO paper](https://arxiv.org/abs/1910.02054). Some of the salient optimizations are: + +1. Optimizer state partitioning (ZeRO stage 1) +2. Gradient partitioning (ZeRO stage 2) +3. Parameter partitioning (ZeRO stage 3) +4. Custom mixed precision training handling +5. A range of fast CUDA-extension-based optimizers +6. ZeRO-Offload to CPU and Disk/NVMe +7. Hierarchical partitioning of model parameters (ZeRO++) + +ZeRO-Offload has its own dedicated paper: [ZeRO-Offload: Democratizing Billion-Scale Model Training](https://arxiv.org/abs/2101.06840). And NVMe-support is described in the paper [ZeRO-Infinity: Breaking the GPU +Memory Wall for Extreme Scale Deep Learning](https://arxiv.org/abs/2104.07857). + +DeepSpeed ZeRO-2 is primarily used only for training, as its features are of no use to inference. + +DeepSpeed ZeRO-3 can be used for inference as well since it allows huge models to be loaded on multiple GPUs, which +won't be possible on a single GPU. + +🤗 Accelerate integrates [DeepSpeed](https://github.com/microsoft/DeepSpeed) via 2 options: + +1. Integration of the DeepSpeed features via `deepspeed config file` specification in `accelerate config` . You just supply your custom config file or use our template. Most of + this document is focused on this feature. This supports all the core features of DeepSpeed and gives user a lot of flexibility. + User may have to change a few lines of code depending on the config. +2. Integration via `deepspeed_plugin`.This supports subset of the DeepSpeed features and uses default options for the rest of the configurations. + User need not change any code and is good for those who are fine with most of the default settings of DeepSpeed. + +## What is integrated? + +Training: + +1. 🤗 Accelerate integrates all features of DeepSpeed ZeRO. This includes all the ZeRO stages 1, 2 and 3 as well as ZeRO-Offload, ZeRO-Infinity (which can offload to disk/NVMe) and ZeRO++. +Below is a short description of Data Parallelism using ZeRO - Zero Redundancy Optimizer along with diagram from this [blog post](https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/) +![ZeRO Data Parallelism](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/parallelism-zero.png) + +(Source: [link](https://www.microsoft.com/en-us/research/blog/zero-deepspeed-new-system-optimizations-enable-training-models-with-over-100-billion-parameters/)) + + a. **Stage 1** : Shards optimizer states across data parallel workers/GPUs + + b. **Stage 2** : Shards optimizer states + gradients across data parallel workers/GPUs + + c. **Stage 3**: Shards optimizer states + gradients + model parameters across data parallel workers/GPUs + + d. **Optimizer Offload**: Offloads the gradients + optimizer states to CPU/Disk building on top of ZERO Stage 2 + + e. **Param Offload**: Offloads the model parameters to CPU/Disk building on top of ZERO Stage 3 + + f. **Hierarchical Partitioning**: Enables efficient multi-node training with data-parallel training across nodes and ZeRO-3 sharding within a node, built on top of ZeRO Stage 3. + +Note: With respect to Disk Offload, the disk should be an NVME for decent speed but it technically works on any Disk + +Inference: + +1. DeepSpeed ZeRO Inference supports ZeRO stage 3 with ZeRO-Infinity. It uses the same ZeRO protocol as training, but + it doesn't use an optimizer and a lr scheduler and only stage 3 is relevant. For more details see: + [deepspeed-zero-inference](#deepspeed-zero-inference). + + +## How it works? + +**Pre-Requisites**: Install DeepSpeed version >=0.6.5. Please refer to the [DeepSpeed Installation details](https://github.com/microsoft/DeepSpeed#installation) +for more information. + +We will first look at easy to use integration via `accelerate config`. +Followed by more flexible and feature rich `deepspeed config file` integration. + +### Accelerate DeepSpeed Plugin +On your machine(s) just run: + +```bash +accelerate config +``` + +and answer the questions asked. It will ask whether you want to use a config file for DeepSpeed to which you should answer no. Then answer the following questions to generate a basic DeepSpeed config. +This will generate a config file that will be used automatically to properly set the +default options when doing + +```bash +accelerate launch my_script.py --args_to_my_script +``` + +For instance, here is how you would run the NLP example `examples/nlp_example.py` (from the root of the repo) with DeepSpeed Plugin: + +**ZeRO Stage-2 DeepSpeed Plugin Example** +```bash +compute_environment: LOCAL_MACHINE +deepspeed_config: + gradient_accumulation_steps: 1 + gradient_clipping: 1.0 + offload_optimizer_device: none + offload_param_device: none + zero3_init_flag: true + zero_stage: 2 +distributed_type: DEEPSPEED +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: fp16 +num_machines: 1 +num_processes: 2 +use_cpu: false +``` + +```bash +accelerate launch examples/nlp_example.py --mixed_precision fp16 +``` + +**ZeRO Stage-3 with CPU Offload DeepSpeed Plugin Example** +```bash +compute_environment: LOCAL_MACHINE +deepspeed_config: + gradient_accumulation_steps: 1 + gradient_clipping: 1.0 + offload_optimizer_device: cpu + offload_param_device: cpu + zero3_init_flag: true + zero3_save_16bit_model: true + zero_stage: 3 +distributed_type: DEEPSPEED +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: fp16 +num_machines: 1 +num_processes: 2 +use_cpu: false +``` + +```bash +accelerate launch examples/nlp_example.py --mixed_precision fp16 +``` + +Currently, `Accelerate` supports following config through the CLI: + +```bash +`zero_stage`: [0] Disabled, [1] optimizer state partitioning, [2] optimizer+gradient state partitioning and [3] optimizer+gradient+parameter partitioning +`gradient_accumulation_steps`: Number of training steps to accumulate gradients before averaging and applying them. +`gradient_clipping`: Enable gradient clipping with value. +`offload_optimizer_device`: [none] Disable optimizer offloading, [cpu] offload optimizer to CPU, [nvme] offload optimizer to NVMe SSD. Only applicable with ZeRO >= Stage-2. +`offload_optimizer_nvme_path`: Decides Nvme Path to offload optimizer states. If unspecified, will default to 'none'. +`offload_param_device`: [none] Disable parameter offloading, [cpu] offload parameters to CPU, [nvme] offload parameters to NVMe SSD. Only applicable with ZeRO Stage-3. +`offload_param_nvme_path`: Decides Nvme Path to offload parameters. If unspecified, will default to 'none'. +`zero3_init_flag`: Decides whether to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with ZeRO Stage-3. +`zero3_save_16bit_model`: Decides whether to save 16-bit model weights when using ZeRO Stage-3. +`mixed_precision`: `no` for FP32 training, `fp16` for FP16 mixed-precision training and `bf16` for BF16 mixed-precision training. +`deepspeed_moe_layer_cls_names`: Comma-separated list of transformer Mixture-of-Experts (MoE) layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ... +`deepspeed_hostfile`: DeepSpeed hostfile for configuring multi-node compute resources. +`deepspeed_exclusion_filter`: DeepSpeed exclusion filter string when using mutli-node setup. +`deepspeed_inclusion_filter`: DeepSpeed inclusion filter string when using mutli-node setup. +`deepspeed_multinode_launcher`: DeepSpeed multi-node launcher to use. If unspecified, will default to `pdsh`. +`deepspeed_config_file`: path to the DeepSpeed config file in `json` format. See the next section for more details on this. +``` +To be able to tweak more options, you will need to use a DeepSpeed config file. + +### DeepSpeed Config File +On your machine(s) just run: + +```bash +accelerate config +``` + +and answer the questions asked. It will ask whether you want to use a config file for deepspeed to which you answer yes +and provide the path to the deepspeed config file. +This will generate a config file that will be used automatically to properly set the +default options when doing + +```bash +accelerate launch my_script.py --args_to_my_script +``` + +For instance, here is how you would run the NLP example `examples/by_feature/deepspeed_with_config_support.py` (from the root of the repo) with DeepSpeed Config File: + +**ZeRO Stage-2 DeepSpeed Config File Example** +```bash +compute_environment: LOCAL_MACHINE +deepspeed_config: + deepspeed_config_file: /home/ubuntu/accelerate/examples/configs/deepspeed_config_templates/zero_stage2_config.json + zero3_init_flag: true +distributed_type: DEEPSPEED +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: fp16 +num_machines: 1 +num_processes: 2 +use_cpu: false +``` + +with the contents of `zero_stage2_config.json` being: +```json +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto", + "torch_adam": true, + "adam_w_mode": true + } + }, + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto", + "total_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 2, + "allgather_partitions": true, + "allgather_bucket_size": 2e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": "auto", + "contiguous_gradients": true + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} +``` + +```bash +accelerate launch examples/by_feature/deepspeed_with_config_support.py \ +--config_name "gpt2-large" \ +--tokenizer_name "gpt2-large" \ +--dataset_name "wikitext" \ +--dataset_config_name "wikitext-2-raw-v1" \ +--block_size 128 \ +--output_dir "./clm/clm_deepspeed_stage2_accelerate" \ +--learning_rate 5e-4 \ +--per_device_train_batch_size 24 \ +--per_device_eval_batch_size 24 \ +--num_train_epochs 3 \ +--with_tracking \ +--report_to "wandb"\ +``` + +**ZeRO Stage-3 with CPU offload DeepSpeed Config File Example** +```bash +compute_environment: LOCAL_MACHINE +deepspeed_config: + deepspeed_config_file: /home/ubuntu/accelerate/examples/configs/deepspeed_config_templates/zero_stage3_offload_config.json + zero3_init_flag: true +distributed_type: DEEPSPEED +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: fp16 +num_machines: 1 +num_processes: 2 +use_cpu: false +``` +with the contents of `zero_stage3_offload_config.json` being: +```json +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto" + } + }, + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto", + "total_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "sub_group_size": 1e9, + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": "auto" + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} +``` + +```bash +accelerate launch examples/by_feature/deepspeed_with_config_support.py \ +--config_name "gpt2-large" \ +--tokenizer_name "gpt2-large" \ +--dataset_name "wikitext" \ +--dataset_config_name "wikitext-2-raw-v1" \ +--block_size 128 \ +--output_dir "./clm/clm_deepspeed_stage3_offload_accelerate" \ +--learning_rate 5e-4 \ +--per_device_train_batch_size 32 \ +--per_device_eval_batch_size 32 \ +--num_train_epochs 3 \ +--with_tracking \ +--report_to "wandb"\ +``` + +**ZeRO++ Config Example** +You can use the features of ZeRO++ by using the appropriate config parameters. Note that ZeRO++ is an extension for ZeRO Stage 3. Here is how the config file can be modified, from [DeepSpeed's ZeRO++ tutorial](https://www.deepspeed.ai/tutorials/zeropp/): + +```json +{ + "zero_optimization": { + "stage": 3, + "reduce_bucket_size": "auto", + + "zero_quantized_weights": true, + "zero_hpz_partition_size": 8, + "zero_quantized_gradients": true, + + "contiguous_gradients": true, + "overlap_comm": true + } +} +``` + +For hierarchical partitioning, the partition size `zero_hpz_partition_size` should ideally be set to the number of GPUs per node. (For example, the above config file assumes 8 GPUs per node) + +**Important code changes when using DeepSpeed Config File** + +1. DeepSpeed Optimizers and Schedulers. For more information on these, +see the [DeepSpeed Optimizers](https://deepspeed.readthedocs.io/en/latest/optimizers.html) and [DeepSpeed Schedulers](https://deepspeed.readthedocs.io/en/latest/schedulers.html) documentation. +We will look at the changes needed in the code when using these. + + a. DS Optim + DS Scheduler: The case when both `optimizer` and `scheduler` keys are present in the DeepSpeed config file. + In this situation, those will be used and the user has to use `accelerate.utils.DummyOptim` and `accelerate.utils.DummyScheduler` to replace the PyTorch/Custom optimizers and schedulers in their code. + Below is the snippet from `examples/by_feature/deepspeed_with_config_support.py` showing this: + ```python + # Creates Dummy Optimizer if `optimizer` was specified in the config file else creates Adam Optimizer + optimizer_cls = ( + torch.optim.AdamW + if accelerator.state.deepspeed_plugin is None + or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config + else DummyOptim + ) + optimizer = optimizer_cls(optimizer_grouped_parameters, lr=args.learning_rate) + + # Creates Dummy Scheduler if `scheduler` was specified in the config file else creates `args.lr_scheduler_type` Scheduler + if ( + accelerator.state.deepspeed_plugin is None + or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config + ): + lr_scheduler = get_scheduler( + name=args.lr_scheduler_type, + optimizer=optimizer, + num_warmup_steps=args.num_warmup_steps, + num_training_steps=args.max_train_steps, + ) + else: + lr_scheduler = DummyScheduler( + optimizer, total_num_steps=args.max_train_steps, warmup_num_steps=args.num_warmup_steps + ) + ``` + b. Custom Optim + Custom Scheduler: The case when both `optimizer` and `scheduler` keys are absent in the DeepSpeed config file. + In this situation, no code changes are needed from the user and this is the case when using integration via DeepSpeed Plugin. + In the above example we can see that the code remains unchanged if the `optimizer` and `scheduler` keys are absent in the DeepSpeed config file. + + c. Custom Optim + DS Scheduler: The case when only `scheduler` key is present in the DeepSpeed config file. + In this situation, the user has to use `accelerate.utils.DummyScheduler` to replace the PyTorch/Custom scheduler in their code. + + d. DS Optim + Custom Scheduler: The case when only `optimizer` key is present in the DeepSpeed config file. + This will result in an error because you can only use DS Scheduler when using DS Optim. + +2. Notice the `auto` values in the above example DeepSpeed config files. These are automatically handled by `prepare` method +based on model, dataloaders, dummy optimizer and dummy schedulers provided to `prepare` method. +Only the `auto` fields specified in above examples are handled by `prepare` method and the rest have to be explicitly specified by the user. + +The `auto` values are calculated as: + +- `reduce_bucket_size`: `hidden_size * hidden_size` +- `stage3_prefetch_bucket_size`: `int(0.9 * hidden_size * hidden_size)` +- `stage3_param_persistence_threshold`: `10 * hidden_size` + +For the `auto` feature to work for these 3 config entries - Accelerate will use `model.config.hidden_size` or `max(model.config.hidden_sizes)` as `hidden_size`. If neither of these is available, the launching will fail and you will have to set these 3 config entries manually. Remember the first 2 config entries are the communication buffers - the larger they are the more efficient the comms will be, and the larger they are the more GPU memory they will consume, so it's a tunable performance trade-off. + + +**Things to note when using DeepSpeed Config File** + +Below is a sample script using `deepspeed_config_file` in different scenarios. + +Code `test.py`: + +```python +from accelerate import Accelerator +from accelerate.state import AcceleratorState + + +def main(): + accelerator = Accelerator() + accelerator.print(f"{AcceleratorState()}") + + +if __name__ == "__main__": + main() +``` + +**Scenario 1**: Manually tampered accelerate config file having `deepspeed_config_file` along with other entries. + +1. Content of the `accelerate` config: + +```yaml +command_file: null +commands: null +compute_environment: LOCAL_MACHINE +deepspeed_config: + gradient_accumulation_steps: 1 + gradient_clipping: 1.0 + offload_optimizer_device: 'cpu' + offload_param_device: 'cpu' + zero3_init_flag: true + zero3_save_16bit_model: true + zero_stage: 3 + deepspeed_config_file: 'ds_config.json' +distributed_type: DEEPSPEED +downcast_bf16: 'no' +dynamo_backend: 'NO' +fsdp_config: {} +gpu_ids: null +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +megatron_lm_config: {} +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_name: null +tpu_zone: null +use_cpu: false +``` + +2. `ds_config.json`: + +```json +{ + "bf16": { + "enabled": true + }, + "zero_optimization": { + "stage": 3, + "stage3_gather_16bit_weights_on_model_save": false, + "offload_optimizer": { + "device": "none" + }, + "offload_param": { + "device": "none" + } + }, + "gradient_clipping": 1.0, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "gradient_accumulation_steps": 10, + "steps_per_print": 2000000 +} +``` + +3. Output of `accelerate launch test.py`: + +```bash +ValueError: When using `deepspeed_config_file`, the following accelerate config variables will be ignored: +['gradient_accumulation_steps', 'gradient_clipping', 'zero_stage', 'offload_optimizer_device', 'offload_param_device', +'zero3_save_16bit_model', 'mixed_precision']. +Please specify them appropriately in the DeepSpeed config file. +If you are using an accelerate config file, remove other config variables mentioned in the above specified list. +The easiest method is to create a new config following the questionnaire via `accelerate config`. +It will only ask for the necessary config variables when using `deepspeed_config_file`. +``` + +**Scenario 2**: Use the solution of the error to create new accelerate config and check that no ambiguity error is now thrown. + +1. Run `accelerate config`: + +```bash +$ accelerate config +------------------------------------------------------------------------------------------------------------------------------- +In which compute environment are you running? +This machine +------------------------------------------------------------------------------------------------------------------------------- +Which type of machine are you using? +multi-GPU +How many different machines will you use (use more than 1 for multi-node training)? [1]: +Do you wish to optimize your script with torch dynamo?[yes/NO]: +Do you want to use DeepSpeed? [yes/NO]: yes +Do you want to specify a json file to a DeepSpeed config? [yes/NO]: yes +Please enter the path to the json DeepSpeed config file: ds_config.json +Do you want to enable `deepspeed.zero.Init` when using ZeRO Stage-3 for constructing massive models? [yes/NO]: yes +How many GPU(s) should be used for distributed training? [1]:4 +accelerate configuration saved at ds_config_sample.yaml +``` + +2. Content of the `accelerate` config: + +```yaml +compute_environment: LOCAL_MACHINE +deepspeed_config: + deepspeed_config_file: ds_config.json + zero3_init_flag: true +distributed_type: DEEPSPEED +downcast_bf16: 'no' +dynamo_backend: 'NO' +fsdp_config: {} +machine_rank: 0 +main_training_function: main +megatron_lm_config: {} +num_machines: 1 +num_processes: 4 +rdzv_backend: static +same_network: true +use_cpu: false +``` + +3. Output of `accelerate launch test.py`: + +```bash +Distributed environment: DEEPSPEED Backend: nccl +Num processes: 4 +Process index: 0 +Local process index: 0 +Device: cuda:0 +Mixed precision type: bf16 +ds_config: {'bf16': {'enabled': True}, 'zero_optimization': {'stage': 3, 'stage3_gather_16bit_weights_on_model_save': False, 'offload_optimizer': {'device': 'none'}, 'offload_param': {'device': 'none'}}, 'gradient_clipping': 1.0, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'gradient_accumulation_steps': 10, 'steps_per_print': inf, 'fp16': {'enabled': False}} +``` + +**Scenario 3**: Setting the `accelerate launch` command arguments related to DeepSpeed as `"auto"` in the DeepSpeed` configuration file and check that things work as expected. + +1. New `ds_config.json` with `"auto"` for the `accelerate launch` DeepSpeed command arguments: + +```json +{ + "bf16": { + "enabled": "auto" + }, + "zero_optimization": { + "stage": "auto", + "stage3_gather_16bit_weights_on_model_save": "auto", + "offload_optimizer": { + "device": "auto" + }, + "offload_param": { + "device": "auto" + } + }, + "gradient_clipping": "auto", + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "gradient_accumulation_steps": "auto", + "steps_per_print": 2000000 +} +``` + +2. Output of `accelerate launch --mixed_precision="fp16" --zero_stage=3 --gradient_accumulation_steps=5 --gradient_clipping=1.0 --offload_param_device="cpu" --offload_optimizer_device="nvme" --zero3_save_16bit_model="true" test.py`: + +```bash +Distributed environment: DEEPSPEED Backend: nccl +Num processes: 4 +Process index: 0 +Local process index: 0 +Device: cuda:0 +Mixed precision type: fp16 +ds_config: {'bf16': {'enabled': False}, 'zero_optimization': {'stage': 3, 'stage3_gather_16bit_weights_on_model_save': True, 'offload_optimizer': {'device': 'nvme'}, 'offload_param': {'device': 'cpu'}}, 'gradient_clipping': 1.0, 'train_batch_size': 'auto', 'train_micro_batch_size_per_gpu': 'auto', 'gradient_accumulation_steps': 5, 'steps_per_print': inf, 'fp16': {'enabled': True, 'auto_cast': True}} +``` + +**Note**: +1. Remaining `"auto"` values are handled in `accelerator.prepare()` call as explained in point 2 of +`Important code changes when using DeepSpeed Config File`. +2. Only when `gradient_accumulation_steps` is `auto`, the value passed while creating `Accelerator` object via `Accelerator(gradient_accumulation_steps=k)` will be used. When using DeepSpeed Plugin, the value from it will be used and it will overwrite the value passed while creating Accelerator object. + +## Saving and loading + +1. Saving and loading of models is unchanged for ZeRO Stage-1 and Stage-2. + +2. under ZeRO Stage-3, `state_dict` contains just the placeholders since the model weights are partitioned across multiple GPUs. +ZeRO Stage-3 has 2 options: + + a. Saving the entire 16bit model weights to directly load later on using `model.load_state_dict(torch.load(pytorch_model.bin))`. + For this, either set `zero_optimization.stage3_gather_16bit_weights_on_model_save` to True in DeepSpeed Config file or set + `zero3_save_16bit_model` to True in DeepSpeed Plugin. + **Note that this option requires consolidation of the weights on one GPU it can be slow and memory demanding, so only use this feature when needed.** + Below is the snippet from `examples/by_feature/deepspeed_with_config_support.py` showing this: + ```python + unwrapped_model = accelerator.unwrap_model(model) + + # New Code # + # Saves the whole/unpartitioned fp16 model when in ZeRO Stage-3 to the output directory if + # `stage3_gather_16bit_weights_on_model_save` is True in DeepSpeed Config file or + # `zero3_save_16bit_model` is True in DeepSpeed Plugin. + # For Zero Stages 1 and 2, models are saved as usual in the output directory. + # The model name saved is `pytorch_model.bin` + unwrapped_model.save_pretrained( + args.output_dir, + is_main_process=accelerator.is_main_process, + save_function=accelerator.save, + state_dict=accelerator.get_state_dict(model), + ) + ``` + + b. To get 32bit weights, first save the model using `model.save_checkpoint()`. + Below is the snippet from `examples/by_feature/deepspeed_with_config_support.py` showing this: + ```python + success = model.save_checkpoint(PATH, ckpt_id, checkpoint_state_dict) + status_msg = f"checkpointing: PATH={PATH}, ckpt_id={ckpt_id}" + if success: + logging.info(f"Success {status_msg}") + else: + logging.warning(f"Failure {status_msg}") + ``` + This will create ZeRO model and optimizer partitions along with `zero_to_fp32.py` script in checkpoint directory. + You can use this script to do offline consolidation. + It requires no configuration files or GPUs. Here is an example of its usage: + ```bash + $ cd /path/to/checkpoint_dir + $ ./zero_to_fp32.py . pytorch_model.bin + Processing zero checkpoint at global_step1 + Detected checkpoint of type zero stage 3, world_size: 2 + Saving fp32 state dict to pytorch_model.bin (total_numel=60506624) + ``` + To get 32bit model for saving/inference, you can perform: + ```python + from deepspeed.utils.zero_to_fp32 import load_state_dict_from_zero_checkpoint + + unwrapped_model = accelerator.unwrap_model(model) + fp32_model = load_state_dict_from_zero_checkpoint(unwrapped_model, checkpoint_dir) + ``` + If you are only interested in the `state_dict`, you can do the following: + ```python + from deepspeed.utils.zero_to_fp32 import get_fp32_state_dict_from_zero_checkpoint + + state_dict = get_fp32_state_dict_from_zero_checkpoint(checkpoint_dir) + ``` + Note that all these functions require ~2x memory (general RAM) of the size of the final checkpoint. + +## ZeRO Inference +DeepSpeed ZeRO Inference supports ZeRO stage 3 with ZeRO-Infinity. +It uses the same ZeRO protocol as training, but it doesn't use an optimizer and a lr scheduler and only stage 3 is relevant. +With accelerate integration, you just need to prepare the model and dataloader as shown below: + +```python +model, eval_dataloader = accelerator.prepare(model, eval_dataloader) +``` + +## Few caveats to be aware of + +1. Current integration doesn’t support Pipeline Parallelism of DeepSpeed. +2. Current integration doesn’t support `mpu`, limiting the tensor parallelism which is supported in Megatron-LM. +3. Current integration doesn’t support multiple models. + +## DeepSpeed Resources + +The documentation for the internals related to deepspeed can be found [here](../package_reference/deepspeed). + +- [Project's github](https://github.com/microsoft/deepspeed) +- [Usage docs](https://www.deepspeed.ai/getting-started/) +- [API docs](https://deepspeed.readthedocs.io/en/latest/index.html) +- [Blog posts](https://www.microsoft.com/en-us/research/search/?q=deepspeed) + +Papers: + +- [ZeRO: Memory Optimizations Toward Training Trillion Parameter Models](https://arxiv.org/abs/1910.02054) +- [ZeRO-Offload: Democratizing Billion-Scale Model Training](https://arxiv.org/abs/2101.06840) +- [ZeRO-Infinity: Breaking the GPU Memory Wall for Extreme Scale Deep Learning](https://arxiv.org/abs/2104.07857) +- [ZeRO++: Extremely Efficient Collective Communication for Giant Model Training](https://arxiv.org/abs/2306.10209) + + +Finally, please, remember that 🤗 `Accelerate` only integrates DeepSpeed, therefore if you +have any problems or questions with regards to DeepSpeed usage, please, file an issue with [DeepSpeed GitHub](https://github.com/microsoft/DeepSpeed/issues). + + + + + For those interested in the similarities and differences between FSDP and DeepSpeed, please check out the [concept guide here](../concept_guides/fsdp_and_deepspeed)! + + \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/distributed_inference.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/distributed_inference.md new file mode 100644 index 0000000000000000000000000000000000000000..045630bf3ab34e61f08e5b16551b14b8fdc759cc --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/distributed_inference.md @@ -0,0 +1,237 @@ + + +# Distributed Inference with 🤗 Accelerate + +Distributed inference can fall into three brackets: + +1. Loading an entire model onto each GPU and sending chunks of a batch through each GPU's model copy at a time +2. Loading parts of a model onto each GPU and processing a single input at one time +3. Loading parts of a model onto each GPU and using what is called scheduled Pipeline Parallelism to combine the two prior techniques. + +We're going to go through the first and the last bracket, showcasing how to do each as they are more realistic scenarios. + + +## Sending chunks of a batch automatically to each loaded model + +This is the most memory-intensive solution, as it requires each GPU to keep a full copy of the model in memory at a given time. + +Normally when doing this, users send the model to a specific device to load it from the CPU, and then move each prompt to a different device. + +A basic pipeline using the `diffusers` library might look something like so: + +```python +import torch +import torch.distributed as dist +from diffusers import DiffusionPipeline + +pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) +``` +Followed then by performing inference based on the specific prompt: + +```python +def run_inference(rank, world_size): + dist.init_process_group("nccl", rank=rank, world_size=world_size) + pipe.to(rank) + + if torch.distributed.get_rank() == 0: + prompt = "a dog" + elif torch.distributed.get_rank() == 1: + prompt = "a cat" + + result = pipe(prompt).images[0] + result.save(f"result_{rank}.png") +``` +One will notice how we have to check the rank to know what prompt to send, which can be a bit tedious. + +A user might then also think that with 🤗 Accelerate, using the `Accelerator` to prepare a dataloader for such a task might also be +a simple way to manage this. (To learn more, check out the relevant section in the [Quick Tour](../quicktour#distributed-evaluation)) + +Can it manage it? Yes. Does it add unneeded extra code however: also yes. + + +With 🤗 Accelerate, we can simplify this process by using the [`Accelerator.split_between_processes`] context manager (which also exists in `PartialState` and `AcceleratorState`). +This function will automatically split whatever data you pass to it (be it a prompt, a set of tensors, a dictionary of the prior data, etc.) across all the processes (with a potential +to be padded) for you to use right away. + +Let's rewrite the above example using this context manager: + +```python +from accelerate import PartialState # Can also be Accelerator or AcceleratorState +from diffusers import DiffusionPipeline + +pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) +distributed_state = PartialState() +pipe.to(distributed_state.device) + +# Assume two processes +with distributed_state.split_between_processes(["a dog", "a cat"]) as prompt: + result = pipe(prompt).images[0] + result.save(f"result_{distributed_state.process_index}.png") +``` + +And then to launch the code, we can use the 🤗 Accelerate: + +If you have generated a config file to be used using `accelerate config`: + +```bash +accelerate launch distributed_inference.py +``` + +If you have a specific config file you want to use: + +```bash +accelerate launch --config_file my_config.json distributed_inference.py +``` + +Or if don't want to make any config files and launch on two GPUs: + +> Note: You will get some warnings about values being guessed based on your system. To remove these you can do `accelerate config default` or go through `accelerate config` to create a config file. + +```bash +accelerate launch --num_processes 2 distributed_inference.py +``` + +We've now reduced the boilerplate code needed to split this data to a few lines of code quite easily. + +But what if we have an odd distribution of prompts to GPUs? For example, what if we have 3 prompts, but only 2 GPUs? + +Under the context manager, the first GPU would receive the first two prompts and the second GPU the third, ensuring that +all prompts are split and no overhead is needed. + +*However*, what if we then wanted to do something with the results of *all the GPUs*? (Say gather them all and perform some kind of post processing) +You can pass in `apply_padding=True` to ensure that the lists of prompts are padded to the same length, with extra data being taken +from the last sample. This way all GPUs will have the same number of prompts, and you can then gather the results. + + + +This is only needed when trying to perform an action such as gathering the results, where the data on each device +needs to be the same length. Basic inference does not require this. + + + +For instance: + +```python +from accelerate import PartialState # Can also be Accelerator or AcceleratorState +from diffusers import DiffusionPipeline + +pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) +distributed_state = PartialState() +pipe.to(distributed_state.device) + +# Assume two processes +with distributed_state.split_between_processes(["a dog", "a cat", "a chicken"], apply_padding=True) as prompt: + result = pipe(prompt).images +``` + +On the first GPU, the prompts will be `["a dog", "a cat"]`, and on the second GPU it will be `["a chicken", "a chicken"]`. +Make sure to drop the final sample, as it will be a duplicate of the previous one. + +You can find more complex examples [here](https://github.com/huggingface/accelerate/tree/main/examples/inference/distributed) such as how to use it with LLMs. + +## Memory-efficient pipeline parallelism (experimental) + +This next part will discuss using *pipeline parallelism*. This is an **experimental** API utilizing the [PiPPy library by PyTorch](https://github.com/pytorch/PiPPy/) as a native solution. + +The general idea with pipeline parallelism is: say you have 4 GPUs and a model big enough it can be *split* on four GPUs using `device_map="auto"`. With this method you can send in 4 inputs at a time (for example here, any amount works) and each model chunk will work on an input, then receive the next input once the prior chunk finished, making it *much* more efficient **and faster** than the method described earlier. Here's a visual taken from the PyTorch repository: + +![PiPPy example](https://camo.githubusercontent.com/681d7f415d6142face9dd1b837bdb2e340e5e01a58c3a4b119dea6c0d99e2ce0/68747470733a2f2f692e696d6775722e636f6d2f657955633934372e706e67) + +To illustrate how you can use this with Accelerate, we have created an [example zoo](https://github.com/huggingface/accelerate/tree/main/examples/inference) showcasing a number of different models and situations. In this tutorial, we'll show this method for GPT2 across two GPUs. + +Before you proceed, please make sure you have the latest pippy installed by running the following: + +```bash +pip install torchpippy +``` + +We require at least version 0.2.0. To confirm that you have the correct version, run `pip show torchpippy`. + +Start by creating the model on the CPU: + +```{python} +from transformers import GPT2ForSequenceClassification, GPT2Config + +config = GPT2Config() +model = GPT2ForSequenceClassification(config) +model.eval() +``` + +Next you'll need to create some example inputs to use. These help PiPPy trace the model. + + + However you make this example will determine the relative batch size that will be used/passed + through the model at a given time, so make sure to remember how many items there are! + + +```{python} +input = torch.randint( + low=0, + high=config.vocab_size, + size=(2, 1024), # bs x seq_len + device="cpu", + dtype=torch.int64, + requires_grad=False, +) +``` +Next we need to actually perform the tracing and get the model ready. To do so, use the [`inference.prepare_pippy`] function and it will fully wrap the model for pipeline parallelism automatically: + +```{python} +from accelerate.inference import prepare_pippy +example_inputs = {"input_ids": input} +model = prepare_pippy(model, example_args=(input,)) +``` + + + + There are a variety of parameters you can pass through to `prepare_pippy`: + + * `split_points` lets you determine what layers to split the model at. By default we use wherever `device_map="auto" declares, such as `fc` or `conv1`. + + * `num_chunks` determines how the batch will be split and sent to the model itself (so `num_chunks=1` with four split points/four GPUs will have a naive MP where a single input gets passed between the four layer split points) + + + +From here, all that's left is to actually perform the distributed inference! + + + +When passing inputs, we highly recommend to pass them in as a tuple of arguments. Using `kwargs` is supported, however, this approach is experimental. + + +```{python} +args = some_more_arguments +with torch.no_grad(): + output = model(*args) +``` + +When finished all the data will be on the last process only: + +```{python} +from accelerate import PartialState +if PartialState().is_last_process: + print(output) +``` + + + + If you pass in `gather_output=True` to [`inference.prepare_pippy`], the output will be sent + across to all the GPUs afterwards without needing the `is_last_process` check. This is + `False` by default as it incurs a communication call. + + + +And that's it! To explore more, please check out the inference examples in the [Accelerate repo](https://github.com/huggingface/accelerate/tree/main/examples/inference/pippy) and our [documentation](../package_reference/inference) as we work to improving this integration. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/explore.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/explore.md new file mode 100644 index 0000000000000000000000000000000000000000..533c4cf444fd5d12ac63d4ce1da5073a82054468 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/explore.md @@ -0,0 +1,51 @@ + + +# Learning how to incorporate 🤗 Accelerate features quickly! + +Please use the interactive tool below to help you get started with learning about a particular +feature of 🤗 Accelerate and how to utilize it! It will provide you with a code diff, an explanation +towards what is going on, as well as provide you with some useful links to explore more within +the documentation! + +Most code examples start from the following python code before integrating 🤗 Accelerate in some way: + +```python +for batch in dataloader: + optimizer.zero_grad() + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) + loss.backward() + optimizer.step() + scheduler.step() +``` + +
+ +
+ diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/fsdp.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/fsdp.md new file mode 100644 index 0000000000000000000000000000000000000000..f315d6b5edca4db80947880080a259a31323f551 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/fsdp.md @@ -0,0 +1,200 @@ + + +# Fully Sharded Data Parallel + +To accelerate training huge models on larger batch sizes, we can use a fully sharded data parallel model. +This type of data parallel paradigm enables fitting more data and larger models by sharding the optimizer states, gradients and parameters. +To read more about it and the benefits, check out the [Fully Sharded Data Parallel blog](https://pytorch.org/blog/introducing-pytorch-fully-sharded-data-parallel-api/). +We have integrated the latest PyTorch's Fully Sharded Data Parallel (FSDP) training feature. +All you need to do is enable it through the config. + +## How it works out of the box + +On your machine(s) just run: + +```bash +accelerate config +``` + +and answer the questions asked. This will generate a config file that will be used automatically to properly set the +default options when doing + +```bash +accelerate launch my_script.py --args_to_my_script +``` + +For instance, here is how you would run `examples/nlp_example.py` (from the root of the repo) with FSDP enabled: + +```bash +compute_environment: LOCAL_MACHINE +debug: false +distributed_type: FSDP +downcast_bf16: 'no' +fsdp_config: + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch_policy: BACKWARD_PRE + fsdp_forward_prefetch: false + fsdp_cpu_ram_efficient_loading: true + fsdp_offload_params: false + fsdp_sharding_strategy: FULL_SHARD + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_transformer_layer_cls_to_wrap: BertLayer + fsdp_use_orig_params: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 2 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: false +``` + +```bash +accelerate launch examples/nlp_example.py +``` + +Currently, `Accelerate` supports the following config through the CLI: + +`fsdp_sharding_strategy`: [1] FULL_SHARD (shards optimizer states, gradients and parameters), [2] SHARD_GRAD_OP (shards optimizer states and gradients), [3] NO_SHARD (DDP), [4] HYBRID_SHARD (shards optimizer states, gradients and parameters within each node while each node has full copy), [5] HYBRID_SHARD_ZERO2 (shards optimizer states and gradients within each node while each node has full copy). For more information, please refer the official [PyTorch docs](https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.ShardingStrategy). + +`fsdp_offload_params` : Decides Whether to offload parameters and gradients to CPU + +`fsdp_auto_wrap_policy`: [1] TRANSFORMER_BASED_WRAP, [2] SIZE_BASED_WRAP, [3] NO_WRAP + +`fsdp_transformer_layer_cls_to_wrap`: Only applicable for 🤗 Transformers. When using `fsdp_auto_wrap_policy=TRANSFORMER_BASED_WRAP`, a user may provide a comma-separated string of transformer layer class names (case-sensitive) to wrap, e.g., `BertLayer`, `GPTJBlock`, `T5Block`, `BertLayer,BertEmbeddings,BertSelfOutput`. This is important because submodules that share weights (e.g., embedding layers) should not end up in different FSDP wrapped units. Using this policy, wrapping happens for each block containing Multi-Head Attention followed by a couple of MLP layers. Remaining layers including the shared embeddings are conveniently wrapped in same outermost FSDP unit. Therefore, use this for transformer-based models. You can use the `model._no_split_modules` for 🤗 Transformer models by answering `yes` to `Do you want to use the model's `_no_split_modules` to wrap. It will try to use `model._no_split_modules` when possible. + +`fsdp_min_num_params`: minimum number of parameters when using `fsdp_auto_wrap_policy=SIZE_BASED_WRAP`. + +`fsdp_backward_prefetch_policy`: [1] BACKWARD_PRE, [2] BACKWARD_POST, [3] NO_PREFETCH + +`fsdp_forward_prefetch`: if True, then FSDP explicitly prefetches the next upcoming all-gather while executing in the forward pass. Should only be used for static-graph models since the prefetching follows the first iteration’s execution order. i.e., if the sub-modules' order changes dynamically during the model's execution do not enable this feature. + +`fsdp_state_dict_type`: [1] FULL_STATE_DICT, [2] LOCAL_STATE_DICT, [3] SHARDED_STATE_DICT + +`fsdp_use_orig_params`: If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable parameters. This setting is useful in cases such as parameter-efficient fine-tuning as discussed in [this post](https://dev-discuss.pytorch.org/t/rethinking-pytorch-fully-sharded-data-parallel-fsdp-from-first-principles/1019). This option also allows one to have multiple optimizer param groups. This should be `True` when creating an optimizer before preparing/wrapping the model with FSDP. + +`fsdp_cpu_ram_efficient_loading`: Only applicable for 🤗 Transformers models. If True, only the first process loads the pretrained model checkpoint while all other processes have empty weights. This should be set to False if you experience errors when loading the pretrained 🤗 Transformers model via `from_pretrained` method. When this setting is True `fsdp_sync_module_states` also must to be True, otherwise all the processes except the main process would have random weights leading to unexpected behaviour during training. For this to work, make sure the distributed process group is initialized before calling Transformers `from_pretrained` method. When using 🤗 Trainer API, the distributed process group is initialized when you create an instance of `TrainingArguments` class. + +`fsdp_sync_module_states`: If True, each individually wrapped FSDP unit will broadcast module parameters from rank 0. + + +For additional and more nuanced control, you can specify other FSDP parameters via `FullyShardedDataParallelPlugin`. +When creating `FullyShardedDataParallelPlugin` object, pass it the parameters that weren't part of the accelerate config or if you want to override them. +The FSDP parameters will be picked based on the accelerate config file or launch command arguments and other parameters that you will pass directly through the `FullyShardedDataParallelPlugin` object will set/override that. + +Below is an example: + +```py +from accelerate import FullyShardedDataParallelPlugin +from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig + +fsdp_plugin = FullyShardedDataParallelPlugin( + state_dict_config=FullStateDictConfig(offload_to_cpu=False, rank0_only=False), + optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=False, rank0_only=False), +) + +accelerator = Accelerator(fsdp_plugin=fsdp_plugin) +``` + +## Saving and loading + +The new recommended way of checkpointing when using FSDP models is to use `SHARDED_STATE_DICT` as `StateDictType` when setting up the accelerate config. +Below is the code snippet to save using `save_state` utility of accelerate. + +```py +accelerator.save_state("ckpt") +``` + +Inspect the checkpoint folder to see model and optimizer as shards per process: +``` +ls ckpt +# optimizer_0 pytorch_model_0 random_states_0.pkl random_states_1.pkl scheduler.bin + +cd ckpt + +ls optimizer_0 +# __0_0.distcp __1_0.distcp + +ls pytorch_model_0 +# __0_0.distcp __1_0.distcp +``` + +To load them back for resuming the training, use the `load_state` utility of accelerate + +```py +accelerator.load_state("ckpt") +``` + +When using transformers `save_pretrained`, pass `state_dict=accelerator.get_state_dict(model)` to save the model state dict. + Below is an example: + +```diff + unwrapped_model.save_pretrained( + args.output_dir, + is_main_process=accelerator.is_main_process, + save_function=accelerator.save, ++ state_dict=accelerator.get_state_dict(model), +) +``` + +### State Dict + +`accelerator.get_state_dict` will call the underlying `model.state_dict` implementation using `FullStateDictConfig(offload_to_cpu=True, rank0_only=True)` context manager to get the state dict only for rank 0 and it will be offloaded to CPU. + +You can then pass `state` into the `save_pretrained` method. There are several modes for `StateDictType` and `FullStateDictConfig` that you can use to control the behavior of `state_dict`. For more information, see the [PyTorch documentation](https://pytorch.org/docs/stable/fsdp.html). + +If you choose to use `StateDictType.SHARDED_STATE_DICT`, the weights of the model during `Accelerator.save_state` will be split into `n` files for each sub-split on the model. To merge them back into +a single dictionary to load back into the model later after training you can use the `merge_weights` utility: + +```py +from accelerate.utils import merge_fsdp_weights + +# Our weights are saved usually in a `pytorch_model_fsdp_{model_number}` folder +merge_fsdp_weights("pytorch_model_fsdp_0", "output_path", safe_serialization=True) +``` +The final output will then either be saved to `model.safetensors` or `pytorch_model.bin` (if `safe_serialization=False` is passed). + +This can also be called using the CLI: +```bash +accelerate merge-weights pytorch_model_fsdp_0/ output_path +``` + + +## Mapping between FSDP sharding strategies and DeepSpeed ZeRO Stages +* `FULL_SHARD` maps to the DeepSpeed `ZeRO Stage-3`. Shards optimizer states, gradients and parameters. +* `SHARD_GRAD_OP` maps to the DeepSpeed `ZeRO Stage-2`. Shards optimizer states and gradients. +* `NO_SHARD` maps to `ZeRO Stage-0`. No sharding wherein each GPU has full copy of model, optimizer states and gradients. +* `HYBRID_SHARD` maps to `ZeRO++ Stage-3` wherein `zero_hpz_partition_size=`. Here, this will shard optimizer states, gradients and parameters within each node while each node has full copy. + +## A few caveats to be aware of + +- In case of multiple models, pass the optimizers to the prepare call in the same order as corresponding models else `accelerator.save_state()` and `accelerator.load_state()` will result in wrong/unexpected behaviour. +- This feature is incompatible with `--predict_with_generate` in the `run_translation.py` script of 🤗 `Transformers` library. + +For more control, users can leverage the `FullyShardedDataParallelPlugin`. After creating an instance of this class, users can pass it to the Accelerator class instantiation. +For more information on these options, please refer to the PyTorch [FullyShardedDataParallel](https://github.com/pytorch/pytorch/blob/0df2e863fbd5993a7b9e652910792bd21a516ff3/torch/distributed/fsdp/fully_sharded_data_parallel.py#L236) code. + + + + + For those interested in the similarities and differences between FSDP and DeepSpeed, please check out the [concept guide here](../concept_guides/fsdp_and_deepspeed)! + + \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/gradient_accumulation.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/gradient_accumulation.md new file mode 100644 index 0000000000000000000000000000000000000000..7960e6b0e4c6e905efea035e8d8170be70d922ba --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/gradient_accumulation.md @@ -0,0 +1,232 @@ + + +# Performing gradient accumulation with 🤗 Accelerate + +Gradient accumulation is a technique where you can train on bigger batch sizes than +your machine would normally be able to fit into memory. This is done by accumulating gradients over +several batches, and only stepping the optimizer after a certain number of batches have been performed. + +While technically standard gradient accumulation code would work fine in a distributed setup, it is not the most efficient +method for doing so and you may experience considerable slowdowns! + +In this tutorial you will see how to quickly setup gradient accumulation and perform it with the utilities provided in 🤗 Accelerate, +which can total to adding just one new line of code! + +This example will use a very simplistic PyTorch training loop that performs gradient accumulation every two batches: + +```python +device = "cuda" +model.to(device) + +gradient_accumulation_steps = 2 + +for index, batch in enumerate(training_dataloader): + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) + loss = loss / gradient_accumulation_steps + loss.backward() + if (index + 1) % gradient_accumulation_steps == 0: + optimizer.step() + scheduler.step() + optimizer.zero_grad() +``` + +## Converting it to 🤗 Accelerate + +First the code shown earlier will be converted to utilize 🤗 Accelerate without the special gradient accumulation helper: + +```diff ++ from accelerate import Accelerator ++ accelerator = Accelerator() + ++ model, optimizer, training_dataloader, scheduler = accelerator.prepare( ++ model, optimizer, training_dataloader, scheduler ++ ) + + for index, batch in enumerate(training_dataloader): + inputs, targets = batch +- inputs = inputs.to(device) +- targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) + loss = loss / gradient_accumulation_steps ++ accelerator.backward(loss) + if (index+1) % gradient_accumulation_steps == 0: + optimizer.step() + scheduler.step() + optimizer.zero_grad() +``` + + + + In its current state, this code is not going to perform gradient accumulation efficiently due to a process called gradient synchronization. Read more about that in the [Concepts tutorial](../concept_guides/gradient_synchronization)! + + + +## Letting 🤗 Accelerate handle gradient accumulation + +All that is left now is to let 🤗 Accelerate handle the gradient accumulation for us. To do so you should pass in a `gradient_accumulation_steps` parameter to [`Accelerator`], dictating the number +of steps to perform before each call to `step()` and how to automatically adjust the loss during the call to [`~Accelerator.backward`]: + +```diff + from accelerate import Accelerator +- accelerator = Accelerator() ++ accelerator = Accelerator(gradient_accumulation_steps=2) +``` + +Alternatively, you can pass in a `gradient_accumulation_plugin` parameter to the [`Accelerator`] object's `__init__`, which will allow you to further customize the gradient accumulation behavior. +Read more about that in the [GradientAccumulationPlugin](../package_reference/accelerator#accelerate.utils.GradientAccumulationPlugin) docs. + +From here you can use the [`~Accelerator.accumulate`] context manager from inside your training loop to automatically perform the gradient accumulation for you! +You just wrap it around the entire training part of our code: + +```diff +- for index, batch in enumerate(training_dataloader): ++ for batch in training_dataloader: ++ with accelerator.accumulate(model): + inputs, targets = batch + outputs = model(inputs) +``` + +You can remove all the special checks for the step number and the loss adjustment: + +```diff +- loss = loss / gradient_accumulation_steps + accelerator.backward(loss) +- if (index+1) % gradient_accumulation_steps == 0: + optimizer.step() + scheduler.step() + optimizer.zero_grad() +``` + +As you can see the [`Accelerator`] is able to keep track of the batch number you are on and it will automatically know whether to step through the prepared optimizer and how to adjust the loss. + + + +Typically with gradient accumulation, you would need to adjust the number of steps to reflect the change in total batches you are +training on. 🤗 Accelerate automagically does this for you by default. Behind the scenes we instantiate a [`GradientAccumulationPlugin`] configured to do this. + + + + + +The [`state.GradientState`] is sync'd with the active dataloader being iterated upon. As such it assumes naively that when we have reached the end of the dataloader everything will sync and a step will be performed. To disable this, set `sync_with_dataloader` to be `False` in the [`GradientAccumulationPlugin`]: + +```{python} +from accelerate import Accelerator +from accelerate.utils import GradientAccumulationPlugin + +plugin = GradientAccumulationPlugin(sync_with_dataloader=False) +accelerator = Accelerator(..., gradient_accumulation_plugin=plugin) +``` + + + +## The finished code + +Below is the finished implementation for performing gradient accumulation with 🤗 Accelerate + +```python +from accelerate import Accelerator +accelerator = Accelerator(gradient_accumulation_steps=2) +model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler +) +for batch in training_dataloader: + with accelerator.accumulate(model): + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() + optimizer.zero_grad() +``` + + + +It's important that **only one forward/backward** should be done inside the context manager `with accelerator.accumulate(model)`. + + + + +To learn more about what magic this wraps around, read the [Gradient Synchronization concept guide](../concept_guides/gradient_synchronization) + + +## Self-contained example + +Here is a self-contained example that you can run to see gradient accumulation in action with 🤗 Accelerate: + +```python +import torch +import copy +from accelerate import Accelerator +from accelerate.utils import set_seed +from torch.utils.data import TensorDataset, DataLoader + +# seed +set_seed(0) + +# define toy inputs and labels +x = torch.tensor([1., 2., 3., 4., 5., 6., 7., 8.]) +y = torch.tensor([2., 4., 6., 8., 10., 12., 14., 16.]) +gradient_accumulation_steps = 4 +batch_size = len(x) // gradient_accumulation_steps + +# define dataset and dataloader +dataset = TensorDataset(x, y) +dataloader = DataLoader(dataset, batch_size=batch_size) + +# define model, optimizer and loss function +model = torch.zeros((1, 1), requires_grad=True) +model_clone = copy.deepcopy(model) +criterion = torch.nn.MSELoss() +model_optimizer = torch.optim.SGD([model], lr=0.02) +accelerator = Accelerator(gradient_accumulation_steps=gradient_accumulation_steps) +model, model_optimizer, dataloader = accelerator.prepare(model, model_optimizer, dataloader) +model_clone_optimizer = torch.optim.SGD([model_clone], lr=0.02) +print(f"initial model weight is {model.mean().item():.5f}") +print(f"initial model weight is {model_clone.mean().item():.5f}") +for i, (inputs, labels) in enumerate(dataloader): + with accelerator.accumulate(model): + inputs = inputs.view(-1, 1) + print(i, inputs.flatten()) + labels = labels.view(-1, 1) + outputs = inputs @ model + loss = criterion(outputs, labels) + accelerator.backward(loss) + model_optimizer.step() + model_optimizer.zero_grad() +loss = criterion(x.view(-1, 1) @ model_clone, y.view(-1, 1)) +model_clone_optimizer.zero_grad() +loss.backward() +model_clone_optimizer.step() +print(f"w/ accumulation, the final model weight is {model.mean().item():.5f}") +print(f"w/o accumulation, the final model weight is {model_clone.mean().item():.5f}") +``` +``` +initial model weight is 0.00000 +initial model weight is 0.00000 +0 tensor([1., 2.]) +1 tensor([3., 4.]) +2 tensor([5., 6.]) +3 tensor([7., 8.]) +w/ accumulation, the final model weight is 2.04000 +w/o accumulation, the final model weight is 2.04000 +``` diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/ipex.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/ipex.md new file mode 100644 index 0000000000000000000000000000000000000000..8783bdc9bef1fa4dbf1eb90757e0674b8354d00b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/ipex.md @@ -0,0 +1,192 @@ + + +# Intel® Extension for PyTorch + +[IPEX](https://github.com/intel/intel-extension-for-pytorch) is optimized for CPUs with AVX-512 or above, and functionally works for CPUs with only AVX2. So, it is expected to bring performance benefit for Intel CPU generations with AVX-512 or above while CPUs with only AVX2 (e.g., AMD CPUs or older Intel CPUs) might result in a better performance under IPEX, but not guaranteed. IPEX provides performance optimizations for CPU training with both Float32 and BFloat16. The usage of BFloat16 is the main focus of the following sections. + +Low precision data type BFloat16 has been natively supported on the 3rd Generation Xeon® Scalable Processors (aka Cooper Lake) with AVX512 instruction set and will be supported on the next generation of Intel® Xeon® Scalable Processors with Intel® Advanced Matrix Extensions (Intel® AMX) instruction set with further boosted performance. The Auto Mixed Precision for CPU backend has been enabled since PyTorch-1.10. At the same time, the support of Auto Mixed Precision with BFloat16 for CPU and BFloat16 optimization of operators has been massively enabled in Intel® Extension for PyTorch, and partially upstreamed to PyTorch master branch. Users can get better performance and user experience with IPEX Auto Mixed Precision. + +## IPEX installation: + +IPEX release is following PyTorch, to install via pip: + +| PyTorch Version | IPEX version | +| :---------------: | :----------: | +| 2.0 | 2.0.0 | +| 1.13 | 1.13.0 | +| 1.12 | 1.12.300 | +| 1.11 | 1.11.200 | +| 1.10 | 1.10.100 | + +``` +pip install intel_extension_for_pytorch== -f https://developer.intel.com/ipex-whl-stable-cpu +``` + +Check more approaches for [IPEX installation](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/installation.html). + + +## How It Works For Training optimization in CPU + +🤗 Accelerate has integrated [IPEX](https://github.com/intel/intel-extension-for-pytorch), all you need to do is enabling it through the config. + +**Scenario 1**: Acceleration of No distributed CPU training + +Run accelerate config on your machine: + +```bash +$ accelerate config +----------------------------------------------------------------------------------------------------------------------------------------------------------- +In which compute environment are you running? +This machine +----------------------------------------------------------------------------------------------------------------------------------------------------------- +Which type of machine are you using? +No distributed training +Do you want to run your training on CPU only (even if a GPU / Apple Silicon device is available)? [yes/NO]:yes +Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU? [yes/NO]:yes +Do you wish to optimize your script with torch dynamo?[yes/NO]:NO +Do you want to use DeepSpeed? [yes/NO]: NO +----------------------------------------------------------------------------------------------------------------------------------------------------------- +Do you wish to use FP16 or BF16 (mixed precision)? +bf16 +``` +This will generate a config file that will be used automatically to properly set the +default options when doing + +```bash +accelerate launch my_script.py --args_to_my_script +``` + +For instance, here is how you would run the NLP example `examples/nlp_example.py` (from the root of the repo) with IPEX enabled. +default_config.yaml that is generated after `accelerate config` + +```bash +compute_environment: LOCAL_MACHINE +distributed_type: 'NO' +downcast_bf16: 'no' +ipex_config: + ipex: true +machine_rank: 0 +main_training_function: main +mixed_precision: bf16 +num_machines: 1 +num_processes: 1 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: true +``` +```bash +accelerate launch examples/nlp_example.py +``` + +**Scenario 2**: Acceleration of distributed CPU training +we use Intel oneCCL for communication, combined with Intel® MPI library to deliver flexible, efficient, scalable cluster messaging on Intel® architecture. you could refer the [here](https://huggingface.co/docs/transformers/perf_train_cpu_many) for the installation guide + +Run accelerate config on your machine(node0): + +```bash +$ accelerate config +----------------------------------------------------------------------------------------------------------------------------------------------------------- +In which compute environment are you running? +This machine +----------------------------------------------------------------------------------------------------------------------------------------------------------- +Which type of machine are you using? +multi-CPU +How many different machines will you use (use more than 1 for multi-node training)? [1]: 4 +----------------------------------------------------------------------------------------------------------------------------------------------------------- +What is the rank of this machine? +0 +What is the IP address of the machine that will host the main process? 36.112.23.24 +What is the port you will use to communicate with the main process? 29500 +Are all the machines on the same local network? Answer `no` if nodes are on the cloud and/or on different network hosts [YES/no]: yes +Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU? [yes/NO]:yes +Do you want accelerate to launch mpirun? [yes/NO]: yes +Please enter the path to the hostfile to use with mpirun [~/hostfile]: ~/hostfile +Enter the number of oneCCL worker threads [1]: 1 +Do you wish to optimize your script with torch dynamo?[yes/NO]:NO +How many processes should be used for distributed training? [1]:16 +----------------------------------------------------------------------------------------------------------------------------------------------------------- +Do you wish to use FP16 or BF16 (mixed precision)? +bf16 +``` +For instance, here is how you would run the NLP example `examples/nlp_example.py` (from the root of the repo) with IPEX enabled for distributed CPU training. + +default_config.yaml that is generated after `accelerate config` +```bash +compute_environment: LOCAL_MACHINE +distributed_type: MULTI_CPU +downcast_bf16: 'no' +ipex_config: + ipex: true +machine_rank: 0 +main_process_ip: 36.112.23.24 +main_process_port: 29500 +main_training_function: main +mixed_precision: bf16 +mpirun_config: + mpirun_ccl: '1' + mpirun_hostfile: /home/user/hostfile +num_machines: 4 +num_processes: 16 +rdzv_backend: static +same_network: true +tpu_env: [] +tpu_use_cluster: false +tpu_use_sudo: false +use_cpu: true +``` + +Set following env and using intel MPI to launch the training + +In node0, you need to create a configuration file which contains the IP addresses of each node (for example hostfile) and pass that configuration file path as an argument. +If you selected to have Accelerate launch `mpirun`, ensure that the location of your hostfile matches the path in the config. +```bash +$ cat hostfile +xxx.xxx.xxx.xxx #node0 ip +xxx.xxx.xxx.xxx #node1 ip +xxx.xxx.xxx.xxx #node2 ip +xxx.xxx.xxx.xxx #node3 ip +``` +When Accelerate is launching `mpirun`, source the oneCCL bindings setvars.sh to get your Intel MPI environment, and then +run your script using `accelerate launch`. Note that the python script and environment needs to exist on all of the +machines being used for multi-CPU training. +```bash +oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)") +source $oneccl_bindings_for_pytorch_path/env/setvars.sh + +accelerate launch examples/nlp_example.py +``` +Otherwise, if you selected not to have Accelerate launch `mpirun`, run the following command in node0 and **16DDP** will +be enabled in node0,node1,node2,node3 with BF16 mixed precision. When using this method, the python script, python +environment, and accelerate config file need to be present on all of the machines used for multi-CPU training. +```bash +oneccl_bindings_for_pytorch_path=$(python -c "from oneccl_bindings_for_pytorch import cwd; print(cwd)") +source $oneccl_bindings_for_pytorch_path/env/setvars.sh +export CCL_WORKER_COUNT=1 +export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip +export CCL_ATL_TRANSPORT=ofi +mpirun -f hostfile -n 16 -ppn 4 accelerate launch examples/nlp_example.py +``` + +## Related Resources + +- [Project's github](https://github.com/intel/intel-extension-for-pytorch) +- [API docs](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/api_doc.html) +- [Tuning guide](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/performance_tuning/tuning_guide.html) +- [Blogs & Publications](https://intel.github.io/intel-extension-for-pytorch/cpu/latest/tutorials/blogs_publications.html) + diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/local_sgd.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/local_sgd.md new file mode 100644 index 0000000000000000000000000000000000000000..5bee411433de523c36d653c4adb552c94dff4982 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/local_sgd.md @@ -0,0 +1,108 @@ + + +# Using Local SGD with 🤗 Accelerate + +Local SGD is a technique for distributed training where gradients are not synchronized every step. Thus, each process updates its own version of the model weights and after a given number of steps these weights are synchronized by averaging across all processes. This improves communication efficiency and can lead to substantial training speed up especially when a computer lacks a faster interconnect such as NVLink. +Unlike gradient accumulation (where improving communication efficiency requires increasing the effective batch size), Local SGD does not require changing a batch size or a learning rate / schedule. However, if necessary, Local SGD can be combined with gradient accumulation as well. + +In this tutorial you will see how to quickly setup Local SGD 🤗 Accelerate. Compared to a standard Accelerate setup, this requires only two extra lines of code. + +This example will use a very simplistic PyTorch training loop that performs gradient accumulation every two batches: + +```python +device = "cuda" +model.to(device) + +gradient_accumulation_steps = 2 + +for index, batch in enumerate(training_dataloader): + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) + loss = loss / gradient_accumulation_steps + loss.backward() + if (index + 1) % gradient_accumulation_steps == 0: + optimizer.step() + scheduler.step() + optimizer.zero_grad() +``` + +## Converting it to 🤗 Accelerate + +First the code shown earlier will be converted to use 🤗 Accelerate with neither a LocalSGD or a gradient accumulation helper: + +```diff ++ from accelerate import Accelerator ++ accelerator = Accelerator() + ++ model, optimizer, training_dataloader, scheduler = accelerator.prepare( ++ model, optimizer, training_dataloader, scheduler ++ ) + + for index, batch in enumerate(training_dataloader): + inputs, targets = batch +- inputs = inputs.to(device) +- targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) + loss = loss / gradient_accumulation_steps ++ accelerator.backward(loss) + if (index+1) % gradient_accumulation_steps == 0: + optimizer.step() + scheduler.step() +``` + +## Letting 🤗 Accelerate handle model synchronization + +All that is left now is to let 🤗 Accelerate handle model parameter synchronization **and** the gradient accumulation for us. For simplicity let us assume we need to synchronize every 8 steps. This is +achieved by adding one `with LocalSGD` statement and one call `local_sgd.step()` after every optimizer step: + +```diff ++local_sgd_steps=8 + ++with LocalSGD(accelerator=accelerator, model=model, local_sgd_steps=8, enabled=True) as local_sgd: + for batch in training_dataloader: + with accelerator.accumulate(model): + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() + optimizer.zero_grad() ++ local_sgd.step() +``` + +Under the hood, the Local SGD code **disables** automatic gradient synchronization (but accumulation still works as expected!). Instead it averages model parameters every `local_sgd_steps` steps (as well as at the end of the training loop). + +## Limitations + +The current implementation works only with basic multi-GPU (or multi-CPU) training without, e.g., [DeepSpeed.](https://github.com/microsoft/DeepSpeed). + +## References + + Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes + back to at least: + + Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint + arXiv:1606.07365.](https://arxiv.org/abs/1606.07365) + + We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of). + + Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on + Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/low_precision_training.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/low_precision_training.md new file mode 100644 index 0000000000000000000000000000000000000000..f8f7d83df0ecf0d683f9212205f1f236200e60e4 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/low_precision_training.md @@ -0,0 +1,145 @@ + + +# Low Precision Training Methods + +🤗 Accelerate provides integrations to train on lower precision methods using specified supported hardware through the `TransformersEngine` and `MS-AMP` packages. This documentation will help guide you through what hardware is supported, how to configure your [`Accelerator`] to leverage the low precision methods, and what you can expect when training. + +## What training on FP8 means + +To explore more of the nitty-gritty in training in FP8 with PyTorch and 🤗 Accelerate, check out the [concept_guide](../concept_guides/low_precision_training) on why this can be difficult. But essentially rather than training in BF16, some (or all) aspects of training a model can be performed using 8 bits instead of 16. The challenge is doing so without degrading final performance. + +This is only enabled on specific NVIDIA hardware, namely: + +* Anything after the 3000 series consumer graphics cards (such as the 4090) +* Hopper-based GPU architectures (such as the `H100` and `H200`) + +What this will result in is some gain in the memory used (as we've cut the needed memory in half for some parts of training) and an increase in throughput *should* be seen as well for larger models that can replace certain layers with FP8-enabled ones. + +## Configuring the Accelerator + +Currently two different backends for FP8 are supported (`TransformersEngine` and `MS-AMP`), each with different capabilities and configurations. + +To use either, the same core API is used. Just pass `mixed_precision="fp8"` to either the [`Accelerator`], during `accelerate config` when prompted about mixed precision, or as part of your `config.yaml` file in the `mixed_precision` key: + +```{python} +from accelerate import Accelerator +accelerator = Accelerator(mixed_precision="fp8") +``` + +By default, if `MS-AMP` is available in your environment, 🤗 Accelerate will automatically utilize it as a backend. To specify it yourself (and customize other parts of the FP8 mixed precision setup), you can utilize the [`utils.FP8RecipeKwargs`] or clarify it in your config `yaml`/during `accelerate launch`: + +```{python} +from accelerate import Accelerator +from accelerate.utils import FP8RecipeKwargs +kwargs = [FP8RecipeKwargs(backend="msamp")] +# Or to specify the backend as `TransformersEngine` even if MS-AMP is installed +# kwargs = [FP8RecipeKwargs(backend="te")] +accelerator = Accelerator(mixed_precision="fp8", kwarg_handlers=kwargs) +``` + +```{yaml} +mixed_precision: fp8 +fp8_config: + amax_compute_algorithm: max + amax_history_length: 1024 + backend: TE + fp8_format: HYBRID + interval: 1 + margin: 0 + override_linear_precision: false + use_autocast_during_eval: false +``` + +## Configuring MS-AMP + +Of the two, `MS-AMP` is traditionally the easier one to configure as there is only a single argument: the optimization level. + +Currently two levels of optimization are supported in the 🤗 Accelerate integration, `"O1"` and `"O2"` (using the letter 'o', not zero). + +* `"O1"` will cast the weight gradients and `all_reduce` communications to happen in 8-bit, while the rest are done in 16 bit. This reduces the general GPU memory usage and speeds up communication bandwidths. +* `"O2"` will also cast first-order optimizer states into 8 bit, while the second order states are in FP16. (Currently just the `Adam` optimizer is supported). This tries its best to minimize final accuracy degradation and will save the highest potential memory. + +To specify an optimization level, pass it to the `FP8KwargsHandler` by setting the `optimization_level` argument: + +```{python} +from accelerate import Accelerator +from accelerate.utils import FP8RecipeKwargs +kwargs = [FP8RecipeKwargs(backend="msamp", optimization_level="O2")] +accelerator = Accelerator(mixed_precision="fp8", kwarg_handlers=kwargs) +``` + +Or during `accelerate launch` via `--fp8_backend=msamp --fp8_opt_level=O2` + +Similarly this can be set in your `config.yaml`: + +```{yaml} +mixed_precision: fp8 +fp8_config: + backend: MSAMP + opt_level: O2 +``` + +## Configuring TransformersEngine + +TransformersEngine has much more available for customizing how and what FP8 calculations are performed. A full list of supported arguments and what they mean are available in [NVIDIA's documentation](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html), however they are restated as part of [`FP8KwargsHandler`]'s docstring for your convenience. + +🤗 Accelerate tries to set sensible defaults, but exploring and tweaking the various parameters yourself can lead to better performance potentially. + +To use it, specify `backend="te"` and modify any of the arguments you want as part of your kwarg handler: + +```{python} +from accelerate import Accelerator +from accelerate.utils import FP8RecipeKwargs +kwargs = [FP8RecipeKwargs(backend="te", ...)] +accelerator = Accelerator(mixed_precision="fp8", kwarg_handlers=kwargs) +``` + +Or during `accelerate launch` via `--fp8_backend=te ...`. Use `accelerate launch --fp8_backend=te -h` to see relevent arguments. + +Similarly this can be set in your `config.yaml`: + +```{yaml} +mixed_precision: fp8 +fp8_config: + amax_compute_algorithm: max + amax_history_length: 1024 + backend: TE + fp8_format: HYBRID + interval: 1 + margin: 0 + override_linear_precision: false + use_autocast_during_eval: false +``` + +## Example Zoo + +We have examples showcasing training with FP8 both with accelerate and its underlying implementation available in the accelerate repo. +Currently we support scripts showcasing: + +* Single GPU +* Distributed Data Parallelism (Multi-GPU) +* Fully Sharded Data Parallelism +* DeepSpeed ZeRO 1 through 3 + +Find out more [here](https://github.com/huggingface/accelerate/tree/main/benchmarks/fp8) + +## Further Reading + +To learn more about training in FP8 please check out the following resources: + +* [Our concept guide](../concept_guides/low_precision_training) detailing into more about both TransformersEngine and MS-AMP +* [The `transformers-engine` documentation](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html) +* [The `MS-AMP` documentation](https://azure.github.io/MS-AMP/docs/) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/megatron_lm.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/megatron_lm.md new file mode 100644 index 0000000000000000000000000000000000000000..06e0fdc48e648fe3b484b1dd29c721677db76c60 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/megatron_lm.md @@ -0,0 +1,586 @@ + + + +# Megatron-LM + +[Megatron-LM](https://github.com/NVIDIA/Megatron-LM) enables training large transformer language models at scale. +It provides efficient tensor, pipeline and sequence based model parallelism for pre-training transformer based +Language Models such as [GPT](https://arxiv.org/abs/2005.14165) (Decoder Only), [BERT](https://arxiv.org/pdf/1810.04805.pdf) (Encoder Only) and [T5](https://arxiv.org/abs/1910.10683) (Encoder-Decoder). +For detailed information and how things work behind the scene please refer the github [repo](https://github.com/NVIDIA/Megatron-LM). + +## What is integrated? + +Accelerate integrates following feature of Megatron-LM to enable large scale pre-training/finetuning +of BERT (Encoder), GPT (Decoder) or T5 models (Encoder and Decoder): + +a. **Tensor Parallelism (TP)**: Reduces memory footprint without much additional communication on intra-node ranks. +Each tensor is split into multiple chunks with each shard residing on separate GPU. At each step, the same mini-batch of data is processed +independently and in parallel by each shard followed by syncing across all GPUs (`all-reduce` operation). +In a simple transformer layer, this leads to 2 `all-reduces` in the forward path and 2 in the backward path. +For more details, please refer research paper [Megatron-LM: Training Multi-Billion Parameter Language Models Using +Model Parallelism](https://arxiv.org/pdf/1909.08053.pdf) and +this section of 🤗 blogpost [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#tensor-parallelism). + + +b. **Pipeline Parallelism (PP)**: Reduces memory footprint and enables large scale training via inter-node parallelization. +Reduces the bubble of naive PP via PipeDream-Flush schedule/1F1B schedule and Interleaved 1F1B schedule. +Layers are distributed uniformly across PP stages. For example, if a model has `24` layers and we have `4` GPUs for +pipeline parallelism, each GPU will have `6` layers (24/4). For more details on schedules to reduce the idle time of PP, +please refer to the research paper [Efficient Large-Scale Language Model Training on GPU Clusters +Using Megatron-LM](https://arxiv.org/pdf/2104.04473.pdf) and +this section of 🤗 blogpost [The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#pipeline-parallelism). + +c. **Sequence Parallelism (SP)**: Reduces memory footprint without any additional communication. Only applicable when using TP. +It reduces activation memory required as it prevents the same copies to be on the tensor parallel ranks +post `all-reduce` by replacing then with `reduce-scatter` and `no-op` operation would be replaced by `all-gather`. +As `all-reduce = reduce-scatter + all-gather`, this saves a ton of activation memory at no added communication cost. +To put it simply, it shards the outputs of each transformer layer along sequence dimension, e.g., +if the sequence length is `1024` and the TP size is `4`, each GPU will have `256` tokens (1024/4) for each sample. +This increases the batch size that can be supported for training. For more details, please refer to the research paper +[Reducing Activation Recomputation in Large Transformer Models](https://arxiv.org/pdf/2205.05198.pdf). + +d. **Data Parallelism (DP)** via Distributed Optimizer: Reduces the memory footprint by sharding optimizer states and gradients across DP ranks +(versus the traditional method of replicating the optimizer state across data parallel ranks). +For example, when using Adam optimizer with mixed-precision training, each parameter accounts for 12 bytes of memory. +This gets distributed equally across the GPUs, i.e., each parameter would account for 3 bytes (12/4) if we have 4 GPUs. +For more details, please refer the research paper [ZeRO: Memory Optimizations Toward Training Trillion +Parameter Models](https://arxiv.org/pdf/1910.02054.pdf) and following section of 🤗 blog +[The Technology Behind BLOOM Training](https://huggingface.co/blog/bloom-megatron-deepspeed#zero-data-parallelism). + +e. **Selective Activation Recomputation**: Reduces the memory footprint of activations significantly via smart activation checkpointing. +It doesn't store activations occupying large memory while being fast to recompute thereby achieving great tradeoff between memory and recomputation. +For example, for GPT-3, this leads to 70% reduction in required memory for activations at the expense of +only 2.7% FLOPs overhead for recomputation of activations. For more details, please refer to the research paper +[Reducing Activation Recomputation in Large Transformer Models](https://arxiv.org/pdf/2205.05198.pdf). + +f. **Fused Kernels**: Fused Softmax, Mixed Precision Fused Layer Norm and Fused gradient accumulation to weight gradient computation of linear layer. +PyTorch JIT compiled Fused GeLU and Fused Bias+Dropout+Residual addition. + +g. **Support for Indexed datasets**: Efficient binary format of datasets for large scale training. Support for the `mmap`, `cached` index file and the `lazy` loader format. + +h. **Checkpoint reshaping and interoperability**: Utility for reshaping Megatron-LM checkpoints of variable +tensor and pipeline parallel sizes to the beloved 🤗 Transformers sharded checkpoints as it has great support with plethora of tools +such as 🤗 Accelerate Big Model Inference, Megatron-DeepSpeed Inference etc. +Support is also available for converting 🤗 Transformers sharded checkpoints to Megatron-LM checkpoint of variable tensor and pipeline parallel sizes +for large scale training. + + +## Pre-Requisites + +You will need to install the latest pytorch, cuda, nccl, and NVIDIA [APEX](https://github.com/NVIDIA/apex#quick-start) releases and the nltk library. +See [documentation](https://github.com/NVIDIA/Megatron-LM#setup) for more details. +Another way to setup the environment is to pull an NVIDIA PyTorch Container that comes with all the required installations from NGC. + +Below is a step-by-step method to set up the conda environment: + +1. Create a virtual environment +``` +conda create --name ml +``` + +2. Assuming that the machine has CUDA 11.3 installed, installing the corresponding PyTorch GPU Version +``` +conda install pytorch torchvision torchaudio cudatoolkit=11.3 -c pytorch +``` + +3. Install Nvidia APEX +``` +git clone https://github.com/NVIDIA/apex +cd apex +pip install -v --disable-pip-version-check --no-cache-dir --global-option="--cpp_ext" --global-option="--cuda_ext" ./ +cd .. +``` + +4. Installing Megatron-LM + +``` +git clone https://github.com/NVIDIA/Megatron-LM.git +cd Megatron-LM +git checkout core_r0.5.0 +pip install --no-use-pep517 -e . +``` + +## Accelerate Megatron-LM Plugin + +Important features are directly supported via the `accelerate config` command. +An example of the corresponding questions for using Megatron-LM features is shown below: + +```bash +:~$ accelerate config --config_file "megatron_gpt_config.yaml" +In which compute environment are you running? ([0] This machine, [1] AWS (Amazon SageMaker)): 0 +Which type of machine are you using? ([0] No distributed training, [1] multi-CPU, [2] multi-GPU, [3] TPU): 2 +How many different machines will you use (use more than 1 for multi-node training)? [1]: +Do you want to use DeepSpeed? [yes/NO]: +Do you want to use FullyShardedDataParallel? [yes/NO]: +Do you want to use Megatron-LM ? [yes/NO]: yes +What is the Tensor Parallelism degree/size? [1]:2 +Do you want to enable Sequence Parallelism? [YES/no]: +What is the Pipeline Parallelism degree/size? [1]:2 +What is the number of micro-batches? [1]:2 +Do you want to enable selective activation recomputation? [YES/no]: +Do you want to use distributed optimizer which shards optimizer state and gradients across data parallel ranks? [YES/no]: +What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: +How many GPU(s) should be used for distributed training? [1]:4 +Do you wish to use FP16 or BF16 (mixed precision)? [NO/fp16/bf16]: bf16 +``` + +The resulting config is shown below: + +``` +~$ cat megatron_gpt_config.yaml +compute_environment: LOCAL_MACHINE +deepspeed_config: {} +distributed_type: MEGATRON_LM +downcast_bf16: 'no' +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +megatron_lm_config: + megatron_lm_gradient_clipping: 1.0 + megatron_lm_num_micro_batches: 2 + megatron_lm_pp_degree: 2 + megatron_lm_recompute_activations: true + megatron_lm_sequence_parallelism: true + megatron_lm_tp_degree: 2 + megatron_lm_use_distributed_optimizer: true +mixed_precision: bf16 +num_machines: 1 +num_processes: 4 +rdzv_backend: static +same_network: true +use_cpu: false +``` + +We will take the example of GPT pre-training. The minimal changes required to the official `run_clm_no_trainer.py` +to use Megatron-LM are as follows: + +1. As Megatron-LM uses its own implementation of Optimizer, the corresponding scheduler compatible with it needs to be used. +As such, support for only the Megatron-LM's scheduler is present. User will need to create `accelerate.utils.MegatronLMDummyScheduler`. +Example is given below: + +```python +from accelerate.utils import MegatronLMDummyScheduler + +if accelerator.distributed_type == DistributedType.MEGATRON_LM: + lr_scheduler = MegatronLMDummyScheduler( + optimizer=optimizer, + total_num_steps=args.max_train_steps, + warmup_num_steps=args.num_warmup_steps, + ) +else: + lr_scheduler = get_scheduler( + name=args.lr_scheduler_type, + optimizer=optimizer, + num_warmup_steps=args.num_warmup_steps * args.gradient_accumulation_steps, + num_training_steps=args.max_train_steps * args.gradient_accumulation_steps, + ) +``` + +2. Getting the details of the total batch size now needs to be cognization of tensor and pipeline parallel sizes. +Example of getting the effective total batch size is shown below: + +```python +if accelerator.distributed_type == DistributedType.MEGATRON_LM: + total_batch_size = accelerator.state.megatron_lm_plugin.global_batch_size +else: + total_batch_size = args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps +``` + +3. When using Megatron-LM, the losses are already averaged across the data parallel group + +```python +if accelerator.distributed_type == DistributedType.MEGATRON_LM: + losses.append(loss) +else: + losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size))) + +if accelerator.distributed_type == DistributedType.MEGATRON_LM: + losses = torch.tensor(losses) +else: + losses = torch.cat(losses) +``` + +4. For Megatron-LM, we need to save the model using `accelerator.save_state` + +```python +if accelerator.distributed_type == DistributedType.MEGATRON_LM: + accelerator.save_state(args.output_dir) +else: + unwrapped_model = accelerator.unwrap_model(model) + unwrapped_model.save_pretrained( + args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save + ) +``` + +That's it! We are good to go 🚀. Please find the example script in the examples folder at the path `accelerate/examples/by_feature/megatron_lm_gpt_pretraining.py`. +Let's run it for `gpt-large` model architecture using 4 A100-80GB GPUs. + +```bash +accelerate launch --config_file megatron_gpt_config.yaml \ +examples/by_feature/megatron_lm_gpt_pretraining.py \ +--config_name "gpt2-large" \ +--tokenizer_name "gpt2-large" \ +--dataset_name wikitext \ +--dataset_config_name wikitext-2-raw-v1 \ +--block_size 1024 \ +--learning_rate 5e-5 \ +--per_device_train_batch_size 24 \ +--per_device_eval_batch_size 24 \ +--num_train_epochs 5 \ +--with_tracking \ +--report_to "wandb" \ +--output_dir "awesome_model" +``` + +Below are some important excerpts from the output logs: + +```bash +Loading extension module fused_dense_cuda... +>>> done with compiling and loading fused kernels. Compilation time: 3.569 seconds + > padded vocab (size: 50257) with 175 dummy tokens (new size: 50432) +Building gpt model in the pre-training mode. +The Megatron LM model weights are initialized at random in `accelerator.prepare`. Please use `accelerator.load_checkpoint` to load a pre-trained checkpoint matching the distributed setup. +Preparing dataloader +Preparing dataloader +Preparing model + > number of parameters on (tensor, pipeline) model parallel rank (1, 0): 210753280 + > number of parameters on (tensor, pipeline) model parallel rank (1, 1): 209445120 + > number of parameters on (tensor, pipeline) model parallel rank (0, 0): 210753280 + > number of parameters on (tensor, pipeline) model parallel rank (0, 1): 209445120 +Preparing optimizer +Preparing scheduler +> learning rate decay style: linear +10/10/2022 22:57:22 - INFO - __main__ - ***** Running training ***** +10/10/2022 22:57:22 - INFO - __main__ - Num examples = 2318 +10/10/2022 22:57:22 - INFO - __main__ - Num Epochs = 5 +10/10/2022 22:57:22 - INFO - __main__ - Instantaneous batch size per device = 24 +10/10/2022 22:57:22 - INFO - __main__ - Total train batch size (w. parallel, distributed & accumulation) = 48 +10/10/2022 22:57:22 - INFO - __main__ - Gradient Accumulation steps = 1 +10/10/2022 22:57:22 - INFO - __main__ - Total optimization steps = 245 + 20%|████████████▍ | 49/245 [01:04<04:09, 1.27s/it] + 10/10/2022 22:58:29 - INFO - __main__ - epoch 0: perplexity: 1222.1594275215962 eval_loss: 7.10837459564209 + 40%|████████████████████████▊ | 98/245 [02:10<03:07, 1.28s/it] + 10/10/2022 22:59:35 - INFO - __main__ - epoch 1: perplexity: 894.5236583794557 eval_loss: 6.796291351318359 + 60%|████████████████████████████████████▌ | 147/245 [03:16<02:05, 1.28s/it] + 10/10/2022 23:00:40 - INFO - __main__ - epoch 2: perplexity: 702.8458788508042 eval_loss: 6.555137634277344 + 80%|████████████████████████████████████████████████▊ | 196/245 [04:22<01:02, 1.28s/it] + 10/10/2022 23:01:46 - INFO - __main__ - epoch 3: perplexity: 600.3220028695281 eval_loss: 6.39746618270874 +100%|█████████████████████████████████████████████████████████████| 245/245 [05:27<00:00, 1.28s/it] +``` + +There are a large number of other options/features that one can set using `accelerate.utils.MegatronLMPlugin`. + +## Advanced features to leverage writing custom train step and Megatron-LM Indexed Datasets + +For leveraging more features, please go through below details. + +1. Below is an example of changes required to customize the Train Step while using Megatron-LM. +You will implement the `accelerate.utils.AbstractTrainStep` or inherit from their corresponding children +`accelerate.utils.GPTTrainStep`, `accelerate.utils.BertTrainStep` or `accelerate.utils.T5TrainStep`. + +```python +from accelerate.utils import MegatronLMDummyScheduler, GPTTrainStep, avg_losses_across_data_parallel_group + + +# Custom loss function for the Megatron model +class GPTTrainStepWithCustomLoss(GPTTrainStep): + def __init__(self, megatron_args, **kwargs): + super().__init__(megatron_args) + self.kwargs = kwargs + + def get_loss_func(self): + def loss_func(inputs, loss_mask, output_tensor): + batch_size, seq_length = output_tensor.shape + losses = output_tensor.float() + loss_mask = loss_mask.view(-1).float() + loss = losses.view(-1) * loss_mask + + # Resize and average loss per sample + loss_per_sample = loss.view(batch_size, seq_length).sum(axis=1) + loss_mask_per_sample = loss_mask.view(batch_size, seq_length).sum(axis=1) + loss_per_sample = loss_per_sample / loss_mask_per_sample + + # Calculate and scale weighting + weights = torch.stack([(inputs == kt).float() for kt in self.kwargs["keytoken_ids"]]).sum(axis=[0, 2]) + weights = 1.0 + self.kwargs["alpha"] * weights + # Calculate weighted average + weighted_loss = (loss_per_sample * weights).mean() + + # Reduce loss across data parallel groups + averaged_loss = avg_losses_across_data_parallel_group([weighted_loss]) + + return weighted_loss, {"lm loss": averaged_loss[0]} + + return loss_func + + def get_forward_step_func(self): + def forward_step(data_iterator, model): + """Forward step.""" + # Get the batch. + tokens, labels, loss_mask, attention_mask, position_ids = self.get_batch(data_iterator) + output_tensor = model(tokens, position_ids, attention_mask, labels=labels) + + return output_tensor, partial(self.loss_func, tokens, loss_mask) + + return forward_step + + +def main(): + # Custom loss function for the Megatron model + keytoken_ids = [] + keywords = ["plt", "pd", "sk", "fit", "predict", " plt", " pd", " sk", " fit", " predict"] + for keyword in keywords: + ids = tokenizer([keyword]).input_ids[0] + if len(ids) == 1: + keytoken_ids.append(ids[0]) + accelerator.print(f"Keytoken ids: {keytoken_ids}") + accelerator.state.megatron_lm_plugin.custom_train_step_class = GPTTrainStepWithCustomLoss + accelerator.state.megatron_lm_plugin.custom_train_step_kwargs = { + "keytoken_ids": keytoken_ids, + "alpha": 0.25, + } +``` + +2. For using the Megatron-LM datasets, a few more changes are required. Dataloaders for these datasets +are available only on rank 0 of each tensor parallel group. As such, there are rank where dataloader won't be +available and this requires tweaks to the training loop. Being able to do all this shows how +flexible and extensible 🤗 Accelerate is. The changes required are as follows. + +a. For Megatron-LM indexed datasets, we need to use `MegatronLMDummyDataLoader` +and pass the required dataset args to it such as `data_path`, `seq_length` etc. +See [here](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/arguments.py#L804) for the list of available args. + +```python +from accelerate.utils import MegatronLMDummyDataLoader + +megatron_dataloader_config = { + "data_path": args.data_path, + "splits_string": args.splits_string, + "seq_length": args.block_size, + "micro_batch_size": args.per_device_train_batch_size, +} +megatron_dataloader = MegatronLMDummyDataLoader(**megatron_dataloader_config) +accelerator.state.megatron_lm_plugin.megatron_dataset_flag = True +``` + +b. `megatron_dataloader` is repeated 3 times to get training, validation and test dataloaders +as per the `args.splits_string` proportions + +```python +model, optimizer, lr_scheduler, train_dataloader, eval_dataloader, _ = accelerator.prepare( + model, optimizer, lr_scheduler, megatron_dataloader, megatron_dataloader, megatron_dataloader +) +``` + +c. Changes to training and evaluation loops as dataloader is only available on tensor parallel ranks 0 +So, we need to iterate only if the dataloader isn't `None` else provide empty dict +As such, we loop using `while` loop and break when `completed_steps` is equal to `args.max_train_steps` +This is similar to the Megatron-LM setup wherein user has to provide `max_train_steps` when using Megaton-LM indexed datasets. +This displays how flexible and extensible 🤗 Accelerate is. + +```python +while completed_steps < args.max_train_steps: + model.train() + batch = next(train_dataloader) if train_dataloader is not None else {} + outputs = model(**batch) + loss = outputs.loss + ... + + if completed_steps % eval_interval == 0: + eval_completed_steps = 0 + losses = [] + while eval_completed_steps < eval_iters: + model.eval() + with torch.no_grad(): + batch = next(eval_dataloader) if eval_dataloader is not None else {} + outputs = model(**batch) +``` + + +## Utility for Checkpoint reshaping and interoperability + +1. The scripts for these are present in 🤗 Transformers library under respective models. +Currently, it is available for GPT model [checkpoint_reshaping_and_interoperability.py](https://github.com/huggingface/transformers/blob/main/src/transformers/models/megatron_gpt2/checkpoint_reshaping_and_interoperability.py) + +2. Below is an example of conversion of checkpoint from Megatron-LM to universal 🤗 Transformers sharded checkpoint. +```bash +python checkpoint_reshaping_and_interoperability.py \ +--convert_checkpoint_from_megatron_to_transformers \ +--load_path "gpt/iter_0005000" \ +--save_path "gpt/trfs_checkpoint" \ +--max_shard_size "200MB" \ +--tokenizer_name "gpt2" \ +--print-checkpoint-structure +``` + +3. Conversion of checkpoint from transformers to megatron with `tp_size=2`, `pp_size=2` and `dp_size=2`. +```bash +python checkpoint_utils/megatgron_gpt2/checkpoint_reshaping_and_interoperability.py \ +--load_path "gpt/trfs_checkpoint" \ +--save_path "gpt/megatron_lm_checkpoint" \ +--target_tensor_model_parallel_size 2 \ +--target_pipeline_model_parallel_size 2 \ +--target_data_parallel_size 2 \ +--target_params_dtype "bf16" \ +--make_vocab_size_divisible_by 128 \ +--use_distributed_optimizer \ +--print-checkpoint-structure +``` + +## Megatron-LM GPT models support returning logits and `megatron_generate` function for text generation + +1. Returning logits require setting `require_logits=True` in MegatronLMPlugin as shown below. +These would be available on the in the last stage of pipeline. +```python +megatron_lm_plugin = MegatronLMPlugin(return_logits=True) +``` + +2. `megatron_generate` method for Megatron-LM GPT model: This will use Tensor and Pipeline Parallelism to complete +generations for a batch of inputs when using greedy with/without top_k/top_p sampling and for individual prompt inputs when using beam search decoding. +Only a subset of features of transformers generate is supported. This will help in using large models via tensor and pipeline parallelism +for generation (already does key-value caching and uses fused kernels by default). +This requires data parallel size to be 1, sequence parallelism and activation checkpointing to be disabled. +It also requires specifying path to tokenizer's vocab file and merges file. +Below example shows how to configure and use `megatron_generate` method for Megatron-LM GPT model. +```python +# specifying tokenizer's vocab and merges file +vocab_file = os.path.join(args.resume_from_checkpoint, "vocab.json") +merge_file = os.path.join(args.resume_from_checkpoint, "merges.txt") +other_megatron_args = {"vocab_file": vocab_file, "merge_file": merge_file} +megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args) + +# inference using `megatron_generate` functionality +tokenizer.pad_token = tokenizer.eos_token +max_new_tokens = 64 +batch_texts = [ + "Are you human?", + "The purpose of life is", + "The arsenal was constructed at the request of", + "How are you doing these days?", +] +batch_encodings = tokenizer(batch_texts, return_tensors="pt", padding=True) + +# top-p sampling +generated_tokens = model.megatron_generate( + batch_encodings["input_ids"], + batch_encodings["attention_mask"], + max_new_tokens=max_new_tokens, + top_p=0.8, + top_p_decay=0.5, + temperature=0.9, +) +decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy()) +accelerator.print(decoded_preds) + +# top-k sampling +generated_tokens = model.megatron_generate( + batch_encodings["input_ids"], + batch_encodings["attention_mask"], + max_new_tokens=max_new_tokens, + top_k=50, + temperature=0.9, +) +decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy()) +accelerator.print(decoded_preds) + +# adding `bos` token at the start +generated_tokens = model.megatron_generate( + batch_encodings["input_ids"], batch_encodings["attention_mask"], max_new_tokens=max_new_tokens, add_BOS=True +) +decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy()) +accelerator.print(decoded_preds) + +# beam search => only takes single prompt +batch_texts = ["The purpose of life is"] +batch_encodings = tokenizer(batch_texts, return_tensors="pt", padding=True) +generated_tokens = model.megatron_generate( + batch_encodings["input_ids"], + batch_encodings["attention_mask"], + max_new_tokens=max_new_tokens, + num_beams=20, + length_penalty=1.5, +) +decoded_preds = tokenizer.batch_decode(generated_tokens.cpu().numpy()) +accelerator.print(decoded_preds) +``` + +3. An end-to-end example of using `megatron_generate` method for Megatron-LM GPT model is available at +[megatron_gpt2_generation.py](https://github.com/pacman100/accelerate-megatron-test/blob/main/src/inference/megatron_gpt2_generation.py) with +config file [megatron_lm_gpt_generate_config.yaml](https://github.com/pacman100/accelerate-megatron-test/blob/main/src/Configs/megatron_lm_gpt_generate_config.yaml). +The bash script with accelerate launch command is available at [megatron_lm_gpt_generate.sh](https://github.com/pacman100/accelerate-megatron-test/blob/main/megatron_lm_gpt_generate.sh). +The output logs of the script are available at [megatron_lm_gpt_generate.log](https://github.com/pacman100/accelerate-megatron-test/blob/main/output_logs/megatron_lm_gpt_generate.log). + +## Support for ROPE and ALiBi Positional embeddings and Multi-Query Attention + +1. For ROPE/ALiBi attention, pass `position_embedding_type` with `("absolute" | "rotary" | "alibi")` to `MegatronLMPlugin` as shown below. +```python +other_megatron_args = {"position_embedding_type": "alibi"} +megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args) +``` + +2. For Multi-Query Attention, pass `attention_head_type` with `("multihead" | "multiquery")` to `MegatronLMPlugin` as shown below. +```python +other_megatron_args = {"attention_head_type": "multiquery"} +megatron_lm_plugin = MegatronLMPlugin(other_megatron_args=other_megatron_args) +``` + +## Caveats + +1. Supports Transformers GPT2, Megatron-BERT and T5 models. +This covers Decoder only, Encode only and Encoder-Decoder model classes. + +2. Only loss is returned from model forward pass as +there is quite complex interplay of pipeline, tensor and data parallelism behind the scenes. +The `model(**batch_data)` call return loss(es) averaged across the data parallel ranks. +This is fine for most cases wherein pre-training jobs are run using Megatron-LM features and +you can easily compute the `perplexity` using the loss. +For GPT model, returning logits in addition to loss(es) is supported. +These logits aren't gathered across data parallel ranks. Use `accelerator.utils.gather_across_data_parallel_groups` +to gather logits across data parallel ranks. These logits along with labels can be used for computing various +performance metrics. + +3. The main process is the last rank as the losses/logits are available in the last stage of pipeline. +`accelerator.is_main_process` and `accelerator.is_local_main_process` return `True` for last rank when using +Megatron-LM integration. + +4. In `accelerator.prepare` call, a Megatron-LM model corresponding to a given Transformers model is created +with random weights. Please use `accelerator.load_state` to load the Megatron-LM checkpoint with matching TP, PP and DP partitions. + +5. Currently, checkpoint reshaping and interoperability support is only available for GPT. +Soon it will be extended to BERT and T5. + +6. `gradient_accumulation_steps` needs to be 1. When using Megatron-LM, micro batches in pipeline parallelism +setting is synonymous with gradient accumulation. + +7. When using Megatron-LM, use `accelerator.save_state` and `accelerator.load_state` for saving and loading checkpoints. + +8. Below are the mapping from Megatron-LM model architectures to the the equivalent 🤗 transformers model architectures. +Only these 🤗 transformers model architectures are supported. + +a. Megatron-LM [BertModel](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/bert_model.py) : +🤗 transformers models with `megatron-bert` in config's model type, e.g., +[MegatronBERT](https://huggingface.co/docs/transformers/model_doc/megatron-bert) + +b. Megatron-LM [GPTModel](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/gpt_model.py) : +🤗 transformers models with `gpt2` in config's model type, e.g., +[OpenAI GPT2](https://huggingface.co/docs/transformers/model_doc/gpt2) + +c. Megatron-LM [T5Model](https://github.com/NVIDIA/Megatron-LM/blob/main/megatron/model/t5_model.py) : +🤗 transformers models with `t5` in config's model type, e.g., +[T5](https://huggingface.co/docs/transformers/model_doc/t5) and +[MT5](https://huggingface.co/docs/transformers/model_doc/mt5) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/model_size_estimator.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/model_size_estimator.md new file mode 100644 index 0000000000000000000000000000000000000000..4e95b19875ec4a2dfc30217ce63288efe341aa6e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/model_size_estimator.md @@ -0,0 +1,137 @@ + + +# Understanding how big of a model can fit on your machine + +One very difficult aspect when exploring potential models to use on your machine is knowing just how big of a model will *fit* into memory with your current graphics card (such as loading the model onto CUDA). + +To help alleviate this, 🤗 Accelerate has a CLI interface through `accelerate estimate-memory`. This tutorial will +help walk you through using it, what to expect, and at the end link to the interactive demo hosted on the 🤗 Hub which will +even let you post those results directly on the model repo! + +Currently we support searching for models that can be used in `timm` and `transformers`. + + + + This API will load the model into memory on the `meta` device, so we are not actually downloading + and loading the full weights of the model into memory, nor do we need to. As a result it's + perfectly fine to measure 8 billion parameter models (or more), without having to worry about + if your CPU can handle it! + + + +## Gradio Demos + +Below are a few gradio demos related to what was described above. The first is the official Hugging Face memory estimation space, utilizing Accelerate directly: + +
+ +
+ + +A community member has taken the idea and expanded it further, allowing you to filter models directly and see if you can run a particular LLM given GPU constraints and LoRA configurations. To play with it, see [here](https://huggingface.co/spaces/Vokturz/can-it-run-llm) for more details. + +## The Command + +When using `accelerate estimate-memory`, you need to pass in the name of the model you want to use, potentially the framework +that model utilizing (if it can't be found automatically), and the data types you want the model to be loaded in with. + +For example, here is how we can calculate the memory footprint for `bert-base-cased`: + +```bash +accelerate estimate-memory bert-base-cased +``` + +This will download the `config.json` for `bert-based-cased`, load the model on the `meta` device, and report back how much space +it will use: + +Memory Usage for loading `bert-base-cased`: + +| dtype | Largest Layer | Total Size | Training using Adam | +|---------|---------------|------------|---------------------| +| float32 | 84.95 MB | 418.18 MB | 1.61 GB | +| float16 | 42.47 MB | 206.59 MB | 826.36 MB | +| int8 | 21.24 MB | 103.29 MB | 413.18 MB | +| int4 | 10.62 MB | 51.65 MB | 206.59 MB | + +By default it will return all the supported dtypes (`int4` through `float32`), but if you are interested in specific ones these can be filtered. + +### Specific libraries + +If the source library cannot be determined automatically (like it could in the case of `bert-base-cased`), a library name can +be passed in. + +```bash +accelerate estimate-memory HuggingFaceM4/idefics-80b-instruct --library_name transformers +``` + +Memory Usage for loading `HuggingFaceM4/idefics-80b-instruct`: + +| dtype | Largest Layer | Total Size | Training using Adam | +|---------|---------------|------------|---------------------| +| float32 | 3.02 GB | 297.12 GB | 1.16 TB | +| float16 | 1.51 GB | 148.56 GB | 594.24 GB | +| int8 | 772.52 MB | 74.28 GB | 297.12 GB | +| int4 | 386.26 MB | 37.14 GB | 148.56 GB | + + +```bash +accelerate estimate-memory timm/resnet50.a1_in1k --library_name timm +``` + +Memory Usage for loading `timm/resnet50.a1_in1k`: + +| dtype | Largest Layer | Total Size | Training using Adam | +|---------|---------------|------------|---------------------| +| float32 | 9.0 MB | 97.7 MB | 390.78 MB | +| float16 | 4.5 MB | 48.85 MB | 195.39 MB | +| int8 | 2.25 MB | 24.42 MB | 97.7 MB | +| int4 | 1.12 MB | 12.21 MB | 48.85 MB | + +### Specific dtypes + +As mentioned earlier, while we return `int4` through `float32` by default, any dtype can be used from `float32`, `float16`, `int8`, and `int4`. + +To do so, pass them in after specifying `--dtypes`: + +```bash +accelerate estimate-memory bert-base-cased --dtypes float32 float16 +``` + +Memory Usage for loading `bert-base-cased`: + +| dtype | Largest Layer | Total Size | Training using Adam | +|---------|---------------|------------|---------------------| +| float32 | 84.95 MB | 413.18 MB | 1.61 GB | +| float16 | 42.47 MB | 206.59 MB | 826.36 MB | + +## Caveats with this calculator + +This calculator will tell you how much memory is needed to purely load the model in, *not* to perform inference. + +This calculation is accurate within a few % of the actual value, so it is a very good view of just how much memory it will take. For instance loading `bert-base-cased` actually takes `413.68 MB` when loaded on CUDA in full precision, and the calculator estimates `413.18 MB`. + +When performing inference you can expect to add up to an additional 20% as found by [EleutherAI](https://blog.eleuther.ai/transformer-math/). We'll be conducting research into finding a more accurate estimate to these values, and will update +this calculator once done. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/mps.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/mps.md new file mode 100644 index 0000000000000000000000000000000000000000..8bd2912d79cc6138ea605b5699f134318144151b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/mps.md @@ -0,0 +1,54 @@ + + +# Accelerated PyTorch Training on Mac + +With PyTorch v1.12 release, developers and researchers can take advantage of Apple silicon GPUs for significantly faster model training. +This unlocks the ability to perform machine learning workflows like prototyping and fine-tuning locally, right on Mac. +Apple's Metal Performance Shaders (MPS) as a backend for PyTorch enables this and can be used via the new `"mps"` device. +This will map computational graphs and primitives on the MPS Graph framework and tuned kernels provided by MPS. +For more information please refer official documents [Introducing Accelerated PyTorch Training on Mac](https://pytorch.org/blog/introducing-accelerated-pytorch-training-on-mac/) +and [MPS BACKEND](https://pytorch.org/docs/stable/notes/mps.html). + +### Benefits of Training and Inference using Apple Silicon Chips + +1. Enables users to train larger networks or batch sizes locally +2. Reduces data retrieval latency and provides the GPU with direct access to the full memory store due to unified memory architecture. +Therefore, improving end-to-end performance. +3. Reduces costs associated with cloud-based development or the need for additional local GPUs. + +**Pre-requisites**: To install torch with mps support, +please follow this nice medium article [GPU-Acceleration Comes to PyTorch on M1 Macs](https://medium.com/towards-data-science/gpu-acceleration-comes-to-pytorch-on-m1-macs-195c399efcc1). + + +## How it works out of the box +It is enabled by default on MacOs machines with MPS enabled Apple Silicon GPUs. +To disable it, pass `--cpu` flag to `accelerate launch` command or answer the corresponding question when answering the `accelerate config` questionnaire. + +You can directly run the following script to test it out on MPS enabled Apple Silicon machines: +```bash +accelerate launch /examples/cv_example.py --data_dir images +``` + +## A few caveats to be aware of + +1. We strongly recommend to install PyTorch >= 1.13 (nightly version at the time of writing) on your MacOS machine. +It has major fixes related to model correctness and performance improvements for transformer based models. +Please refer to https://github.com/pytorch/pytorch/issues/82707 for more details. +2. Distributed setups `gloo` and `nccl` are not working with `mps` device. +This means that currently only single GPU of `mps` device type can be used. + +Finally, please, remember that, 🤗 `Accelerate` only integrates MPS backend, therefore if you +have any problems or questions with regards to MPS backend usage, please, file an issue with [PyTorch GitHub](https://github.com/pytorch/pytorch/issues). \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/profiler.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/profiler.md new file mode 100644 index 0000000000000000000000000000000000000000..be32193135eae2527f22f682bb926e65d7467846 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/profiler.md @@ -0,0 +1,334 @@ + + +# Profiler + +Profiler is a tool that allows the collection of performance metrics during training and inference. Profiler’s context manager API can be used to better understand what model operators are the most expensive, examine their input shapes and stack traces, study device kernel activity, and visualize the execution trace. It provides insights into the performance of your model, allowing you to optimize and improve it. + +This guide explains how to use PyTorch Profiler to measure the time and memory consumption of the model’s operators and how to integrate this with 🤗 Accelerate. We will cover various use cases and provide examples for each. + +## Using profiler to analyze execution time + +Profiler allows one to check which operators were called during the execution of a code range wrapped with a profiler context manager. + +Let’s see how we can use profiler to analyze the execution time: + + + + +```python +import torch +import torchvision.models as models +from torch.profiler import profile, record_function, ProfilerActivity + +model = models.resnet18() +inputs = torch.randn(5, 3, 224, 224) + +with profile(activities=[ProfilerActivity.CPU], record_shapes=True) as prof: + model(inputs) + +print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10)) +``` + + + + +```python +from accelerate import Accelerator, ProfileKwargs +import torch +import torchvision.models as models + +model = models.resnet18() +inputs = torch.randn(5, 3, 224, 224) + +profile_kwargs = ProfileKwargs( + activities=["cpu"], + record_shapes=True +) + +accelerator = Accelerator(cpu=True, kwargs_handlers=[profile_kwargs]) +model = accelerator.prepare(model) + +with accelerator.profile() as prof: + with torch.no_grad(): + model(inputs) + +print(prof.key_averages().table(sort_by="cpu_time_total", row_limit=10)) +``` + + + + +The resulting table output (omitting some columns): + +``` +--------------------------------- ------------ ------------ ------------ ------------ + Name Self CPU CPU total CPU time avg # of Calls +--------------------------------- ------------ ------------ ------------ ------------ + aten::conv2d 171.000us 52.260ms 2.613ms 20 + aten::convolution 227.000us 52.089ms 2.604ms 20 + aten::_convolution 270.000us 51.862ms 2.593ms 20 + aten::mkldnn_convolution 51.273ms 51.592ms 2.580ms 20 + aten::batch_norm 118.000us 7.059ms 352.950us 20 + aten::_batch_norm_impl_index 315.000us 6.941ms 347.050us 20 + aten::native_batch_norm 6.305ms 6.599ms 329.950us 20 + aten::max_pool2d 40.000us 4.008ms 4.008ms 1 + aten::max_pool2d_with_indices 3.968ms 3.968ms 3.968ms 1 + aten::add_ 780.000us 780.000us 27.857us 28 +--------------------------------- ------------ ------------ ------------ ------------ +Self CPU time total: 67.016ms +``` + +To get a finer granularity of results and include operator input shapes, pass `group_by_input_shape=True` (note: this requires running the profiler with `record_shapes=True`): + +```python +print(prof.key_averages(group_by_input_shape=True).table(sort_by="cpu_time_total", row_limit=10)) +``` + +## Using profiler to analyze memory consumption + +Profiler can also show the amount of memory (used by the model’s tensors) that was allocated (or released) during the execution of the model’s operators. To enable memory profiling functionality pass `profile_memory=True`. + + + + +```python +model = models.resnet18() +inputs = torch.randn(5, 3, 224, 224) + +with profile(activities=[ProfilerActivity.CPU], + profile_memory=True, record_shapes=True) as prof: + model(inputs) + +print(prof.key_averages().table(sort_by="self_cpu_memory_usage", row_limit=10)) +``` + + + + +```python +model = models.resnet18() +inputs = torch.randn(5, 3, 224, 224) + +profile_kwargs = ProfileKwargs( + activities=["cpu"], + profile_memory=True, + record_shapes=True +) + +accelerator = Accelerator(cpu=True, kwargs_handlers=[profile_kwargs]) +model = accelerator.prepare(model) + +with accelerator.profile() as prof: + model(inputs) + +print(prof.key_averages().table(sort_by="self_cpu_memory_usage", row_limit=10)) +``` + + + + +The resulting table output (omitting some columns): + +``` +--------------------------------- ------------ ------------ ------------ + Name CPU Mem Self CPU Mem # of Calls +--------------------------------- ------------ ------------ ------------ + aten::empty 94.85 Mb 94.85 Mb 205 + aten::max_pool2d_with_indices 11.48 Mb 11.48 Mb 1 + aten::addmm 19.53 Kb 19.53 Kb 1 + aten::mean 10.00 Kb 10.00 Kb 1 + aten::empty_strided 492 b 492 b 5 + aten::cat 240 b 240 b 6 + aten::abs 480 b 240 b 4 + aten::masked_select 120 b 112 b 1 + aten::ne 61 b 53 b 3 + aten::eq 30 b 30 b 1 +--------------------------------- ------------ ------------ ------------ +Self CPU time total: 69.332ms +``` + + +## Exporting chrome trace + +You can examine the sequence of profiled operators and CUDA kernels in Chrome trace viewer (`chrome://tracing`): + +![profile_export](https://github.com/huggingface/accelerate/assets/100389977/5acb193f-6d11-4f7b-9873-c600c19e8172) + + + + +```python +model = models.resnet18().cuda() +inputs = torch.randn(5, 3, 224, 224).cuda() + +with profile(activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA]) as prof: + model(inputs) + +prof.export_chrome_trace("trace.json") +``` + + + + +```python +profile_kwargs = ProfileKwargs( + activities=["cpu", "cuda"], + output_trace_dir="trace" +) + +accelerator = Accelerator(kwargs_handlers=[profile_kwargs]) +model = accelerator.prepare(model) + +with accelerator.profile() as prof: + model(inputs) + +# The trace will be saved to the specified directory +``` + + + + +## Using Profiler to Analyze Long-Running Jobs + +Profiler offers an additional API to handle long-running jobs (such as training loops). Tracing all of the execution can be slow and result in very large trace files. To avoid this, use optional arguments: + +- `schedule_option`: Scheduling options allow you to control when profiling is active. This is useful for long-running jobs to avoid collecting too much data. Available keys are `wait`, `warmup`, `active`, `repeat` and `skip_first`. The profiler will skip the first `skip_first` steps, then wait for `wait` steps, then do the warmup for the next `warmup` steps, then do the active recording for the next `active` steps and then repeat the cycle starting with `wait` steps. The optional number of cycles is specified with the `repeat` parameter, the zero value means that the cycles will continue until the profiling is finished. +- `on_trace_ready`: specifies a function that takes a reference to the profiler as an input and is called by the profiler each time the new trace is ready. + +To illustrate how the API works, consider the following example: + + + + +```python +from torch.profiler import schedule + +my_schedule = schedule( + skip_first=10, + wait=5, + warmup=1, + active=3, + repeat=2 +) + +def trace_handler(p): + output = p.key_averages().table(sort_by="self_cuda_time_total", row_limit=10) + print(output) + p.export_chrome_trace("/tmp/trace_" + str(p.step_num) + ".json") + +with profile( + activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], + schedule=my_schedule, + on_trace_ready=trace_handler +) as p: + for idx in range(8): + model(inputs) + p.step() +``` + + + + +```python +def trace_handler(p): + output = p.key_averages().table(sort_by="self_cuda_time_total", row_limit=10) + print(output) + p.export_chrome_trace("/tmp/trace_" + str(p.step_num) + ".json") + +profile_kwargs = ProfileKwargs( + activities=["cpu", "cuda"], + schedule_option={"wait": 5, "warmup": 1, "active": 3, "repeat": 2, "skip_first": 10}, + on_trace_ready=trace_handler +) + +accelerator = Accelerator(kwargs_handlers=[profile_kwargs]) +model = accelerator.prepare(model) + +with accelerator.profile() as prof: + for idx in range(8): + model(inputs) + prof.step() +``` + + + + +## FLOPS + +Use formula to estimate the FLOPs (floating point operations) of specific operators (matrix multiplication and 2D convolution). + +To measure floating-point operations (FLOPS): + + + + +```python +with profile( + activities=[ProfilerActivity.CPU, ProfilerActivity.CUDA], + with_flops=True +) as prof: + model(inputs) + +print(prof.key_averages().table(sort_by="flops", row_limit=10)) +``` + + + + +```python +profile_kwargs = ProfileKwargs( + with_flops=True +) +accelerator = Accelerator(kwargs_handlers=[profile_kwargs]) + +with accelerator.profile() as prof: + model(inputs) + +print(prof.key_averages().table(sort_by="flops", row_limit=10)) +``` + + + + +The resulting table output (omitting some columns): + +``` +------------------------------------------------------- ------------ ------------ ------------ + Name Self CPU Self CUDA Total FLOPs +------------------------------------------------------- ------------ ------------ ------------ + aten::conv2d 197.000us 0.000us 18135613440.000 + aten::addmm 103.000us 17.000us 5120000.000 + aten::mul 29.000us 2.000us 30.000 + aten::convolution 409.000us 0.000us -- + aten::_convolution 253.000us 0.000us -- + aten::cudnn_convolution 5.465ms 2.970ms -- + cudaEventRecord 138.000us 0.000us -- + cudaStreamIsCapturing 43.000us 0.000us -- + cudaStreamGetPriority 40.000us 0.000us -- + cudaDeviceGetStreamPriorityRange 10.000us 0.000us -- +------------------------------------------------------- ------------ ------------ ------------ +Self CPU time total: 21.938ms +Self CUDA time total: 4.165ms +``` + + + +## Conclusion and Further Information + +PyTorch Profiler is a powerful tool for analyzing the performance of your models. By integrating it with 🤗 Accelerate, you can easily profile your models and gain insights into their performance, helping you to optimize and improve them. + +For more detailed information, refer to the [PyTorch Profiler documentation](https://pytorch.org/docs/stable/profiler.html). \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/quantization.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/quantization.md new file mode 100644 index 0000000000000000000000000000000000000000..4c60de4fa2dcb57e184922e161c7ff81acd81691 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/quantization.md @@ -0,0 +1,136 @@ + + +# Quantization + +## `bitsandbytes` Integration + +🤗 Accelerate brings `bitsandbytes` quantization to your model. You can now load any pytorch model in 8-bit or 4-bit with a few lines of code. + +If you want to use 🤗 Transformers models with `bitsandbytes`, you should follow this [documentation](https://huggingface.co/docs/transformers/main_classes/quantization). + +To learn more about how the `bitsandbytes` quantization works, check out the blog posts on [8-bit quantization](https://huggingface.co/blog/hf-bitsandbytes-integration) and [4-bit quantization](https://huggingface.co/blog/4bit-transformers-bitsandbytes). + +### Pre-Requisites +You will need to install the following requirements: + +- Install `bitsandbytes` library +```bash +pip install bitsandbytes +``` +- Install latest `accelerate` from source +```bash +pip install git+https://github.com/huggingface/accelerate.git +``` +- Install `minGPT` and `huggingface_hub` to run examples +```bash +git clone https://github.com/karpathy/minGPT.git +pip install minGPT/ +pip install huggingface_hub +``` + +### How it works + +First, we need to initialize our model. To save memory, we can initialize an empty model using the context manager [`init_empty_weights`]. + +Let's take the GPT2 model from minGPT library. +```py +from accelerate import init_empty_weights +from mingpt.model import GPT + +model_config = GPT.get_default_config() +model_config.model_type = 'gpt2-xl' +model_config.vocab_size = 50257 +model_config.block_size = 1024 + +with init_empty_weights(): + empty_model = GPT(model_config) +``` + +Then, we need to get the path to the weights of your model. The path can be the state_dict file (e.g. "pytorch_model.bin") or a folder containing the sharded checkpoints. + +```py +from huggingface_hub import snapshot_download +weights_location = snapshot_download(repo_id="marcsun13/gpt2-xl-linear-sharded") +``` + +Finally, you need to set your quantization configuration with [`~utils.BnbQuantizationConfig`]. + +Here's an example for 8-bit quantization: +```py +from accelerate.utils import BnbQuantizationConfig +bnb_quantization_config = BnbQuantizationConfig(load_in_8bit=True, llm_int8_threshold = 6) +``` + +Here's an example for 4-bit quantization: +```py +from accelerate.utils import BnbQuantizationConfig +bnb_quantization_config = BnbQuantizationConfig(load_in_4bit=True, bnb_4bit_compute_dtype=torch.bfloat16, bnb_4bit_use_double_quant=True, bnb_4bit_quant_type="nf4") +``` + +To quantize your empty model with the selected configuration, you need to use [`~utils.load_and_quantize_model`]. + +```py +from accelerate.utils import load_and_quantize_model +quantized_model = load_and_quantize_model(empty_model, weights_location=weights_location, bnb_quantization_config=bnb_quantization_config, device_map = "auto") +``` + +### Saving and loading 8-bit model + +You can save your 8-bit model with accelerate using [`~Accelerator.save_model`]. + +```py +from accelerate import Accelerator +accelerate = Accelerator() +new_weights_location = "path/to/save_directory" +accelerate.save_model(quantized_model, new_weights_location) + +quantized_model_from_saved = load_and_quantize_model(empty_model, weights_location=new_weights_location, bnb_quantization_config=bnb_quantization_config, device_map = "auto") +``` + +Note that 4-bit model serialization is currently not supported. + +### Offload modules to cpu and disk + +You can offload some modules to cpu/disk if you don't have enough space on the GPU to store the entire model on your GPUs. +This uses big model inference under the hood. Check this [documentation](https://huggingface.co/docs/accelerate/usage_guides/big_modeling) for more details. + +For 8-bit quantization, the selected modules will be converted to 8-bit precision. + +For 4-bit quantization, the selected modules will be kept in `torch_dtype` that the user passed in `BnbQuantizationConfig`. We will add support to convert these offloaded modules in 4-bit when 4-bit serialization will be possible. + + You just need to pass a custom `device_map` in order to offload modules on cpu/disk. The offload modules will be dispatched on the GPU when needed. Here's an example : + +```py +device_map = { + "transformer.wte": 0, + "transformer.wpe": 0, + "transformer.drop": 0, + "transformer.h": "cpu", + "transformer.ln_f": "disk", + "lm_head": "disk", +} +``` +### Fine-tune a quantized model + +It is not possible to perform pure 8bit or 4bit training on these models. However, you can train these models by leveraging parameter efficient fine tuning methods (PEFT) and train for example adapters on top of them. Please have a look at [peft](https://github.com/huggingface/peft) library for more details. + +Currently, you can't add adapters on top of any quantized model. However, with the official support of adapters with 🤗 Transformers models, you can fine-tune quantized models. If you want to finetune a 🤗 Transformers model , follow this [documentation](https://huggingface.co/docs/transformers/main_classes/quantization) instead. Check out this [demo](https://colab.research.google.com/drive/1VoYNfYDKcKRQRor98Zbf2-9VQTtGJ24k?usp=sharing) on how to fine-tune a 4-bit 🤗 Transformers model. + +Note that you don’t need to pass `device_map` when loading the model for training. It will automatically load your model on your GPU. Please note that `device_map=auto` should be used for inference only. + +### Example demo - running GPT2 1.5b on a Google Colab + +Check out the Google Colab [demo](https://colab.research.google.com/drive/1T1pOgewAWVpR9gKpaEWw4orOrzPFb3yM?usp=sharing) for running quantized models on a GTP2 model. The GPT2-1.5B model checkpoint is in FP32 which uses 6GB of memory. After quantization, it uses 1.6GB with 8-bit modules and 1.2GB with 4-bit modules. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/sagemaker.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/sagemaker.md new file mode 100644 index 0000000000000000000000000000000000000000..4d7c12f4bcf098c02f00127778d95e9e9beb26d9 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/sagemaker.md @@ -0,0 +1,205 @@ + + +# Amazon SageMaker + +Hugging Face and Amazon introduced new [Hugging Face Deep Learning Containers (DLCs)](https://github.com/aws/deep-learning-containers/blob/master/available_images.md#huggingface-training-containers) to +make it easier than ever to train Hugging Face Transformer models in [Amazon SageMaker](https://aws.amazon.com/sagemaker/). + +## Getting Started + +### Setup & Installation + + +Before you can run your 🤗 Accelerate scripts on Amazon SageMaker you need to sign up for an AWS account. If you do not +have an AWS account yet learn more [here](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-set-up.html). + +After you have your AWS Account you need to install the `sagemaker` sdk for 🤗 Accelerate with: + +```bash +pip install "accelerate[sagemaker]" --upgrade +``` + +🤗 Accelerate currently uses the 🤗 DLCs, with `transformers`, `datasets` and `tokenizers` pre-installed. 🤗 +Accelerate is not in the DLC yet (will soon be added!) so to use it within Amazon SageMaker you need to create a +`requirements.txt` in the same directory where your training script is located and add it as dependency: + +``` +accelerate +``` + +You should also add any other dependencies you have to this `requirements.txt`. + + +### Configure 🤗 Accelerate + +You can configure the launch configuration for Amazon SageMaker the same as you do for non SageMaker training jobs with +the 🤗 Accelerate CLI: + +```bash +accelerate config +# In which compute environment are you running? ([0] This machine, [1] AWS (Amazon SageMaker)): 1 +``` + +🤗 Accelerate will go through a questionnaire about your Amazon SageMaker setup and create a config file you can edit. + + + + 🤗 Accelerate is not saving any of your credentials. + + + +### Prepare a 🤗 Accelerate fine-tuning script + +The training script is very similar to a training script you might run outside of SageMaker, but to save your model +after training you need to specify either `/opt/ml/model` or use `os.environ["SM_MODEL_DIR"]` as your save +directory. After training, artifacts in this directory are uploaded to S3: + + +```diff +- torch.save('/opt/ml/model`) ++ accelerator.save('/opt/ml/model') +``` + + + + SageMaker doesn’t support argparse actions. If you want to use, for example, boolean hyperparameters, you need to + specify type as bool in your script and provide an explicit True or False value for this hyperparameter. [[REF]](https://sagemaker.readthedocs.io/en/stable/frameworks/pytorch/using_pytorch.html#prepare-a-pytorch-training-script). + + + +### Launch Training + +You can launch your training with 🤗 Accelerate CLI with: + +``` +accelerate launch path_to_script.py --args_to_the_script +``` + +This will launch your training script using your configuration. The only thing you have to do is provide all the +arguments needed by your training script as named arguments. + +**Examples** + + + + If you run one of the example scripts, don't forget to add `accelerator.save('/opt/ml/model')` to it. + + + +```bash +accelerate launch ./examples/sagemaker_example.py +``` + +Outputs: + +``` +Configuring Amazon SageMaker environment +Converting Arguments to Hyperparameters +Creating Estimator +2021-04-08 11:56:50 Starting - Starting the training job... +2021-04-08 11:57:13 Starting - Launching requested ML instancesProfilerReport-1617883008: InProgress +......... +2021-04-08 11:58:54 Starting - Preparing the instances for training......... +2021-04-08 12:00:24 Downloading - Downloading input data +2021-04-08 12:00:24 Training - Downloading the training image.................. +2021-04-08 12:03:39 Training - Training image download completed. Training in progress.. +........ +epoch 0: {'accuracy': 0.7598039215686274, 'f1': 0.8178438661710037} +epoch 1: {'accuracy': 0.8357843137254902, 'f1': 0.882249560632689} +epoch 2: {'accuracy': 0.8406862745098039, 'f1': 0.8869565217391304} +........ +2021-04-08 12:05:40 Uploading - Uploading generated training model +2021-04-08 12:05:40 Completed - Training job completed +Training seconds: 331 +Billable seconds: 331 +You can find your model data at: s3://your-bucket/accelerate-sagemaker-1-2021-04-08-11-56-47-108/output/model.tar.gz +``` + +## Advanced Features + +### Distributed Training: Data Parallelism + +Set up the accelerate config by running `accelerate config` and answer the SageMaker questions and set it up. +To use SageMaker DDP, select it when asked +`What is the distributed mode? ([0] No distributed training, [1] data parallelism):`. +Example config below: +```yaml +base_job_name: accelerate-sagemaker-1 +compute_environment: AMAZON_SAGEMAKER +distributed_type: DATA_PARALLEL +ec2_instance_type: ml.p3.16xlarge +iam_role_name: xxxxx +image_uri: null +mixed_precision: fp16 +num_machines: 1 +profile: xxxxx +py_version: py38 +pytorch_version: 1.10.2 +region: us-east-1 +transformers_version: 4.17.0 +use_cpu: false +``` + +### Distributed Training: Model Parallelism + +*currently in development, will be supported soon.* + +### Python packages and dependencies + +🤗 Accelerate currently uses the 🤗 DLCs, with `transformers`, `datasets` and `tokenizers` pre-installed. If you +want to use different/other Python packages you can do this by adding them to the `requirements.txt`. These packages +will be installed before your training script is started. + +### Local Training: SageMaker Local mode + +The local mode in the SageMaker SDK allows you to run your training script locally inside the HuggingFace DLC (Deep Learning container) +or using your custom container image. This is useful for debugging and testing your training script inside the final container environment. +Local mode uses Docker compose (*Note: Docker Compose V2 is not supported yet*). The SDK will handle the authentication against ECR +to pull the DLC to your local environment. You can emulate CPU (single and multi-instance) and GPU (single instance) SageMaker training jobs. + +To use local mode, you need to set your `ec2_instance_type` to `local`. + +```yaml +ec2_instance_type: local +``` + +### Advanced configuration + +The configuration allows you to override parameters for the [Estimator](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html). +These settings have to be applied in the config file and are not part of `accelerate config`. You can control many additional aspects of the training job, e.g. use Spot instances, enable network isolation and many more. + +```yaml +additional_args: + # enable network isolation to restrict internet access for containers + enable_network_isolation: True +``` + +You can find all available configuration [here](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html). + +### Use Spot Instances + +You can use Spot Instances e.g. using (see [Advanced configuration](#advanced-configuration)): +```yaml +additional_args: + use_spot_instances: True + max_wait: 86400 +``` + +*Note: Spot Instances are subject to be terminated and training to be continued from a checkpoint. This is not handled in 🤗 Accelerate out of the box. Contact us if you would like this feature.* + +### Remote scripts: Use scripts located on Github + +*undecided if feature is needed. Contact us if you would like this feature.* \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/tracking.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/tracking.md new file mode 100644 index 0000000000000000000000000000000000000000..80d69bca0460c9e357f2c5e3bdd840b4ec890c3f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/tracking.md @@ -0,0 +1,233 @@ + + +# Tracking + +There are a large number of experiment tracking API's available, however getting them all to work with in a multi-processing environment can oftentimes be complex. +🤗 Accelerate provides a general tracking API that can be used to log useful items during your script through [`Accelerator.log`] + +## Integrated Trackers + +Currently `Accelerate` supports seven trackers out-of-the-box: + +- TensorBoard +- WandB +- CometML +- Aim +- MLFlow +- ClearML +- DVCLive + +To use any of them, pass in the selected type(s) to the `log_with` parameter in [`Accelerate`]: +```python +from accelerate import Accelerator +from accelerate.utils import LoggerType + +accelerator = Accelerator(log_with="all") # For all available trackers in the environment +accelerator = Accelerator(log_with="wandb") +accelerator = Accelerator(log_with=["wandb", LoggerType.TENSORBOARD]) +``` + +At the start of your experiment [`Accelerator.init_trackers`] should be used to setup your project, and potentially add any experiment hyperparameters to be logged: +```python +hps = {"num_iterations": 5, "learning_rate": 1e-2} +accelerator.init_trackers("my_project", config=hps) +``` + +When you are ready to log any data, [`Accelerator.log`] should be used. +A `step` can also be passed in to correlate the data with a particular step in the training loop. +```python +accelerator.log({"train_loss": 1.12, "valid_loss": 0.8}, step=1) +``` + +Once you've finished training, make sure to run [`Accelerator.end_training`] so that all the trackers can run their finish functionalities if they have any. +```python +accelerator.end_training() +``` + + +A full example is below: +```python +from accelerate import Accelerator + +accelerator = Accelerator(log_with="all") +config = { + "num_iterations": 5, + "learning_rate": 1e-2, + "loss_function": str(my_loss_function), +} + +accelerator.init_trackers("example_project", config=config) + +my_model, my_optimizer, my_training_dataloader = accelerate.prepare(my_model, my_optimizer, my_training_dataloader) +device = accelerator.device +my_model.to(device) + +for iteration in config["num_iterations"]: + for step, batch in my_training_dataloader: + my_optimizer.zero_grad() + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = my_model(inputs) + loss = my_loss_function(outputs, targets) + accelerator.backward(loss) + my_optimizer.step() + accelerator.log({"training_loss": loss}, step=step) +accelerator.end_training() +``` + +If a tracker requires a directory to save data to, such as `TensorBoard`, then pass the directory path to `project_dir`. The `project_dir` parameter is useful +when there are other configurations to be combined with in the [`~utils.ProjectConfiguration`] data class. For example, you can save the TensorBoard data to `project_dir` and everything else can be logged in the `logging_dir` parameter of [`~utils.ProjectConfiguration`: + +```python +accelerator = Accelerator(log_with="tensorboard", project_dir=".") + +# use with ProjectConfiguration +config = ProjectConfiguration(project_dir=".", logging_dir="another/directory") +accelerator = Accelerator(log_with="tensorboard", project_config=config) +``` + +## Implementing Custom Trackers + +To implement a new tracker to be used in `Accelerator`, a new one can be made through implementing the [`GeneralTracker`] class. +Every tracker must implement three functions and have three properties: + - `__init__`: + - Should store a `run_name` and initialize the tracker API of the integrated library. + - If a tracker stores their data locally (such as TensorBoard), a `logging_dir` parameter can be added. + - `store_init_configuration`: + - Should take in a `values` dictionary and store them as a one-time experiment configuration + - `log`: + - Should take in a `values` dictionary and a `step`, and should log them to the run + + - `name` (`str`): + - A unique string name for the tracker, such as `"wandb"` for the wandb tracker. + - This will be used for interacting with this tracker specifically + - `requires_logging_directory` (`bool`): + - Whether a `logging_dir` is needed for this particular tracker and if it uses one. + - `tracker`: + - This should be implemented as a `@property` function + - Should return the internal tracking mechanism the library uses, such as the `run` object for `wandb`. + +Each method should also utilize the [`state.PartialState`] class if the logger should only be executed on the main process for instance. + +A brief example can be seen below with an integration with Weights and Biases, containing only the relevant information and logging just on +the main process: +```python +from accelerate.tracking import GeneralTracker, on_main_process +from typing import Optional + +import wandb + + +class MyCustomTracker(GeneralTracker): + name = "wandb" + requires_logging_directory = False + + @on_main_process + def __init__(self, run_name: str): + self.run_name = run_name + run = wandb.init(self.run_name) + + @property + def tracker(self): + return self.run.run + + @on_main_process + def store_init_configuration(self, values: dict): + wandb.config(values) + + @on_main_process + def log(self, values: dict, step: Optional[int] = None): + wandb.log(values, step=step) +``` + +When you are ready to build your `Accelerator` object, pass in an **instance** of your tracker to [`Accelerator.log_with`] to have it automatically +be used with the API: + +```python +tracker = MyCustomTracker("some_run_name") +accelerator = Accelerator(log_with=tracker) +``` + +These also can be mixed with existing trackers, including with `"all"`: + +```python +tracker = MyCustomTracker("some_run_name") +accelerator = Accelerator(log_with=[tracker, "all"]) +``` + +## Accessing the internal tracker + +If some custom interactions with a tracker might be wanted directly, you can quickly access one using the +[`Accelerator.get_tracker`] method. Just pass in the string corresponding to a tracker's `.name` attribute +and it will return that tracker on the main process. + +This example shows doing so with wandb: + +```python +wandb_tracker = accelerator.get_tracker("wandb") +``` + +From there you can interact with `wandb`'s `run` object like normal: + +```python +wandb_run.log_artifact(some_artifact_to_log) +``` + + + Trackers built in Accelerate will automatically execute on the correct process, + so if a tracker is only meant to be ran on the main process it will do so + automatically. + + +If you want to truly remove Accelerate's wrapping entirely, you can +achieve the same outcome with: + +```python +wandb_tracker = accelerator.get_tracker("wandb", unwrap=True) +if accelerator.is_main_process: + wandb_tracker.log_artifact(some_artifact_to_log) +``` + + +## When a wrapper cannot work + +If a library has an API that does not follow a strict `.log` with an overall dictionary such as Neptune.AI, logging can be done manually under an `if accelerator.is_main_process` statement: +```diff + from accelerate import Accelerator ++ import neptune.new as neptune + + accelerator = Accelerator() ++ run = neptune.init(...) + + my_model, my_optimizer, my_training_dataloader = accelerate.prepare(my_model, my_optimizer, my_training_dataloader) + device = accelerator.device + my_model.to(device) + + for iteration in config["num_iterations"]: + for batch in my_training_dataloader: + my_optimizer.zero_grad() + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = my_model(inputs) + loss = my_loss_function(outputs, targets) + total_loss += loss + accelerator.backward(loss) + my_optimizer.step() ++ if accelerator.is_main_process: ++ run["logs/training/batch/loss"].log(loss) +``` diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/training_zoo.md b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/training_zoo.md new file mode 100644 index 0000000000000000000000000000000000000000..ab7cc072d12ccc389a540aafddf50fb07121cab6 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/docs/source/usage_guides/training_zoo.md @@ -0,0 +1,180 @@ + + +# Example Zoo + +Below contains a non-exhaustive list of tutorials and scripts showcasing 🤗 Accelerate + +## Official Accelerate Examples: + +### Basic Examples + +These examples showcase the base features of Accelerate and are a great starting point + +- [Barebones NLP example](https://github.com/huggingface/accelerate/blob/main/examples/nlp_example.py) +- [Barebones distributed NLP example in a Jupyter Notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb) +- [Barebones computer vision example](https://github.com/huggingface/accelerate/blob/main/examples/cv_example.py) +- [Barebones distributed computer vision example in a Jupyter Notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_cv_example.ipynb) +- [Using Accelerate in Kaggle](https://www.kaggle.com/code/muellerzr/multi-gpu-and-accelerate) + +### Feature Specific Examples + +These examples showcase specific features that the Accelerate framework offers + +- [Automatic memory-aware gradient accumulation](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/automatic_gradient_accumulation.py) +- [Checkpointing states](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/checkpointing.py) +- [Cross validation](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/cross_validation.py) +- [DeepSpeed](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/deepspeed_with_config_support.py) +- [Fully Sharded Data Parallelism](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/fsdp_with_peak_mem_tracking.py) +- [Gradient accumulation](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/gradient_accumulation.py) +- [Memory-aware batch size finder](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/memory.py) +- [Metric Computation](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/multi_process_metrics.py) +- [Using Trackers](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/tracking.py) +- [Using Megatron-LM](https://github.com/huggingface/accelerate/blob/main/examples/by_feature/megatron_lm_gpt_pretraining.py) + +### Full Examples + +These examples showcase every feature in Accelerate at once that was shown in "Feature Specific Examples" + +- [Complete NLP example](https://github.com/huggingface/accelerate/blob/main/examples/complete_nlp_example.py) +- [Complete computer vision example](https://github.com/huggingface/accelerate/blob/main/examples/complete_cv_example.py) +- [Very complete and extensible vision example showcasing SLURM, hydra, and a very extensible usage of the framework](https://github.com/yuvalkirstain/PickScore) +- [Causal language model fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_clm_no_trainer.py) +- [Masked language model fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/language-modeling/run_mlm_no_trainer.py) +- [Speech pretraining example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/speech-pretraining/run_wav2vec2_pretraining_no_trainer.py) +- [Translation fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/translation/run_translation_no_trainer.py) +- [Text classification fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue_no_trainer.py) +- [Semantic segmentation fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/semantic-segmentation/run_semantic_segmentation_no_trainer.py) +- [Question answering fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/question-answering/run_qa_no_trainer.py) +- [Beam search question answering fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/question-answering/run_qa_beam_search_no_trainer.py) +- [Multiple choice question answering fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/multiple-choice/run_swag_no_trainer.py) +- [Named entity recognition fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/token-classification/run_ner_no_trainer.py) +- [Image classification fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/image-classification/run_image_classification_no_trainer.py) +- [Summarization fine-tuning example](https://github.com/huggingface/transformers/blob/main/examples/pytorch/summarization/run_summarization_no_trainer.py) +- [End-to-end examples on how to use AWS SageMaker integration of Accelerate](https://github.com/huggingface/notebooks/blob/main/sagemaker/22_accelerate_sagemaker_examples/README.md) +- [Megatron-LM examples for various NLp tasks](https://github.com/pacman100/accelerate-megatron-test) + +## Integration Examples + +These are tutorials from libraries that integrate with 🤗 Accelerate: + +> Don't find your integration here? Make a PR to include it! + +### Amphion +- [Training Text-to-Speech Models with Amphion](https://github.com/open-mmlab/Amphion/blob/main/egs/tts/README.md) +- [Training Singing Voice Conversion Models with Amphion](https://github.com/open-mmlab/Amphion/blob/main/egs/svc/README.md) +- [Training Vocoders with Amphion](https://github.com/open-mmlab/Amphion/blob/main/egs/vocoder/README.md) + +### Catalyst + +- [Distributed training tutorial with Catalyst](https://catalyst-team.github.io/catalyst/tutorials/ddp.html) + +### DALLE2-pytorch + +- [Fine-tuning DALLE2](https://github.com/lucidrains/DALLE2-pytorch#usage) + +### 🤗 diffusers + +- [Performing textual inversion with diffusers](https://github.com/huggingface/diffusers/tree/main/examples/textual_inversion) +- [Training DreamBooth with diffusers](https://github.com/huggingface/diffusers/tree/main/examples/dreambooth) + +### fastai + +- [Distributed training from Jupyter Notebooks with fastai](https://docs.fast.ai/tutorial.distributed.html) +- [Basic distributed training examples with fastai](https://docs.fast.ai/examples/distributed_app_examples.html) + +### GradsFlow + +- [Auto Image Classification with GradsFlow](https://docs.gradsflow.com/en/latest/examples/nbs/01-ImageClassification/) + +### imagen-pytorch + +- [Fine-tuning Imagen](https://github.com/lucidrains/imagen-pytorch#usage) + +### Kornia + +- [Fine-tuning vision models with Kornia's Trainer](https://kornia.readthedocs.io/en/latest/get-started/training.html) + +### PyTorch Accelerated + +- [Quickstart distributed training tutorial with PyTorch Accelerated](https://pytorch-accelerated.readthedocs.io/en/latest/quickstart.html) + +### PyTorch3D + +- [Perform Deep Learning with 3D data](https://pytorch3d.org/tutorials/) + +### Stable-Dreamfusion + +- [Training with Stable-Dreamfusion to convert text to a 3D model](https://colab.research.google.com/drive/1MXT3yfOFvO0ooKEfiUUvTKwUkrrlCHpF?usp=sharing) + +### Tez + +- [Leaf disease detection with Tez and Accelerate](https://www.kaggle.com/code/abhishek/tez-faster-and-easier-training-for-leaf-detection/notebook) + +### trlx + +- [How to implement a sentiment learning task with trlx](https://github.com/CarperAI/trlx#example-how-to-add-a-task) + +### Comfy-UI + +- [Enabling using large Stable Diffusion Models in low-vram settings using Accelerate](https://github.com/comfyanonymous/ComfyUI/blob/master/comfy/model_management.py#L291-L296) + + +## In Science + +Below contains a non-exhaustive list of papers utilizing 🤗 Accelerate. + +> Don't find your paper here? Make a PR to include it! + +* Yuval Kirstain, Adam Polyak, Uriel Singer, Shahbuland Matiana, Joe Penna, Omer Levy: “Pick-a-Pic: An Open Dataset of User Preferences for Text-to-Image Generation”, 2023; [arXiv:2305.01569](http://arxiv.org/abs/2305.01569). +* Lei Wang, Wanyu Xu, Yihuai Lan, Zhiqiang Hu, Yunshi Lan, Roy Ka-Wei Lee, Ee-Peng Lim: “Plan-and-Solve Prompting: Improving Zero-Shot Chain-of-Thought Reasoning by Large Language Models”, 2023; [arXiv:2305.04091](http://arxiv.org/abs/2305.04091). +* Arthur Câmara, Claudia Hauff: “Moving Stuff Around: A study on efficiency of moving documents into memory for Neural IR models”, 2022; [arXiv:2205.08343](http://arxiv.org/abs/2205.08343). +* Ying Sheng, Lianmin Zheng, Binhang Yuan, Zhuohan Li, Max Ryabinin, Daniel Y. Fu, Zhiqiang Xie, Beidi Chen, Clark Barrett, Joseph E. Gonzalez, Percy Liang, Christopher Ré, Ion Stoica, Ce Zhang: “High-throughput Generative Inference of Large Language Models with a Single GPU”, 2023; [arXiv:2303.06865](http://arxiv.org/abs/2303.06865). +* Peter Melchior, Yan Liang, ChangHoon Hahn, Andy Goulding: “Autoencoding Galaxy Spectra I: Architecture”, 2022; [arXiv:2211.07890](http://arxiv.org/abs/2211.07890). +* Jiaao Chen, Aston Zhang, Mu Li, Alex Smola, Diyi Yang: “A Cheaper and Better Diffusion Language Model with Soft-Masked Noise”, 2023; [arXiv:2304.04746](http://arxiv.org/abs/2304.04746). +* Ayaan Haque, Matthew Tancik, Alexei A. Efros, Aleksander Holynski, Angjoo Kanazawa: “Instruct-NeRF2NeRF: Editing 3D Scenes with Instructions”, 2023; [arXiv:2303.12789](http://arxiv.org/abs/2303.12789). +* Luke Melas-Kyriazi, Christian Rupprecht, Iro Laina, Andrea Vedaldi: “RealFusion: 360° Reconstruction of Any Object from a Single Image”, 2023; [arXiv:2302.10663](http://arxiv.org/abs/2302.10663). +* Xiaoshi Wu, Keqiang Sun, Feng Zhu, Rui Zhao, Hongsheng Li: “Better Aligning Text-to-Image Models with Human Preference”, 2023; [arXiv:2303.14420](http://arxiv.org/abs/2303.14420). +* Yongliang Shen, Kaitao Song, Xu Tan, Dongsheng Li, Weiming Lu, Yueting Zhuang: “HuggingGPT: Solving AI Tasks with ChatGPT and its Friends in HuggingFace”, 2023; [arXiv:2303.17580](http://arxiv.org/abs/2303.17580). +* Yue Yang, Wenlin Yao, Hongming Zhang, Xiaoyang Wang, Dong Yu, Jianshu Chen: “Z-LaVI: Zero-Shot Language Solver Fueled by Visual Imagination”, 2022; [arXiv:2210.12261](http://arxiv.org/abs/2210.12261). +* Sheng-Yen Chou, Pin-Yu Chen, Tsung-Yi Ho: “How to Backdoor Diffusion Models?”, 2022; [arXiv:2212.05400](http://arxiv.org/abs/2212.05400). +* Junyoung Seo, Wooseok Jang, Min-Seop Kwak, Jaehoon Ko, Hyeonsu Kim, Junho Kim, Jin-Hwa Kim, Jiyoung Lee, Seungryong Kim: “Let 2D Diffusion Model Know 3D-Consistency for Robust Text-to-3D Generation”, 2023; [arXiv:2303.07937](http://arxiv.org/abs/2303.07937). +* Or Patashnik, Daniel Garibi, Idan Azuri, Hadar Averbuch-Elor, Daniel Cohen-Or: “Localizing Object-level Shape Variations with Text-to-Image Diffusion Models”, 2023; [arXiv:2303.11306](http://arxiv.org/abs/2303.11306). +* Dídac Surís, Sachit Menon, Carl Vondrick: “ViperGPT: Visual Inference via Python Execution for Reasoning”, 2023; [arXiv:2303.08128](http://arxiv.org/abs/2303.08128). +* Chenyang Qi, Xiaodong Cun, Yong Zhang, Chenyang Lei, Xintao Wang, Ying Shan, Qifeng Chen: “FateZero: Fusing Attentions for Zero-shot Text-based Video Editing”, 2023; [arXiv:2303.09535](http://arxiv.org/abs/2303.09535). +* Sean Welleck, Jiacheng Liu, Ximing Lu, Hannaneh Hajishirzi, Yejin Choi: “NaturalProver: Grounded Mathematical Proof Generation with Language Models”, 2022; [arXiv:2205.12910](http://arxiv.org/abs/2205.12910). +* Elad Richardson, Gal Metzer, Yuval Alaluf, Raja Giryes, Daniel Cohen-Or: “TEXTure: Text-Guided Texturing of 3D Shapes”, 2023; [arXiv:2302.01721](http://arxiv.org/abs/2302.01721). +* Puijin Cheng, Li Lin, Yijin Huang, Huaqing He, Wenhan Luo, Xiaoying Tang: “Learning Enhancement From Degradation: A Diffusion Model For Fundus Image Enhancement”, 2023; [arXiv:2303.04603](http://arxiv.org/abs/2303.04603). +* Shun Shao, Yftah Ziser, Shay Cohen: “Erasure of Unaligned Attributes from Neural Representations”, 2023; [arXiv:2302.02997](http://arxiv.org/abs/2302.02997). +* Seonghyeon Ye, Hyeonbin Hwang, Sohee Yang, Hyeongu Yun, Yireun Kim, Minjoon Seo: “In-Context Instruction Learning”, 2023; [arXiv:2302.14691](http://arxiv.org/abs/2302.14691). +* Shikun Liu, Linxi Fan, Edward Johns, Zhiding Yu, Chaowei Xiao, Anima Anandkumar: “Prismer: A Vision-Language Model with An Ensemble of Experts”, 2023; [arXiv:2303.02506](http://arxiv.org/abs/2303.02506). +* Haoyu Chen, Zhihua Wang, Yang Yang, Qilin Sun, Kede Ma: “Learning a Deep Color Difference Metric for Photographic Images”, 2023; [arXiv:2303.14964](http://arxiv.org/abs/2303.14964). +* Van-Hoang Le, Hongyu Zhang: “Log Parsing with Prompt-based Few-shot Learning”, 2023; [arXiv:2302.07435](http://arxiv.org/abs/2302.07435). +* Keito Kudo, Yoichi Aoki, Tatsuki Kuribayashi, Ana Brassard, Masashi Yoshikawa, Keisuke Sakaguchi, Kentaro Inui: “Do Deep Neural Networks Capture Compositionality in Arithmetic Reasoning?”, 2023; [arXiv:2302.07866](http://arxiv.org/abs/2302.07866). +* Ruoyao Wang, Peter Jansen, Marc-Alexandre Côté, Prithviraj Ammanabrolu: “Behavior Cloned Transformers are Neurosymbolic Reasoners”, 2022; [arXiv:2210.07382](http://arxiv.org/abs/2210.07382). +* Martin Wessel, Tomáš Horych, Terry Ruas, Akiko Aizawa, Bela Gipp, Timo Spinde: “Introducing MBIB -- the first Media Bias Identification Benchmark Task and Dataset Collection”, 2023; [arXiv:2304.13148](http://arxiv.org/abs/2304.13148). DOI: [https://dx.doi.org/10.1145/3539618.3591882 10.1145/3539618.3591882]. +* Hila Chefer, Yuval Alaluf, Yael Vinker, Lior Wolf, Daniel Cohen-Or: “Attend-and-Excite: Attention-Based Semantic Guidance for Text-to-Image Diffusion Models”, 2023; [arXiv:2301.13826](http://arxiv.org/abs/2301.13826). +* Marcio Fonseca, Yftah Ziser, Shay B. Cohen: “Factorizing Content and Budget Decisions in Abstractive Summarization of Long Documents”, 2022; [arXiv:2205.12486](http://arxiv.org/abs/2205.12486). +* Elad Richardson, Gal Metzer, Yuval Alaluf, Raja Giryes, Daniel Cohen-Or: “TEXTure: Text-Guided Texturing of 3D Shapes”, 2023; [arXiv:2302.01721](http://arxiv.org/abs/2302.01721). +* Tianxing He, Jingyu Zhang, Tianle Wang, Sachin Kumar, Kyunghyun Cho, James Glass, Yulia Tsvetkov: “On the Blind Spots of Model-Based Evaluation Metrics for Text Generation”, 2022; [arXiv:2212.10020](http://arxiv.org/abs/2212.10020). +* Ori Ram, Yoav Levine, Itay Dalmedigos, Dor Muhlgay, Amnon Shashua, Kevin Leyton-Brown, Yoav Shoham: “In-Context Retrieval-Augmented Language Models”, 2023; [arXiv:2302.00083](http://arxiv.org/abs/2302.00083). +* Dacheng Li, Rulin Shao, Hongyi Wang, Han Guo, Eric P. Xing, Hao Zhang: “MPCFormer: fast, performant and private Transformer inference with MPC”, 2022; [arXiv:2211.01452](http://arxiv.org/abs/2211.01452). +* Baolin Peng, Michel Galley, Pengcheng He, Chris Brockett, Lars Liden, Elnaz Nouri, Zhou Yu, Bill Dolan, Jianfeng Gao: “GODEL: Large-Scale Pre-Training for Goal-Directed Dialog”, 2022; [arXiv:2206.11309](http://arxiv.org/abs/2206.11309). +* Egil Rønningstad, Erik Velldal, Lilja Øvrelid: “Entity-Level Sentiment Analysis (ELSA): An exploratory task survey”, 2023, Proceedings of the 29th International Conference on Computational Linguistics, 2022, pages 6773-6783; [arXiv:2304.14241](http://arxiv.org/abs/2304.14241). +* Charlie Snell, Ilya Kostrikov, Yi Su, Mengjiao Yang, Sergey Levine: “Offline RL for Natural Language Generation with Implicit Language Q Learning”, 2022; [arXiv:2206.11871](http://arxiv.org/abs/2206.11871). +* Zhiruo Wang, Shuyan Zhou, Daniel Fried, Graham Neubig: “Execution-Based Evaluation for Open-Domain Code Generation”, 2022; [arXiv:2212.10481](http://arxiv.org/abs/2212.10481). +* Minh-Long Luu, Zeyi Huang, Eric P. Xing, Yong Jae Lee, Haohan Wang: “Expeditious Saliency-guided Mix-up through Random Gradient Thresholding”, 2022; [arXiv:2212.04875](http://arxiv.org/abs/2212.04875). +* Jun Hao Liew, Hanshu Yan, Daquan Zhou, Jiashi Feng: “MagicMix: Semantic Mixing with Diffusion Models”, 2022; [arXiv:2210.16056](http://arxiv.org/abs/2210.16056). +* Yaqing Wang, Subhabrata Mukherjee, Xiaodong Liu, Jing Gao, Ahmed Hassan Awadallah, Jianfeng Gao: “LiST: Lite Prompted Self-training Makes Parameter-Efficient Few-shot Learners”, 2021; [arXiv:2110.06274](http://arxiv.org/abs/2110.06274). diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/README.md b/tasks/tasksmith-5d12db5414d2/environment/source/examples/README.md new file mode 100644 index 0000000000000000000000000000000000000000..27938cd7f97debc26983a2dfb5044ab23cca8b3f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/README.md @@ -0,0 +1,276 @@ + + +# In this folder we showcase various full examples using 🤗 Accelerate + +## Simple NLP example + +The [nlp_example.py](./nlp_example.py) script is a simple example to train a Bert model on a classification task ([GLUE's MRPC](https://www.microsoft.com/en-us/download/details.aspx?id=52398)). + +Prior to running it you should install 🤗 Dataset and 🤗 Transformers: + +```bash +pip install datasets evaluate transformers +``` + +The same script can be run in any of the following configurations: +- single CPU or single GPU +- multi CPUs +- multi GPUs (using PyTorch distributed mode) +- (multi) TPUs +- fp16 (mixed-precision) or fp32 (normal precision) + +To run it in each of these various modes, use the following commands: +- single CPU: + * from a server without GPU + ```bash + python ./nlp_example.py + ``` + * from any server by passing `cpu=True` to the `Accelerator`. + ```bash + python ./nlp_example.py --cpu + ``` + * from any server with Accelerate launcher + ```bash + accelerate launch --cpu ./nlp_example.py + ``` +- single GPU: + ```bash + python ./nlp_example.py # from a server with a GPU + ``` +- with fp16 (mixed-precision) + * from any server by passing `mixed_precison=fp16` to the `Accelerator`. + ```bash + python ./nlp_example.py --mixed_precision fp16 + ``` + * from any server with Accelerate launcher + ```bash + accelerate launch --mixed_precision fp16 ./nlp_example.py +- multi CPUs (requires Open MPI, Intel MPI, or MVAPICH) + * With Accelerate config and launcher, execute the following from node 0: + ```bash + accelerate config # Select to have accelerate launch mpirun + accelerate launch ./nlp_example.py # This will run the script on each server + ``` + * With Intel MPI: + ```bash + export CCL_WORKER_COUNT=1 + export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip + mpirun -f hostfile -n 16 -ppn 4 python ./nlp_example.py + ``` +- multi GPUs (using PyTorch distributed mode) + * With Accelerate config and launcher + ```bash + accelerate config # This will create a config file on your server + accelerate launch ./nlp_example.py # This will run the script on your server + ``` + * With traditional PyTorch launcher (`python -m torch.distributed.run` can be used instead of `torchrun`) + ```bash + torchrun --nproc_per_node 2 ./nlp_example.py + ``` +- multi GPUs, multi node (several machines, using PyTorch distributed mode) + * With Accelerate config and launcher, on each machine: + ```bash + accelerate config # This will create a config file on each server + accelerate launch ./nlp_example.py # This will run the script on each server + ``` + * With PyTorch launcher only (`python -m torch.distributed.run` can be used instead of `torchrun`). Run this command on each node: + ```bash + torchrun \ # python -m torch.distributed.run + --nproc_per_node 2 \ + --nnodes 2 \ + --rdzv_id 2299 \ # A unique job id + --rdzv_backend c10d \ + --rdzv_endpoint master_node_ip_address:29500 \ + ./nlp_example.py + ``` +- (multi) TPUs + * With Accelerate config and launcher + ```bash + accelerate config # This will create a config file on your TPU server + accelerate launch ./nlp_example.py # This will run the script on each server + ``` + * In PyTorch: + Add an `xmp.spawn` line in your script as you usually do. + + +## Simple vision example + +The [cv_example.py](./cv_example.py) script is a simple example to fine-tune a ResNet-50 on a classification task ([Ofxord-IIT Pet Dataset](https://www.robots.ox.ac.uk/~vgg/data/pets/)). + +The same script can be run in any of the following configurations: +- single CPU or single GPU +- multi CPUs +- multi GPUs (using PyTorch distributed mode) +- (multi) TPUs +- fp16 (mixed-precision) or fp32 (normal precision) + +Prior to running it you should install timm and torchvision: + +```bash +pip install timm torchvision +``` + +and you should download the data with the following commands: + +```bash +wget https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz +tar -xzf images.tar.gz +``` + +To run it in each of these various modes, use the following commands: +- single CPU: + * from a server without GPU + ```bash + python ./cv_example.py --data_dir path_to_data + ``` + * from any server by passing `cpu=True` to the `Accelerator`. + ```bash + python ./cv_example.py --data_dir path_to_data --cpu + ``` + * from any server with Accelerate launcher + ```bash + accelerate launch --cpu ./cv_example.py --data_dir path_to_data + ``` +- single GPU: + ```bash + python ./cv_example.py # from a server with a GPU + ``` +- with fp16 (mixed-precision) + * from any server by passing `mixed_precison=fp16` to the `Accelerator`. + ```bash + python ./cv_example.py --data_dir path_to_data --mixed_precison fp16 + ``` + * from any server with Accelerate launcher + ```bash + accelerate launch --mixed_precison fp16 ./cv_example.py --data_dir path_to_data +- multi CPUs (requires Open MPI, Intel MPI, or MVAPICH) + * With Accelerate config and launcher, run the following from node 0: + ```bash + accelerate config --config_file config.yaml # Select to have accelerate launch mpirun + accelerate launch ./cv_example.py --data_dir path_to_data # This will run the script on each server + ``` + * With Intel MPI, execute mpirun from node 0: + ```bash + export CCL_WORKER_COUNT=1 + export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip + mpirun -f hostfile -n 16 -ppn 4 python ./cv_example.py --data_dir path_to_data + ``` +- multi GPUs (using PyTorch distributed mode) + * With Accelerate config and launcher + ```bash + accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml` + accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on your server + ``` + * With traditional PyTorch launcher (`python -m torch.distributed.run` can be used instead of `torchrun`) + ```bash + torchrun --nproc_per_node 2 ./cv_example.py --data_dir path_to_data + ``` +- multi GPUs, multi node (several machines, using PyTorch distributed mode) + * With Accelerate config and launcher, on each machine: + ```bash + accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml` + accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on each server + ``` + * With PyTorch launcher only (`python -m torch.distributed.run` can be used instead of `torchrun`). Run this command on each node: + ```bash + torchrun \ # python -m torch.distributed.run + --nproc_per_node 2 \ + --nnodes 2 \ + --rdzv_id 2299 \ # A unique job id + --rdzv_backend c10d \ + --rdzv_endpoint master_node_ip_address:29500 \ + ./cv_example.py --data_dir path_to_data + ``` +- (multi) TPUs + * With Accelerate config and launcher + ```bash + accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml` + accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on each server + ``` + * In PyTorch: + Add an `xmp.spawn` line in your script as you usually do. + +### Simple vision example (GANs) + +- [huggan project](https://github.com/huggingface/community-events/tree/main/huggan) + + +### Using AWS SageMaker integration +- [Examples showcasing AWS SageMaker integration of 🤗 Accelerate.](https://github.com/pacman100/accelerate-aws-sagemaker) + +## Configuration zoo +In [/config_yaml_templates](./config_yaml_templates/) we have a variety of *minimal* `config.yaml` templates and examples to help you learn +how to create your own configuration files depending on the scenario. + +## SLURM Scripts +In [/slurm/submit_multigpu.sh](./slurm/submit_multigpu.sh) and [/slurm/submit_multinode.sh](./slurm/submit_multinode.sh) we present two scripts for running the examples on a machine with [SLURM](https://slurm.schedmd.com/documentation.html) workload manager. + +In [/slurm/submit_multigpu.sh](./slurm/submit_multigpu.sh) the only parameter in the launcher that needs to be modified is `--num_processes`, which determines the number of GPUs we will use. In this case, using the environment variable `$SLURM_GPUS`, we indicate that we want to utilize all the GPUs available on the node we have requested. + +In [/slurm/submit_multinode.sh](./slurm/submit_multinode.sh) we must specify the number of nodes that will be part of the training (`--num_machines`), how many GPUs we will use in total (`--num_processes`), the [`backend`](https://pytorch.org/docs/stable/elastic/run.html#note-on-rendezvous-backend), `--main_process_ip` which will be the address the master node and the `--main_process_port`. + +In [/slurm/submit_multicpu.sh](./slurm/submit_multicpu.sh) we must specify the number of nodes that will be part of the training (`--num_machines`), how many CPU processes we will use in total (`--num_processes`), the [`backend`](https://pytorch.org/docs/stable/elastic/run.html#note-on-rendezvous-backend), `--main_process_ip` which will be the address the master node and the `--main_process_port`. `mpirun_hostfile` specifies to run the job using MPIRun. + +In both scripts, we run `activateEnviroment.sh` at the beginning. This script should contain the necessary instructions to initialize the environment for execution. Below, we show an example that loads the necessary libraries ([Environment modules](https://github.com/cea-hpc/modules)), activates the Python environment, and sets up various environment variables, most of them to run the scripts in offline mode in case we don't have internet connection from the cluster. + +```bash +# activateEnvironment.sh +module purge +module load anaconda3/2020.02 cuda/10.2 cudnn/8.0.5 nccl/2.9.9 arrow/7.0.0 openmpi +source activate /home/nct01/nct01328/pytorch_antoni_local + +export HF_HOME=/gpfs/projects/nct01/nct01328/ +export HF_LOCAL_HOME=/gpfs/projects/nct01/nct01328/HF_LOCAL +export HF_DATASETS_OFFLINE=1 +export TRANSFORMERS_OFFLINE=1 +export PYTHONPATH=/home/nct01/nct01328/transformers-in-supercomputers:$PYTHONPATH +export GPUS_PER_NODE=4 +``` + +## Simple Multi-GPU Hardware Launcher (using an external platform) + +[multigpu_remote_launcher.py](./multigpu_remote_launcher.py) is a minimal script that demonstrates launching accelerate +on multiple remote GPUs, and with automatic hardware environment and dependency setup for reproducibility. You can +easily customize the training function used, training arguments, hyperparameters, and type of compute hardware, and then +run the script to automatically launch multi GPU training on remote hardware. + +This script uses [Runhouse](https://github.com/run-house/runhouse) to launch on self-hosted hardware (e.g. in your own +cloud account or on-premise cluster) but there are other options for running remotely as well. Runhouse can be installed +with `pip install runhouse`, and you can refer to +[hardware setup](https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup) +for hardware setup instructions, or this +[Colab tutorial](https://colab.research.google.com/drive/1qVwYyLTCPYPSdz9ZX7BZl9Qm0A3j7RJe) for a more in-depth walkthrough. + +## Finer Examples + +While the first two scripts are extremely barebones when it comes to what you can do with accelerate, more advanced features are documented in two other locations. + +### `by_feature` examples + +These scripts are *individual* examples highlighting one particular feature or use-case within Accelerate. They all stem from the [nlp_example.py](./nlp_example.py) script, and any changes or modifications is denoted with a `# New Code #` comment. + +Read the README.md file located in the `by_feature` folder for more information. + +### `complete_*` examples + +These two scripts contain *every* single feature currently available in Accelerate in one place, as one giant script. + +New arguments that can be passed include: + +- `checkpointing_steps`, whether the various states should be saved at the end of every `n` steps, or `"epoch"` for each epoch. States are then saved to folders named `step_{n}` or `epoch_{n}` +- `resume_from_checkpoint`, should be used if you want to resume training off of a previous call to the script and passed a `checkpointing_steps` to it. +- `with_tracking`, should be used if you want to log the training run using all available experiment trackers in your environment. Currently supported trackers include TensorBoard, Weights and Biases, and CometML. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/README.md b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7b825dd18b3594be13e818c7b895637c3e76b6d2 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/README.md @@ -0,0 +1,121 @@ +# What are these scripts? + +All scripts in this folder originate from the `nlp_example.py` file, as it is a very simplistic NLP training example using Accelerate with zero extra features. + +From there, each further script adds in just **one** feature of Accelerate, showing how you can quickly modify your own scripts to implement these capabilities. + +A full example with all of these parts integrated together can be found in the `complete_nlp_example.py` script and `complete_cv_example.py` script. + +Adjustments to each script from the base `nlp_example.py` file can be found quickly by searching for "# New Code #" + +## Example Scripts by Feature and their Arguments + +### Base Example (`../nlp_example.py`) + +- Shows how to use `Accelerator` in an extremely simplistic PyTorch training loop +- Arguments available: + - `mixed_precision`, whether to use mixed precision. ("no", "fp16", or "bf16") + - `cpu`, whether to train using only the CPU. (yes/no/1/0) + +All following scripts also accept these arguments in addition to their added ones. + +These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torch.distributed.run`), such as: + +```bash +accelerate launch ../nlp_example.py --mixed_precision fp16 --cpu 0 +``` + +### Checkpointing and Resuming Training (`checkpointing.py`) + +- Shows how to use `Accelerator.save_state` and `Accelerator.load_state` to save or continue training +- **It is assumed you are continuing off the same training script** +- Arguments available: + - `checkpointing_steps`, after how many steps the various states should be saved. ("epoch", 1, 2, ...) + - `output_dir`, where saved state folders should be saved to, default is current working directory + - `resume_from_checkpoint`, what checkpoint folder to resume from. ("epoch_0", "step_22", ...) + +These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as: + +(Note, `resume_from_checkpoint` assumes that we've ran the script for one epoch with the `--checkpointing_steps epoch` flag) + +```bash +accelerate launch ./checkpointing.py --checkpointing_steps epoch output_dir "checkpointing_tutorial" --resume_from_checkpoint "checkpointing_tutorial/epoch_0" +``` + +### Cross Validation (`cross_validation.py`) + +- Shows how to use `Accelerator.free_memory` and run cross validation efficiently with `datasets`. +- Arguments available: + - `num_folds`, the number of folds the training dataset should be split into. + +These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as: + +```bash +accelerate launch ./cross_validation.py --num_folds 2 +``` + +### Experiment Tracking (`tracking.py`) + +- Shows how to use `Accelerate.init_trackers` and `Accelerator.log` +- Can be used with Weights and Biases, TensorBoard, or CometML. +- Arguments available: + - `with_tracking`, whether to load in all available experiment trackers from the environment. + +These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as: + +```bash +accelerate launch ./tracking.py --with_tracking +``` + +### Gradient Accumulation (`gradient_accumulation.py`) + +- Shows how to use `Accelerator.no_sync` to prevent gradient averaging in a distributed setup. +- Arguments available: + - `gradient_accumulation_steps`, the number of steps to perform before the gradients are accumulated and the optimizer and scheduler are stepped + zero_grad + +These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as: + +```bash +accelerate launch ./gradient_accumulation.py --gradient_accumulation_steps 5 +``` + +### LocalSGD (`local_sgd.py`) +- Shows how to use `Accelerator.no_sync` to prevent gradient averaging in a distributed setup. However, unlike gradient accumulation, this method does not change the effective batch size. Local SGD can be combined with gradient accumulation. + +These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as: + +```bash +accelerate launch ./local_sgd.py --local_sgd_steps 4 +``` + +### DDP Communication Hook (`ddp_comm_hook.py`) + +- Shows how to use DDP Communication Hooks to control and optimize gradient communication across workers in a DistributedDataParallel setup. +- Arguments available: + - `ddp_comm_hook`, the type of DDP communication hook to use. Choose between `no`, `fp16`, `bf16`, `power_sgd`, and `batched_power_sgd`. + +These arguments should be added at the end of any method for starting the python script (such as `accelerate launch`, `python -m torch.distributed.run`), such as: + +```bash +accelerate launch ./ddp_comm_hook.py --mixed_precision fp16 --ddp_comm_hook power_sgd +``` + +### Profiler (`profiler.py`) + +- Shows how to use the profiling capabilities of `Accelerate` to profile PyTorch models during training. +- Uses the `ProfileKwargs` handler to customize profiling options, including activities, scheduling, and additional profiling options. +- Can generate and save profiling traces in JSON format for visualization in Chrome's tracing tool. + +Arguments available: +- `--record_shapes`: If passed, records shapes for profiling. +- `--profile_memory`: If passed, profiles memory usage. +- `--with_stack`: If passed, profiles stack traces. +- `--with_flops`: If passed, profiles floating point operations (FLOPS). +- `--output_trace_dir`: If specified, saves the profiling trace to the given dir in JSON format. +- `--cpu`: If passed, trains on the CPU instead of GPU. + +These arguments should be added at the end of any method for starting the Python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as: + +```bash +accelerate launch ./profiler.py --record_shapes --profile_memory --with_flops --output_trace_dir "profiler" +``` diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/automatic_gradient_accumulation.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/automatic_gradient_accumulation.py new file mode 100644 index 0000000000000000000000000000000000000000..c610f7704c301d372074b5fcd289e9df4653cf9f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/automatic_gradient_accumulation.py @@ -0,0 +1,243 @@ +# 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. +import argparse +import os + +# New Code # +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator +from accelerate.utils import find_executable_batch_size + + +######################################################################## +# This is a fully working simple example to use Accelerate, +# specifically showcasing how to combine both the gradient accumulation +# and automatic batch size finder utilities of Accelerate to perfrom +# automatic gradient accumulation +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# New additions from the base script can be found quickly by +# looking for the # New Code # tags +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + observed_batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + # New Code # + # We use the `find_executable_batch_size` decorator, passing in the desired observed batch size + # to train on. If a CUDA OOM error occurs, it will retry this loop cutting the batch size in + # half each time. From this, we can calculate the number of gradient accumulation steps needed + # and modify the Accelerator object as a result + @find_executable_batch_size(starting_batch_size=int(observed_batch_size)) + def inner_training_loop(batch_size): + # Since we need to modify the outside accelerator object, we need to bring it + # to the local scope + nonlocal accelerator + + # We can calculate the number of gradient accumulation steps based on the current + # batch size vs the starting batch size + num_gradient_accumulation_steps = observed_batch_size // batch_size + + # And then set it in the Accelerator directly: + accelerator.gradient_accumulation_steps = num_gradient_accumulation_steps + + # Next we need to free all of the stored model references in the Accelerator each time + accelerator.free_memory() + + # And set the seed so our results are reproducable each reset + set_seed(seed) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs), + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # And perform gradient accumulation + with accelerator.accumulate(model): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + + # New Code # + # And call it at the end with no arguments + # Note: You could also refactor this outside of your training loop function + inner_training_loop() + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + # New Code # + # We modify the starting batch size to be an observed batch size of 256, to guarentee an initial CUDA OOM + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 256} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/checkpointing.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..218f4a50914b85d1d29ddfb6e1f0e33246b90be5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/checkpointing.py @@ -0,0 +1,326 @@ +# Copyright 2021 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup + +from accelerate import Accelerator, DataLoaderConfiguration, DistributedType +from accelerate.utils import set_seed + + +######################################################################## +# This is a fully working simple example to use Accelerate, +# specifically showcasing the checkpointing capability, +# and builds off the `nlp_example.py` script. +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To help focus on the differences in the code, building `DataLoaders` +# was refactored into its own function. +# New additions from the base script can be found quickly by +# looking for the # New Code # tags +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # Initialize accelerator + dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader) + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + # New Code # + # Parse out whether we are saving every epoch or after a certain number of batches + if hasattr(args.checkpointing_steps, "isdigit"): + if args.checkpointing_steps == "epoch": + checkpointing_steps = args.checkpointing_steps + elif args.checkpointing_steps.isdigit(): + checkpointing_steps = int(args.checkpointing_steps) + else: + raise ValueError( + f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed." + ) + else: + checkpointing_steps = None + + set_seed(seed) + + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + metric = evaluate.load("glue", "mrpc") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # New Code # + # We need to keep track of how many total steps we have iterated over + overall_step = 0 + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + + # We need to load the checkpoint back in before training here with `load_state` + # The total number of epochs is adjusted based on where the state is being loaded from, + # as we assume continuation of the same training script + if args.resume_from_checkpoint: + if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": + accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}") + accelerator.load_state(args.resume_from_checkpoint) + path = os.path.basename(args.resume_from_checkpoint) + else: + # Get the most recent checkpoint + dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()] + dirs.sort(key=os.path.getctime) + path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last + # Extract `epoch_{i}` or `step_{i}` + training_difference = os.path.splitext(path)[0] + + if "epoch" in training_difference: + starting_epoch = int(training_difference.replace("epoch_", "")) + 1 + resume_step = None + else: + resume_step = int(training_difference.replace("step_", "")) + starting_epoch = resume_step // len(train_dataloader) + resume_step -= starting_epoch * len(train_dataloader) + + # Now we train the model + for epoch in range(starting_epoch, num_epochs): + model.train() + # New Code # + if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: + # We need to skip steps until we reach the resumed step only if we are not using a stateful dataloader + if not args.use_stateful_dataloader: + active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step) + else: + active_dataloader = train_dataloader + overall_step += resume_step + else: + # After the first iteration though, we need to go back to the original dataloader + active_dataloader = train_dataloader + for step, batch in enumerate(active_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + # New Code # + overall_step += 1 + + # New Code # + # We save the model, optimizer, lr_scheduler, and seed states by calling `save_state` + # These are saved to folders named `step_{overall_step}` + # Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl" + # If mixed precision was used, will also save a "scalar.bin" file + if isinstance(checkpointing_steps, int): + output_dir = f"step_{overall_step}" + if overall_step % checkpointing_steps == 0: + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True` (the default). + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + + # New Code # + # We save the model, optimizer, lr_scheduler, and seed states by calling `save_state` + # These are saved to folders named `epoch_{epoch}` + # Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl" + # If mixed precision was used, will also save a "scalar.bin" file + if checkpointing_steps == "epoch": + output_dir = f"epoch_{epoch}" + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + parser.add_argument( + "--checkpointing_steps", + type=str, + default=None, + help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="If the training should continue from a checkpoint folder.", + ) + parser.add_argument( + "--use_stateful_dataloader", + action="store_true", + help="If the dataloader should be a resumable stateful dataloader.", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/cross_validation.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/cross_validation.py new file mode 100644 index 0000000000000000000000000000000000000000..f1caa2672ee479ce84e9747478e1261faf9e83bc --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/cross_validation.py @@ -0,0 +1,281 @@ +# Copyright 2022 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. +import argparse +from typing import List + +import evaluate +import numpy as np +import torch +from datasets import DatasetDict, load_dataset + +# New Code # +# We'll be using StratifiedKFold for this example +from sklearn.model_selection import StratifiedKFold +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType + + +######################################################################## +# This is a fully working simple example to use Accelerate, +# specifically showcasing how to perform Cross Validation, +# and builds off the `nlp_example.py` script. +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To help focus on the differences in the code, building `DataLoaders` +# was refactored into its own function. +# New additions from the base script can be found quickly by +# looking for the # New Code # tags +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + +# New Code # +# We need a different `get_dataloaders` function that will build dataloaders by index + + +def get_fold_dataloaders( + accelerator: Accelerator, dataset: DatasetDict, train_idxs: List[int], valid_idxs: List[int], batch_size: int = 16 +): + """ + Gets a set of train, valid, and test dataloaders for a particular fold + + Args: + accelerator (`Accelerator`): + The main `Accelerator` object + train_idxs (list of `int`): + The split indices for the training dataset + valid_idxs (list of `int`): + The split indices for the validation dataset + batch_size (`int`): + The size of the minibatch. Default is 16 + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = DatasetDict( + { + "train": dataset["train"].select(train_idxs), + "validation": dataset["train"].select(valid_idxs), + "test": dataset["validation"], + } + ) + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + test_dataloader = DataLoader( + tokenized_datasets["test"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader, test_dataloader + + +def training_function(config, args): + # New Code # + test_predictions = [] + # Download the dataset + datasets = load_dataset("glue", "mrpc") + # Create our splits + kfold = StratifiedKFold(n_splits=int(args.num_folds)) + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + set_seed(seed) + + # New Code # + # Create our folds: + folds = kfold.split(np.zeros(datasets["train"].num_rows), datasets["train"]["label"]) + test_references = [] + # Iterate over them + for i, (train_idxs, valid_idxs) in enumerate(folds): + train_dataloader, eval_dataloader, test_dataloader = get_fold_dataloaders( + accelerator, + datasets, + train_idxs, + valid_idxs, + ) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + + # New Code # + # We also run predictions on the test set at the very end + fold_predictions = [] + for step, batch in enumerate(test_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + fold_predictions.append(predictions.cpu()) + if i == 0: + # We need all of the test predictions + test_references.append(references.cpu()) + # Use accelerator.print to print only on the main process. + test_predictions.append(torch.cat(fold_predictions, dim=0)) + # We now need to release all our memory and get rid of the current model, optimizer, etc + model, optimizer = accelerator.free_memory(model, optimizer) + # New Code # + # Finally we check the accuracy of our folded results: + test_references = torch.cat(test_references, dim=0) + preds = torch.stack(test_predictions, dim=0).sum(dim=0).div(int(args.num_folds)).argmax(dim=-1) + test_metric = metric.compute(predictions=preds, references=test_references) + accelerator.print("Average test metrics from all folds:", test_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + # New Code # + parser.add_argument("--num_folds", type=int, default=3, help="The number of splits to perform across the dataset") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/ddp_comm_hook.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/ddp_comm_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..d7028b597939a5e3d4bb2bc4a589de26f53a9da5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/ddp_comm_hook.py @@ -0,0 +1,232 @@ +# Copyright 2021 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils import DDPCommunicationHookType, DistributedDataParallelKwargs + + +######################################################################## +# This is a fully working simple example to use Accelerate +# and perform ddp communication hook +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # New Code # + ddp_comm_hook_type = DDPCommunicationHookType(args.ddp_comm_hook) + ddp_comm_wrapper = DDPCommunicationHookType(args.ddp_comm_wrapper) + ddp_kwargs = DistributedDataParallelKwargs(comm_hook=ddp_comm_hook_type, comm_wrapper=ddp_comm_wrapper) + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, kwargs_handlers=[ddp_kwargs]) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs), + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + # We use the new `accumulate` context manager to perform gradient accumulation + with accelerator.accumulate(model): + output = model(**batch) + loss = output.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + # New Code # + parser.add_argument( + "--ddp_comm_hook", + type=str, + default="no", + choices=["no", "fp16", "bf16", "power_sgd", "batched_power_sgd"], + help="DDP Communication hook to use. Choose between `no`, `fp16`, `bf16`, `power_sgd`, and `batched_power_sgd`.", + ) + # New Code # + parser.add_argument( + "--ddp_comm_wrapper", + type=str, + default="no", + choices=["no", "fp16", "bf16"], + help="DDP Communication wrapper to use. Choose between `no`, `fp16`, and `bf16`.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/deepspeed_with_config_support.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/deepspeed_with_config_support.py new file mode 100644 index 0000000000000000000000000000000000000000..ff7535761af689cfe1d83153f1226245f422c4cf --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/deepspeed_with_config_support.py @@ -0,0 +1,723 @@ +#!/usr/bin/env python +# Copyright 2022 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. +""" +Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) +on a text file or a dataset without using HuggingFace Trainer. + +Here is the full list of checkpoints on the hub that can be fine-tuned by this script: +https://huggingface.co/models?filter=text-generation +""" +# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments. + +import argparse +import json +import logging +import math +import os +import random +from itertools import chain +from pathlib import Path + +import datasets +import torch +import transformers +from datasets import load_dataset +from huggingface_hub import HfApi +from torch.utils.data import DataLoader +from tqdm.auto import tqdm +from transformers import ( + CONFIG_MAPPING, + MODEL_MAPPING, + AutoConfig, + AutoModelForCausalLM, + AutoTokenizer, + SchedulerType, + default_data_collator, + get_scheduler, +) +from transformers.utils.versions import require_version + +from accelerate import Accelerator, DistributedType +from accelerate.logging import get_logger +from accelerate.utils import DummyOptim, DummyScheduler, set_seed + + +logger = get_logger(__name__) + +require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt") + +MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys()) +MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task") + parser.add_argument( + "--dataset_name", + type=str, + default=None, + help="The name of the dataset to use (via the datasets library).", + ) + parser.add_argument( + "--dataset_config_name", + type=str, + default=None, + help="The configuration name of the dataset to use (via the datasets library).", + ) + parser.add_argument( + "--train_file", type=str, default=None, help="A csv or a json file containing the training data." + ) + parser.add_argument( + "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data." + ) + parser.add_argument( + "--validation_split_percentage", + default=5, + help="The percentage of the train set used as validation set in case there's no validation split", + ) + parser.add_argument( + "--model_name_or_path", + type=str, + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--config_name", + type=str, + default=None, + help="Pretrained config name or path if not the same as model_name", + ) + parser.add_argument( + "--tokenizer_name", + type=str, + default=None, + help="Pretrained tokenizer name or path if not the same as model_name", + ) + parser.add_argument( + "--use_slow_tokenizer", + action="store_true", + help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).", + ) + parser.add_argument( + "--per_device_train_batch_size", + type=int, + default=8, + help="Batch size (per device) for the training dataloader.", + ) + parser.add_argument( + "--per_device_eval_batch_size", + type=int, + default=8, + help="Batch size (per device) for the evaluation dataloader.", + ) + parser.add_argument( + "--learning_rate", + type=float, + default=5e-5, + help="Initial learning rate (after the potential warmup period) to use.", + ) + parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.") + parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.") + parser.add_argument( + "--max_train_steps", + type=int, + default=None, + help="Total number of training steps to perform. If provided, overrides num_train_epochs.", + ) + parser.add_argument( + "--gradient_accumulation_steps", + type=int, + default=1, + help="Number of updates steps to accumulate before performing a backward/update pass.", + ) + parser.add_argument( + "--lr_scheduler_type", + type=SchedulerType, + default="linear", + help="The scheduler type to use.", + choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"], + ) + parser.add_argument( + "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler." + ) + parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.") + parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") + parser.add_argument( + "--model_type", + type=str, + default=None, + help="Model type to use if training from scratch.", + choices=MODEL_TYPES, + ) + parser.add_argument( + "--block_size", + type=int, + default=None, + help=( + "Optional input sequence length after tokenization. The training dataset will be truncated in block of" + " this size for training. Default to the model max input length for single sentence inputs (take into" + " account special tokens)." + ), + ) + parser.add_argument( + "--preprocessing_num_workers", + type=int, + default=None, + help="The number of processes to use for the preprocessing.", + ) + parser.add_argument( + "--overwrite_cache", type=bool, default=False, help="Overwrite the cached training and evaluation sets" + ) + parser.add_argument( + "--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files." + ) + parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.") + parser.add_argument( + "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`." + ) + parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.") + parser.add_argument( + "--checkpointing_steps", + type=str, + default=None, + help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="If the training should continue from a checkpoint folder.", + ) + # New Code # + # Whether to load the best model at the end of training + parser.add_argument( + "--load_best_model", + action="store_true", + help="Whether to load the best model at the end of training", + ) + parser.add_argument( + "--with_tracking", + action="store_true", + help="Whether to enable experiment trackers for logging.", + ) + parser.add_argument( + "--report_to", + type=str, + default="all", + help=( + 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,' + ' `"wandb"`, `"comet_ml"`, and `"dvclive"`. Use `"all"` (default) to report to all integrations.' + "Only applicable when `--with_tracking` is passed." + ), + ) + args = parser.parse_args() + + # Sanity checks + if args.dataset_name is None and args.train_file is None and args.validation_file is None: + raise ValueError("Need either a dataset name or a training/validation file.") + else: + if args.train_file is not None: + extension = args.train_file.split(".")[-1] + assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file." + if args.validation_file is not None: + extension = args.validation_file.split(".")[-1] + assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file." + + if args.push_to_hub: + assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed." + + return args + + +# New Code # +def evaluate(args, model, eval_dataloader, accelerator, eval_dataset): + model.eval() + losses = [] + for step, batch in enumerate(eval_dataloader): + with torch.no_grad(): + outputs = model(**batch) + + loss = outputs.loss + losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size))) + + losses = torch.cat(losses) + try: + eval_loss = torch.mean(losses) + perplexity = math.exp(eval_loss) + except OverflowError: + perplexity = float("inf") + return perplexity, eval_loss + + +def main(): + args = parse_args() + + # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. + # If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers + # in the environment + + # when using DeepSpeed, the `gradient_accumulation_steps` is properly set from the DeepSpeed plugin/config + # or from `accelerate launch` via `--gradient_accumulation_steps` else + # defaulting to the passed `args.gradient_accumulation_steps` + accelerator = ( + Accelerator( + log_with=args.report_to, + project_dir=args.output_dir, + gradient_accumulation_steps=args.gradient_accumulation_steps, + ) + if args.with_tracking + else Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps) + ) + + # Make one log on every process with the configuration for debugging. + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + level=logging.INFO, + ) + logger.info(accelerator.state, main_process_only=False) + if accelerator.is_local_main_process: + datasets.utils.logging.set_verbosity_warning() + transformers.utils.logging.set_verbosity_info() + else: + datasets.utils.logging.set_verbosity_error() + transformers.utils.logging.set_verbosity_error() + + # If passed along, set the training seed now. + if args.seed is not None: + set_seed(args.seed) + + # Handle the repository creation + if accelerator.is_main_process: + if args.push_to_hub: + api = HfApi(token=args.hub_token) + + # Create repo (repo_name from args or inferred) + repo_name = args.hub_model_id + if repo_name is None: + repo_name = Path(args.output_dir).absolute().name + repo_id = api.create_repo(repo_name, exist_ok=True).repo_id + + with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore: + if "step_*" not in gitignore: + gitignore.write("step_*\n") + if "epoch_*" not in gitignore: + gitignore.write("epoch_*\n") + elif args.output_dir is not None: + os.makedirs(args.output_dir, exist_ok=True) + accelerator.wait_for_everyone() + + # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) + # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ + # (the dataset will be downloaded automatically from the datasets Hub). + # + # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called + # 'text' is found. You can easily tweak this behavior (see below). + # + # In distributed training, the load_dataset function guarantee that only one local process can concurrently + # download the dataset. + if args.dataset_name is not None: + # Downloading and loading a dataset from the hub. + raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name) + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + args.dataset_name, + args.dataset_config_name, + split=f"train[:{args.validation_split_percentage}%]", + ) + raw_datasets["train"] = load_dataset( + args.dataset_name, + args.dataset_config_name, + split=f"train[{args.validation_split_percentage}%:]", + ) + else: + data_files = {} + dataset_args = {} + if args.train_file is not None: + data_files["train"] = args.train_file + if args.validation_file is not None: + data_files["validation"] = args.validation_file + extension = args.train_file.split(".")[-1] + if extension == "txt": + extension = "text" + dataset_args["keep_linebreaks"] = not args.no_keep_linebreaks + raw_datasets = load_dataset(extension, data_files=data_files, **dataset_args) + # If no validation data is there, validation_split_percentage will be used to divide the dataset. + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + extension, + data_files=data_files, + split=f"train[:{args.validation_split_percentage}%]", + **dataset_args, + ) + raw_datasets["train"] = load_dataset( + extension, + data_files=data_files, + split=f"train[{args.validation_split_percentage}%:]", + **dataset_args, + ) + + # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at + # https://huggingface.co/docs/datasets/loading_datasets.html. + + # Load pretrained model and tokenizer + # + # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently + # download model & vocab. + if args.config_name: + config = AutoConfig.from_pretrained(args.config_name) + elif args.model_name_or_path: + config = AutoConfig.from_pretrained(args.model_name_or_path) + else: + config = CONFIG_MAPPING[args.model_type]() + logger.warning("You are instantiating a new config instance from scratch.") + + if args.tokenizer_name: + tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer) + elif args.model_name_or_path: + tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer) + else: + raise ValueError( + "You are instantiating a new tokenizer from scratch. This is not supported by this script." + "You can do it from another script, save it, and load it from here, using --tokenizer_name." + ) + + if args.model_name_or_path: + model = AutoModelForCausalLM.from_pretrained( + args.model_name_or_path, + from_tf=bool(".ckpt" in args.model_name_or_path), + config=config, + ) + else: + logger.info("Training new model from scratch") + model = AutoModelForCausalLM.from_config(config) + + model.resize_token_embeddings(len(tokenizer)) + + # Preprocessing the datasets. + # First we tokenize all the texts. + column_names = raw_datasets["train"].column_names + text_column_name = "text" if "text" in column_names else column_names[0] + + def tokenize_function(examples): + return tokenizer(examples[text_column_name]) + + with accelerator.main_process_first(): + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + num_proc=args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not args.overwrite_cache, + desc="Running tokenizer on dataset", + ) + + if args.block_size is None: + block_size = tokenizer.model_max_length + if block_size > 1024: + logger.warning( + f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). " + "Picking 1024 instead. You can change that default value by passing --block_size xxx." + ) + block_size = 1024 + else: + if args.block_size > tokenizer.model_max_length: + logger.warning( + f"The block_size passed ({args.block_size}) is larger than the maximum length for the model" + f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." + ) + block_size = min(args.block_size, tokenizer.model_max_length) + + # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. + def group_texts(examples): + # Concatenate all texts. + concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} + total_length = len(concatenated_examples[list(examples.keys())[0]]) + # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can + # customize this part to your needs. + if total_length >= block_size: + total_length = (total_length // block_size) * block_size + # Split by chunks of max_len. + result = { + k: [t[i : i + block_size] for i in range(0, total_length, block_size)] + for k, t in concatenated_examples.items() + } + result["labels"] = result["input_ids"].copy() + return result + + # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder + # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower + # to preprocess. + # + # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: + # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map + + with accelerator.main_process_first(): + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + num_proc=args.preprocessing_num_workers, + load_from_cache_file=not args.overwrite_cache, + desc=f"Grouping texts in chunks of {block_size}", + ) + + train_dataset = lm_datasets["train"] + eval_dataset = lm_datasets["validation"] + + # Log a few random samples from the training set: + for index in random.sample(range(len(train_dataset)), 3): + logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") + + # DataLoaders creation: + train_dataloader = DataLoader( + train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=args.per_device_train_batch_size + ) + eval_dataloader = DataLoader( + eval_dataset, collate_fn=default_data_collator, batch_size=args.per_device_eval_batch_size + ) + + # Optimizer + # Split weights in two groups, one with weight decay and the other not. + no_decay = ["bias", "LayerNorm.weight"] + optimizer_grouped_parameters = [ + { + "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], + "weight_decay": args.weight_decay, + }, + { + "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + ] + # New Code # + # Creates Dummy Optimizer if `optimizer` was specified in the config file else creates Adam Optimizer + optimizer_cls = ( + torch.optim.AdamW + if accelerator.state.deepspeed_plugin is None + or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config + else DummyOptim + ) + optimizer = optimizer_cls(optimizer_grouped_parameters, lr=args.learning_rate) + + # On TPU, the tie weights in our model have been disconnected, so we need to restore the ties. + if accelerator.distributed_type == DistributedType.XLA: + model.tie_weights() + + # Scheduler and math around the number of training steps. + num_update_steps_per_epoch = math.ceil(len(train_dataloader) / accelerator.gradient_accumulation_steps) + overrode_max_train_steps = False + if args.max_train_steps is None: + args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch + overrode_max_train_steps = True + else: + args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) + + # New Code # + # Creates Dummy Scheduler if `scheduler` was specified in the config file else creates `args.lr_scheduler_type` Scheduler + if ( + accelerator.state.deepspeed_plugin is None + or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config + ): + lr_scheduler = get_scheduler( + name=args.lr_scheduler_type, + optimizer=optimizer, + num_warmup_steps=args.num_warmup_steps, + num_training_steps=args.max_train_steps, + ) + else: + lr_scheduler = DummyScheduler( + optimizer, total_num_steps=args.max_train_steps, warmup_num_steps=args.num_warmup_steps + ) + + # Prepare everything with our `accelerator`. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # We need to recalculate our total training steps as the size of the training dataloader may have changed. + num_update_steps_per_epoch = math.ceil(len(train_dataloader) / accelerator.gradient_accumulation_steps) + if overrode_max_train_steps: + args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch + # Afterwards we recalculate our number of training epochs + args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) + + # Figure out how many steps we should save the Accelerator states + checkpointing_steps = args.checkpointing_steps + if checkpointing_steps is not None and checkpointing_steps.isdigit(): + checkpointing_steps = int(checkpointing_steps) + + # We need to initialize the trackers we use, and also store our configuration. + # The trackers initializes automatically on the main process. + if args.with_tracking: + experiment_config = vars(args) + # TensorBoard cannot log Enums, need the raw value + experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value + accelerator.init_trackers("clm_no_trainer", experiment_config) + + # Train! + total_batch_size = ( + args.per_device_train_batch_size * accelerator.num_processes * accelerator.gradient_accumulation_steps + ) + + logger.info("***** Running training *****") + logger.info(f" Num examples = {len(train_dataset)}") + logger.info(f" Num Epochs = {args.num_train_epochs}") + logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") + logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") + logger.info(f" Gradient Accumulation steps = {accelerator.gradient_accumulation_steps}") + logger.info(f" Total optimization steps = {args.max_train_steps}") + # Only show the progress bar once on each machine. + progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) + completed_steps = 0 + starting_epoch = 0 + best_metric = None + best_metric_checkpoint = None + + # Potentially load in the weights and states from a previous save + if args.resume_from_checkpoint: + accelerator.load_state(args.resume_from_checkpoint) + accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}") + path = os.path.basename(args.resume_from_checkpoint) + training_difference = os.path.splitext(path)[0] + + if "epoch" in training_difference: + starting_epoch = int(training_difference.replace("epoch_", "")) + 1 + resume_step = None + completed_steps = starting_epoch * num_update_steps_per_epoch + else: + resume_step = int(training_difference.replace("step_", "")) + starting_epoch = resume_step // num_update_steps_per_epoch + resume_step -= starting_epoch * num_update_steps_per_epoch + completed_steps = resume_step + + # update progress bar if resumed from checkpoint + progress_bar.update(completed_steps) + + for epoch in range(starting_epoch, args.num_train_epochs): + model.train() + if args.with_tracking: + total_loss = 0 + + # skip new `skip_first_batches` to skip the batches when resuming from ckpt + if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: + # We need to skip steps until we reach the resumed step + active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step) + else: + # After the first iteration though, we need to go back to the original dataloader + active_dataloader = train_dataloader + for step, batch in enumerate(active_dataloader): + # In particular, DeepSpeed handles `gradient_accumulation` via `DeepSpeedEngine`. + # Below, we use `accelerator.accumulate` if the user + # wants to switch to other approaches such as plain DDP, PyTorch FSDP ... + # This avoids having to change any code as things are all handled across different distributed setups. + with accelerator.accumulate(model): + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + if accelerator.sync_gradients: + progress_bar.update(1) + completed_steps += 1 + + # We keep track of the loss at each epoch + if args.with_tracking: + step_loss = accelerator.reduce(loss.detach().clone()).item() + total_loss += step_loss + + if isinstance(checkpointing_steps, int): + if completed_steps % checkpointing_steps == 0: + output_dir = f"step_{completed_steps}" + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + if completed_steps >= args.max_train_steps: + break + + perplexity, eval_loss = evaluate(args, model, eval_dataloader, accelerator, eval_dataset) + logger.info(f"epoch {epoch}: perplexity: {perplexity} eval_loss: {eval_loss}") + + if args.with_tracking: + accelerator.log( + { + "perplexity": perplexity, + "eval_loss": eval_loss, + "train_loss": total_loss / len(train_dataloader), + "epoch": epoch, + "step": completed_steps, + }, + step=completed_steps, + ) + + if isinstance(checkpointing_steps, str) and checkpointing_steps == "epoch": + accelerator.save_state(os.path.join(args.output_dir, f"epoch_{epoch}")) + + # New Code # + # Tracks the best checkpoint and best metric + if best_metric is None or best_metric > perplexity: + best_metric = perplexity + best_metric_checkpoint = os.path.join(args.output_dir, "best_checkpoint") + accelerator.save_state(best_metric_checkpoint) + accelerator.print(f"New best metric: {best_metric} at epoch {epoch}") + accelerator.print(f"best_metric_checkpoint: {best_metric_checkpoint}") + + # New Code # + # Loads the best checkpoint after the training is finished + if args.load_best_model: + accelerator.load_state(best_metric_checkpoint) + + # New Code # + # Evaluates using the best checkpoint + perplexity, eval_loss = evaluate(args, model, eval_dataloader, accelerator, eval_dataset) + logger.info(f"Best model metrics: perplexity: {perplexity} eval_loss: {eval_loss}") + if perplexity != best_metric: + raise AssertionError( + f"Best metric {best_metric} does not match the metric {perplexity} of the loaded best model." + ) + + if args.output_dir is not None: + accelerator.wait_for_everyone() + unwrapped_model = accelerator.unwrap_model(model) + + # New Code # + # Saves the whole/unpartitioned fp16 model when in ZeRO Stage-3 to the output directory if + # `stage3_gather_16bit_weights_on_model_save` is True in DeepSpeed Config file or + # `zero3_save_16bit_model` is True in DeepSpeed Plugin. + # For Zero Stages 1 and 2, models are saved as usual in the output directory. + # The model name saved is `pytorch_model.bin` + unwrapped_model.save_pretrained( + args.output_dir, + is_main_process=accelerator.is_main_process, + save_function=accelerator.save, + state_dict=accelerator.get_state_dict(model), + ) + if accelerator.is_main_process: + tokenizer.save_pretrained(args.output_dir) + if args.push_to_hub: + api.upload_folder( + repo_id=repo_id, + folder_path=args.output_dir, + commit_message="End of training", + ) + + with open(os.path.join(args.output_dir, "all_results.json"), "w") as f: + json.dump({"perplexity": perplexity, "eval_loss": eval_loss.item()}, f) + accelerator.end_training() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/early_stopping.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/early_stopping.py new file mode 100644 index 0000000000000000000000000000000000000000..12e087d891fad40d3ce0515e226c39e561d19f55 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/early_stopping.py @@ -0,0 +1,246 @@ +# Copyright 2021 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. +import argparse + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType + + +######################################################################## +# This is a fully working simple example to use Accelerate +# specifically showcasing how to perform early stopping, +# and builds off the `nlp_example.py` script +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], + shuffle=False, + collate_fn=collate_fn, + batch_size=EVAL_BATCH_SIZE, + drop_last=(accelerator.mixed_precision == "fp8"), + ) + + return train_dataloader, eval_dataloader + + +# New code +class EarlyStoppingCallback: + "A callback class that helps with early stopping" + + def __init__(self, min_delta=0, patience=5): + self.min_delta = min_delta + self.patience = patience + self.counter = 0 + self.lowest_loss = float("inf") + + def check_early_stopping(self, eval_loss): + delta = self.lowest_loss - eval_loss + if delta >= self.min_delta: + self.lowest_loss = eval_loss + self.counter = 0 + else: + self.counter += 1 + if self.counter >= self.patience: + return True + return False + + +callback = EarlyStoppingCallback() + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + # New code + # Check if we should stop the training on any processes + if callback.check_early_stopping(loss.item()): + accelerator.set_trigger() + + # If so, we break the loop + if accelerator.check_trigger(): + break + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/fsdp_with_peak_mem_tracking.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/fsdp_with_peak_mem_tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd3fec55d5a4ea77c16168329a3d29f769fe1ed --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/fsdp_with_peak_mem_tracking.py @@ -0,0 +1,458 @@ +# Copyright 2021 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. +import argparse +import gc +import os +import threading + +import evaluate +import psutil +import torch +from datasets import load_dataset +from torch.distributed.fsdp.fully_sharded_data_parallel import FullOptimStateDictConfig, FullStateDictConfig +from torch.utils.data import DataLoader +from transformers import ( + AutoModelForSequenceClassification, + AutoTokenizer, + get_linear_schedule_with_warmup, + set_seed, +) + +from accelerate import Accelerator, DistributedType, FullyShardedDataParallelPlugin +from accelerate.utils import is_npu_available, is_xpu_available + + +######################################################################## +# This is a fully working simple example to use Accelerate +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# - FSDP +# +# This example also demonstrates the checkpointing and sharding capabilities +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +# New Code # +# Converting Bytes to Megabytes +def b2mb(x): + return int(x / 2**20) + + +# New Code # +# This context manager is used to track the peak memory usage of the process +class TorchTracemalloc: + def __enter__(self): + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.cuda.memory_allocated() + elif is_xpu_available(): + torch.xpu.empty_cache() + torch.xpu.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.xpu.memory_allocated() + elif is_npu_available(): + torch.npu.empty_cache() + torch.npu.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.npu.memory_allocated() + self.process = psutil.Process() + + self.cpu_begin = self.cpu_mem_used() + self.peak_monitoring = True + peak_monitor_thread = threading.Thread(target=self.peak_monitor_func) + peak_monitor_thread.daemon = True + peak_monitor_thread.start() + return self + + def cpu_mem_used(self): + """get resident set size memory for the current process""" + return self.process.memory_info().rss + + def peak_monitor_func(self): + self.cpu_peak = -1 + + while True: + self.cpu_peak = max(self.cpu_mem_used(), self.cpu_peak) + + # can't sleep or will not catch the peak right (this comment is here on purpose) + # time.sleep(0.001) # 1msec + + if not self.peak_monitoring: + break + + def __exit__(self, *exc): + self.peak_monitoring = False + + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + self.end = torch.cuda.memory_allocated() + self.peak = torch.cuda.max_memory_allocated() + elif is_xpu_available(): + torch.xpu.empty_cache() + self.end = torch.xpu.memory_allocated() + self.peak = torch.xpu.max_memory_allocated() + elif is_npu_available(): + torch.npu.empty_cache() + self.end = torch.npu.memory_allocated() + self.peak = torch.npu.max_memory_allocated() + self.used = b2mb(self.end - self.begin) + self.peaked = b2mb(self.peak - self.begin) + + self.cpu_end = self.cpu_mem_used() + self.cpu_used = b2mb(self.cpu_end - self.cpu_begin) + self.cpu_peaked = b2mb(self.cpu_peak - self.cpu_begin) + # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + + # New Code # + # Pass the advanced FSDP settings not part of the accelerate config by creating fsdp_plugin + fsdp_plugin = FullyShardedDataParallelPlugin( + state_dict_config=FullStateDictConfig(offload_to_cpu=False, rank0_only=False), + optim_state_dict_config=FullOptimStateDictConfig(offload_to_cpu=False, rank0_only=False), + ) + + # Initialize accelerator + if args.with_tracking: + accelerator = Accelerator( + cpu=args.cpu, + mixed_precision=args.mixed_precision, + log_with="wandb", + project_dir=args.logging_dir, + fsdp_plugin=fsdp_plugin, + ) + else: + accelerator = Accelerator(fsdp_plugin=fsdp_plugin) + accelerator.print(accelerator.distributed_type) + + if hasattr(args.checkpointing_steps, "isdigit"): + if args.checkpointing_steps == "epoch": + checkpointing_steps = args.checkpointing_steps + elif args.checkpointing_steps.isdigit(): + checkpointing_steps = int(args.checkpointing_steps) + else: + raise ValueError( + f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed." + ) + else: + checkpointing_steps = None + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + # We need to initialize the trackers we use, and also store our configuration + if args.with_tracking: + experiment_config = vars(args) + accelerator.init_trackers("fsdp_glue_no_trainer", experiment_config) + + tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path) + datasets = load_dataset("glue", "mrpc") + metric = evaluate.load("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + set_seed(seed) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained( + args.model_name_or_path, return_dict=True, low_cpu_mem_usage=True + ) + + no_decay = ["bias", "LayerNorm.weight"] + optimizer_grouped_parameters = [ + { + "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], + "weight_decay": 0.003, + }, + { + "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + ] + + optimizer = torch.optim.AdamW(params=optimizer_grouped_parameters, lr=lr, weight_decay=2e-4) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=10, + num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, + ) + + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + overall_step = 0 + + # Potentially load in the weights and states from a previous save + if args.resume_from_checkpoint: + if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": + accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}") + accelerator.load_state(args.resume_from_checkpoint) + path = os.path.basename(args.resume_from_checkpoint) + else: + # Get the most recent checkpoint + dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()] + dirs.sort(key=os.path.getctime) + path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last + # Extract `epoch_{i}` or `step_{i}` + training_difference = os.path.splitext(path)[0] + + if "epoch" in training_difference: + num_epochs -= int(training_difference.replace("epoch_", "")) + resume_step = None + else: + resume_step = int(training_difference.replace("step_", "")) + num_epochs -= resume_step // len(train_dataloader) + # If resuming by step, we also need to know exactly how far into the DataLoader we went + resume_step = (num_epochs * len(train_dataloader)) - resume_step + + # Now we train the model + for epoch in range(num_epochs): + # New Code # + # context manager to track the peak memory usage during the training epoch + with TorchTracemalloc() as tracemalloc: + model.train() + if args.with_tracking: + total_loss = 0 + for step, batch in enumerate(train_dataloader): + # We need to skip steps until we reach the resumed step + if args.resume_from_checkpoint and epoch == 0: + if resume_step is not None and step < resume_step: + pass + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + # We keep track of the loss at each epoch + if args.with_tracking: + total_loss += loss.detach().float() + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + # accelerator.print(lr_scheduler.get_lr()) + + overall_step += 1 + + if isinstance(checkpointing_steps, int): + output_dir = f"step_{overall_step}" + if overall_step % checkpointing_steps == 0: + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + # New Code # + # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage + accelerator.print(f"Memory before entering the train : {b2mb(tracemalloc.begin)}") + accelerator.print(f"Memory consumed at the end of the train (end-begin): {tracemalloc.used}") + accelerator.print(f"Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}") + accelerator.print( + f"Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}" + ) + # Logging the peak memory usage of the GPU to the tracker + if args.with_tracking: + accelerator.log( + { + "train_total_peak_memory": tracemalloc.peaked + b2mb(tracemalloc.begin), + }, + step=epoch, + ) + + # New Code # + # context manager to track the peak memory usage during the evaluation + with TorchTracemalloc() as tracemalloc: + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + if args.with_tracking: + accelerator.log( + { + "accuracy": eval_metric["accuracy"], + "f1": eval_metric["f1"], + "train_loss": total_loss.item() / len(train_dataloader), + }, + step=epoch, + ) + + if checkpointing_steps == "epoch": + output_dir = f"epoch_{epoch}" + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + # New Code # + # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage + accelerator.print(f"Memory before entering the eval : {b2mb(tracemalloc.begin)}") + accelerator.print(f"Memory consumed at the end of the eval (end-begin): {tracemalloc.used}") + accelerator.print(f"Peak Memory consumed during the eval (max-begin): {tracemalloc.peaked}") + accelerator.print( + f"Total Peak Memory consumed during the eval (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}" + ) + # Logging the peak memory usage of the GPU to the tracker + if args.with_tracking: + accelerator.log( + { + "eval_total_peak_memory": tracemalloc.peaked + b2mb(tracemalloc.begin), + }, + step=epoch, + ) + + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + parser.add_argument( + "--checkpointing_steps", + type=str, + default=None, + help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="If the training should continue from a checkpoint folder.", + ) + parser.add_argument( + "--with_tracking", + action="store_true", + help="Whether to load in all available experiment trackers from the environment and use them for logging.", + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--logging_dir", + type=str, + default="logs", + help="Location on where to store experiment tracking logs`", + ) + parser.add_argument( + "--model_name_or_path", + type=str, + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=True, + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/gradient_accumulation.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/gradient_accumulation.py new file mode 100644 index 0000000000000000000000000000000000000000..d277bd7d8bb7345a5024e044655ed2569ff6f174 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/gradient_accumulation.py @@ -0,0 +1,228 @@ +# Copyright 2021 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType + + +######################################################################## +# This is a fully working simple example to use Accelerate +# and perform gradient accumulation +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # New Code # + gradient_accumulation_steps = int(args.gradient_accumulation_steps) + # Initialize accelerator + accelerator = Accelerator( + cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps + ) + if accelerator.distributed_type == DistributedType.XLA and gradient_accumulation_steps > 1: + raise NotImplementedError( + "Gradient accumulation on TPUs is currently not supported. Pass `gradient_accumulation_steps=1`" + ) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs), + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + # New code # + # We use the new `accumulate` context manager to perform gradient accumulation + # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. + with accelerator.accumulate(model): + output = model(**batch) + loss = output.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + # New Code # + parser.add_argument( + "--gradient_accumulation_steps", + type=int, + default=1, + help="The number of minibatches to be ran before gradients are accumulated.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/local_sgd.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/local_sgd.py new file mode 100644 index 0000000000000000000000000000000000000000..cdcf950af190fa71b403836f1a7ec2f0d6a8e3ec --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/local_sgd.py @@ -0,0 +1,236 @@ +# Copyright 2023 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.local_sgd import LocalSGD + + +######################################################################## +# This is a fully working simple example to use Accelerate +# with LocalSGD, which is a method to synchronize model +# parameters every K batches. It is different, but complementary +# to gradient accumulation. +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # New Code # + gradient_accumulation_steps = int(args.gradient_accumulation_steps) + local_sgd_steps = int(args.local_sgd_steps) + # Initialize accelerator + accelerator = Accelerator( + cpu=args.cpu, mixed_precision=args.mixed_precision, gradient_accumulation_steps=gradient_accumulation_steps + ) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs), + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + with LocalSGD( + accelerator=accelerator, model=model, local_sgd_steps=local_sgd_steps, enabled=local_sgd_steps is not None + ) as local_sgd: + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + # New code # + # We use the new `accumulate` context manager to perform gradient accumulation + # We also currently do not support TPUs nor advise it as bugs were found on the XLA side when running our tests. + with accelerator.accumulate(model): + output = model(**batch) + loss = output.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + # LocalSGD-specific line + local_sgd.step() + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + # New Code # + parser.add_argument( + "--gradient_accumulation_steps", + type=int, + default=1, + help="The number of minibatches to be ran before gradients are accumulated.", + ) + parser.add_argument( + "--local_sgd_steps", type=int, default=8, help="Number of local SGD steps or None to disable local SGD" + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/megatron_lm_gpt_pretraining.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/megatron_lm_gpt_pretraining.py new file mode 100644 index 0000000000000000000000000000000000000000..18488ec41e2a08612ccabb9155001584ba4894de --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/megatron_lm_gpt_pretraining.py @@ -0,0 +1,710 @@ +#!/usr/bin/env python +# Copyright 2021 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. +""" +Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...) +on a text file or a dataset without using HuggingFace Trainer. + +Here is the full list of checkpoints on the hub that can be fine-tuned by this script: +https://huggingface.co/models?filter=text-generation +""" +# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments. + +import argparse +import json +import logging +import math +import os +import random +from itertools import chain +from pathlib import Path + +import datasets +import torch +import transformers +from datasets import load_dataset +from huggingface_hub import HfApi +from torch.utils.data import DataLoader +from tqdm.auto import tqdm +from transformers import ( + CONFIG_MAPPING, + MODEL_MAPPING, + AutoConfig, + AutoModelForCausalLM, + AutoTokenizer, + SchedulerType, + default_data_collator, + get_scheduler, +) +from transformers.utils import check_min_version, send_example_telemetry +from transformers.utils.versions import require_version + +from accelerate import Accelerator, DistributedType +from accelerate.logging import get_logger +from accelerate.utils import MegatronLMDummyScheduler, set_seed + + +# Will error if the minimal version of Transformers is not installed. Remove at your own risks. +check_min_version("4.23.0.dev0") + +logger = get_logger(__name__) + +require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt") + +MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys()) +MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES) + + +def parse_args(): + parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task") + parser.add_argument( + "--dataset_name", + type=str, + default=None, + help="The name of the dataset to use (via the datasets library).", + ) + parser.add_argument( + "--dataset_config_name", + type=str, + default=None, + help="The configuration name of the dataset to use (via the datasets library).", + ) + parser.add_argument( + "--train_file", type=str, default=None, help="A csv or a json file containing the training data." + ) + parser.add_argument( + "--validation_file", type=str, default=None, help="A csv or a json file containing the validation data." + ) + parser.add_argument( + "--validation_split_percentage", + default=5, + help="The percentage of the train set used as validation set in case there's no validation split", + ) + parser.add_argument( + "--model_name_or_path", + type=str, + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--config_name", + type=str, + default=None, + help="Pretrained config name or path if not the same as model_name", + ) + parser.add_argument( + "--tokenizer_name", + type=str, + default=None, + help="Pretrained tokenizer name or path if not the same as model_name", + ) + parser.add_argument( + "--use_slow_tokenizer", + action="store_true", + help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).", + ) + parser.add_argument( + "--per_device_train_batch_size", + type=int, + default=8, + help="Batch size (per device) for the training dataloader.", + ) + parser.add_argument( + "--per_device_eval_batch_size", + type=int, + default=8, + help="Batch size (per device) for the evaluation dataloader.", + ) + parser.add_argument( + "--learning_rate", + type=float, + default=5e-5, + help="Initial learning rate (after the potential warmup period) to use.", + ) + parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.") + parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.") + parser.add_argument( + "--max_train_steps", + type=int, + default=None, + help="Total number of training steps to perform. If provided, overrides num_train_epochs.", + ) + parser.add_argument( + "--gradient_accumulation_steps", + type=int, + default=1, + help="Number of updates steps to accumulate before performing a backward/update pass.", + ) + parser.add_argument( + "--lr_scheduler_type", + type=SchedulerType, + default="linear", + help="The scheduler type to use.", + choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"], + ) + parser.add_argument( + "--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler." + ) + parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.") + parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.") + parser.add_argument( + "--model_type", + type=str, + default=None, + help="Model type to use if training from scratch.", + choices=MODEL_TYPES, + ) + parser.add_argument( + "--block_size", + type=int, + default=None, + help=( + "Optional input sequence length after tokenization. The training dataset will be truncated in block of" + " this size for training. Default to the model max input length for single sentence inputs (take into" + " account special tokens)." + ), + ) + parser.add_argument( + "--preprocessing_num_workers", + type=int, + default=None, + help="The number of processes to use for the preprocessing.", + ) + parser.add_argument( + "--overwrite_cache", action="store_true", help="Overwrite the cached training and evaluation sets" + ) + parser.add_argument( + "--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files." + ) + parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.") + parser.add_argument( + "--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`." + ) + parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.") + parser.add_argument( + "--checkpointing_steps", + type=str, + default=None, + help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="If the training should continue from a checkpoint folder.", + ) + parser.add_argument( + "--with_tracking", + action="store_true", + help="Whether to enable experiment trackers for logging.", + ) + parser.add_argument( + "--report_to", + type=str, + default="all", + help=( + 'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,' + ' `"wandb"`, `"comet_ml"`, and `"dvclive"`. Use `"all"` (default) to report to all integrations.' + "Only applicable when `--with_tracking` is passed." + ), + ) + args = parser.parse_args() + + # Sanity checks + if args.dataset_name is None and args.train_file is None and args.validation_file is None: + raise ValueError("Need either a dataset name or a training/validation file.") + else: + if args.train_file is not None: + extension = args.train_file.split(".")[-1] + assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file." + if args.validation_file is not None: + extension = args.validation_file.split(".")[-1] + assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file." + + if args.push_to_hub: + assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed." + + return args + + +def main(): + args = parse_args() + + # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The + # information sent is the one passed as arguments along with your Python/PyTorch versions. + send_example_telemetry("run_clm_no_trainer", args) + + # Initialize the accelerator. We will let the accelerator handle device placement for us in this example. + # If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers + # in the environment + accelerator_log_kwargs = {} + + if args.with_tracking: + accelerator_log_kwargs["log_with"] = args.report_to + accelerator_log_kwargs["logging_dir"] = args.output_dir + + accelerator = Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps, **accelerator_log_kwargs) + + # Make one log on every process with the configuration for debugging. + logging.basicConfig( + format="%(asctime)s - %(levelname)s - %(name)s - %(message)s", + datefmt="%m/%d/%Y %H:%M:%S", + level=logging.INFO, + ) + logger.info(accelerator.state, main_process_only=False) + if accelerator.is_local_main_process: + datasets.utils.logging.set_verbosity_warning() + transformers.utils.logging.set_verbosity_info() + else: + datasets.utils.logging.set_verbosity_error() + transformers.utils.logging.set_verbosity_error() + + # If passed along, set the training seed now. + if args.seed is not None: + set_seed(args.seed) + + # Handle the repository creation + if accelerator.is_main_process: + if args.push_to_hub: + api = HfApi(token=args.hub_token) + + # Create repo (repo_name from args or inferred) + repo_name = args.hub_model_id + if repo_name is None: + repo_name = Path(args.output_dir).absolute().name + repo_id = api.create_repo(repo_name, exist_ok=True).repo_id + + with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore: + if "step_*" not in gitignore: + gitignore.write("step_*\n") + if "epoch_*" not in gitignore: + gitignore.write("epoch_*\n") + elif args.output_dir is not None: + os.makedirs(args.output_dir, exist_ok=True) + accelerator.wait_for_everyone() + + # Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below) + # or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/ + # (the dataset will be downloaded automatically from the datasets Hub). + # + # For CSV/JSON files, this script will use the column called 'text' or the first column if no column called + # 'text' is found. You can easily tweak this behavior (see below). + # + # In distributed training, the load_dataset function guarantee that only one local process can concurrently + # download the dataset. + if args.dataset_name is not None: + # Downloading and loading a dataset from the hub. + raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name) + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + args.dataset_name, + args.dataset_config_name, + split=f"train[:{args.validation_split_percentage}%]", + ) + raw_datasets["train"] = load_dataset( + args.dataset_name, + args.dataset_config_name, + split=f"train[{args.validation_split_percentage}%:]", + ) + else: + data_files = {} + dataset_args = {} + if args.train_file is not None: + data_files["train"] = args.train_file + if args.validation_file is not None: + data_files["validation"] = args.validation_file + extension = args.train_file.split(".")[-1] + if extension == "txt": + extension = "text" + dataset_args["keep_linebreaks"] = not args.no_keep_linebreaks + raw_datasets = load_dataset(extension, data_files=data_files, **dataset_args) + # If no validation data is there, validation_split_percentage will be used to divide the dataset. + if "validation" not in raw_datasets.keys(): + raw_datasets["validation"] = load_dataset( + extension, + data_files=data_files, + split=f"train[:{args.validation_split_percentage}%]", + **dataset_args, + ) + raw_datasets["train"] = load_dataset( + extension, + data_files=data_files, + split=f"train[{args.validation_split_percentage}%:]", + **dataset_args, + ) + + # See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at + # https://huggingface.co/docs/datasets/loading_datasets.html. + + # Load pretrained model and tokenizer + # + # In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently + # download model & vocab. + if args.config_name: + config = AutoConfig.from_pretrained(args.config_name) + elif args.model_name_or_path: + config = AutoConfig.from_pretrained(args.model_name_or_path) + else: + config = CONFIG_MAPPING[args.model_type]() + logger.warning("You are instantiating a new config instance from scratch.") + + if args.tokenizer_name: + tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer) + elif args.model_name_or_path: + tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer) + else: + raise ValueError( + "You are instantiating a new tokenizer from scratch. This is not supported by this script." + "You can do it from another script, save it, and load it from here, using --tokenizer_name." + ) + + if args.model_name_or_path: + model = AutoModelForCausalLM.from_pretrained( + args.model_name_or_path, + from_tf=bool(".ckpt" in args.model_name_or_path), + config=config, + ) + else: + logger.info("Training new model from scratch") + model = AutoModelForCausalLM.from_config(config) + + model.resize_token_embeddings(len(tokenizer)) + + # Preprocessing the datasets. + # First we tokenize all the texts. + column_names = raw_datasets["train"].column_names + text_column_name = "text" if "text" in column_names else column_names[0] + + def tokenize_function(examples): + return tokenizer(examples[text_column_name]) + + with accelerator.main_process_first(): + tokenized_datasets = raw_datasets.map( + tokenize_function, + batched=True, + num_proc=args.preprocessing_num_workers, + remove_columns=column_names, + load_from_cache_file=not args.overwrite_cache, + desc="Running tokenizer on dataset", + ) + + if args.block_size is None: + block_size = tokenizer.model_max_length + if block_size > 1024: + logger.warning( + f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). " + "Picking 1024 instead. You can change that default value by passing --block_size xxx." + ) + block_size = 1024 + else: + if args.block_size > tokenizer.model_max_length: + logger.warning( + f"The block_size passed ({args.block_size}) is larger than the maximum length for the model" + f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}." + ) + block_size = min(args.block_size, tokenizer.model_max_length) + + # Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size. + def group_texts(examples): + # Concatenate all texts. + concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()} + total_length = len(concatenated_examples[list(examples.keys())[0]]) + # We drop the small remainder, we could add padding if the model supported it instead of this drop, you can + # customize this part to your needs. + if total_length >= block_size: + total_length = (total_length // block_size) * block_size + # Split by chunks of max_len. + result = { + k: [t[i : i + block_size] for i in range(0, total_length, block_size)] + for k, t in concatenated_examples.items() + } + result["labels"] = result["input_ids"].copy() + return result + + # Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder + # for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower + # to preprocess. + # + # To speed up this part, we use multiprocessing. See the documentation of the map method for more information: + # https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map + + with accelerator.main_process_first(): + lm_datasets = tokenized_datasets.map( + group_texts, + batched=True, + num_proc=args.preprocessing_num_workers, + load_from_cache_file=not args.overwrite_cache, + desc=f"Grouping texts in chunks of {block_size}", + ) + + train_dataset = lm_datasets["train"] + eval_dataset = lm_datasets["validation"] + + # Log a few random samples from the training set: + for index in random.sample(range(len(train_dataset)), 3): + logger.info(f"Sample {index} of the training set: {train_dataset[index]}.") + + # DataLoaders creation: + train_dataloader = DataLoader( + train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=args.per_device_train_batch_size + ) + eval_dataloader = DataLoader( + eval_dataset, collate_fn=default_data_collator, batch_size=args.per_device_eval_batch_size + ) + + # Optimizer + # Split weights in two groups, one with weight decay and the other not. + no_decay = ["bias", "layer_norm.weight"] + optimizer_grouped_parameters = [ + { + "params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], + "weight_decay": args.weight_decay, + }, + { + "params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], + "weight_decay": 0.0, + }, + ] + optimizer = torch.optim.AdamW(optimizer_grouped_parameters, lr=args.learning_rate) + + # Scheduler and math around the number of training steps. + overrode_max_train_steps = False + num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) + if args.max_train_steps is None: + args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch + overrode_max_train_steps = True + + # New Code + # For Megatron-LM, we need to use `MegatronLMDummyScheduler` instead of regular schedulers + if accelerator.distributed_type == DistributedType.MEGATRON_LM: + lr_scheduler = MegatronLMDummyScheduler( + optimizer=optimizer, + total_num_steps=args.max_train_steps, + warmup_num_steps=args.num_warmup_steps, + ) + else: + lr_scheduler = get_scheduler( + name=args.lr_scheduler_type, + optimizer=optimizer, + num_warmup_steps=args.num_warmup_steps * args.gradient_accumulation_steps, + num_training_steps=args.max_train_steps * args.gradient_accumulation_steps, + ) + + # Prepare everything with our `accelerator`. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # On TPU, the tie weights in our model have been disconnected, so we need to restore the ties. + if accelerator.distributed_type == DistributedType.XLA: + model.tie_weights() + + # We need to recalculate our total training steps as the size of the training dataloader may have changed. + num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps) + if overrode_max_train_steps: + args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch + # Afterwards we recalculate our number of training epochs + args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch) + + # Figure out how many steps we should save the Accelerator states + checkpointing_steps = args.checkpointing_steps + if checkpointing_steps is not None and checkpointing_steps.isdigit(): + checkpointing_steps = int(checkpointing_steps) + + # We need to initialize the trackers we use, and also store our configuration. + # The trackers initializes automatically on the main process. + if args.with_tracking: + experiment_config = vars(args) + # TensorBoard cannot log Enums, need the raw value + experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value + accelerator.init_trackers("clm_no_trainer", experiment_config) + + # Train! + # New Code + # For Megatron-LM, we need to get `global_batch_size` from megatron_lm_plugin + # as it handles the specifics related to data parallelism, tensor model parallelism and pipeline parallelism + if accelerator.distributed_type == DistributedType.MEGATRON_LM: + total_batch_size = accelerator.state.megatron_lm_plugin.global_batch_size + else: + total_batch_size = ( + args.per_device_train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps + ) + + logger.info("***** Running training *****") + logger.info(f" Num examples = {len(train_dataset)}") + logger.info(f" Num Epochs = {args.num_train_epochs}") + logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}") + logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}") + logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}") + logger.info(f" Total optimization steps = {args.max_train_steps}") + # Only show the progress bar once on each machine. + progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) + completed_steps = 0 + starting_epoch = 0 + + # Potentially load in the weights and states from a previous save + if args.resume_from_checkpoint: + if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": + accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}") + accelerator.load_state(args.resume_from_checkpoint) + path = os.path.basename(args.resume_from_checkpoint) + else: + # Get the most recent checkpoint + dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()] + dirs.sort(key=os.path.getctime) + path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last + # Extract `epoch_{i}` or `step_{i}` + training_difference = os.path.splitext(path)[0] + + if "epoch" in training_difference: + starting_epoch = int(training_difference.replace("epoch_", "")) + 1 + resume_step = None + else: + # need to multiply `gradient_accumulation_steps` to reflect real steps + resume_step = int(training_difference.replace("step_", "")) * args.gradient_accumulation_steps + starting_epoch = resume_step // len(train_dataloader) + resume_step -= starting_epoch * len(train_dataloader) + + # update the progress_bar if load from checkpoint + progress_bar.update(starting_epoch * num_update_steps_per_epoch) + completed_steps = starting_epoch * num_update_steps_per_epoch + + for epoch in range(starting_epoch, args.num_train_epochs): + model.train() + if args.with_tracking: + total_loss = 0 + for step, batch in enumerate(train_dataloader): + # We need to skip steps until we reach the resumed step + if args.resume_from_checkpoint and epoch == starting_epoch: + if resume_step is not None and step < resume_step: + if step % args.gradient_accumulation_steps == 0: + progress_bar.update(1) + completed_steps += 1 + continue + + with accelerator.accumulate(model): + outputs = model(**batch) + loss = outputs.loss + # We keep track of the loss at each epoch + if args.with_tracking: + total_loss += loss.detach().float() + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + # Checks if the accelerator has performed an optimization step behind the scenes + if accelerator.sync_gradients: + progress_bar.update(1) + completed_steps += 1 + + if isinstance(checkpointing_steps, int): + if completed_steps % checkpointing_steps == 0: + output_dir = f"step_{completed_steps }" + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + if completed_steps >= args.max_train_steps: + break + + model.eval() + losses = [] + for step, batch in enumerate(eval_dataloader): + with torch.no_grad(): + outputs = model(**batch) + + loss = outputs.loss + # New Code + # For Megatron-LM, the losses are already averaged across the data parallel group + if accelerator.distributed_type == DistributedType.MEGATRON_LM: + losses.append(loss) + else: + losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size))) + try: + if accelerator.distributed_type == DistributedType.MEGATRON_LM: + losses = torch.tensor(losses) + else: + losses = torch.cat(losses) + eval_loss = torch.mean(losses) + perplexity = math.exp(eval_loss) + except OverflowError: + perplexity = float("inf") + + logger.info(f"epoch {epoch}: perplexity: {perplexity} eval_loss: {eval_loss}") + + if args.with_tracking: + accelerator.log( + { + "perplexity": perplexity, + "eval_loss": eval_loss, + "train_loss": total_loss.item() / len(train_dataloader), + "epoch": epoch, + "step": completed_steps, + }, + step=completed_steps, + ) + + if args.push_to_hub and epoch < args.num_train_epochs - 1: + accelerator.wait_for_everyone() + unwrapped_model = accelerator.unwrap_model(model) + unwrapped_model.save_pretrained( + args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save + ) + if accelerator.is_main_process: + tokenizer.save_pretrained(args.output_dir) + api.upload_folder( + repo_id=repo_id, + folder_path=args.output_dir, + commit_message=f"Training in progress epoch {epoch}", + run_as_future=True, + ) + + if args.checkpointing_steps == "epoch": + output_dir = f"epoch_{epoch}" + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + + # this is causing some issue with Megatron-LM when using `wandb` at the end of the main function. + # Everything works fine inspite of commenting this out. (wandb finishes/closes the run without error) + # if args.with_tracking: + # accelerator.end_training() + + if args.output_dir is not None: + accelerator.wait_for_everyone() + # New Code + # For Megatron-LM, we need to save the model using `accelerator.save_state` + if accelerator.distributed_type == DistributedType.MEGATRON_LM: + accelerator.save_state(args.output_dir) + else: + unwrapped_model = accelerator.unwrap_model(model) + unwrapped_model.save_pretrained( + args.output_dir, is_main_process=accelerator.is_main_process, save_function=accelerator.save + ) + if accelerator.is_main_process: + tokenizer.save_pretrained(args.output_dir) + if args.push_to_hub: + api.upload_folder( + repo_id=repo_id, + folder_path=args.output_dir, + commit_message="End of training", + ) + + with open(os.path.join(args.output_dir, "all_results.json"), "w") as f: + json.dump({"perplexity": perplexity}, f) + accelerator.end_training() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/memory.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..847135e426eed5f87d5bc853cc80a98c255a3984 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/memory.py @@ -0,0 +1,234 @@ +# 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. +import argparse +import os + +# New Code # +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils import find_executable_batch_size + + +######################################################################## +# This is a fully working simple example to use Accelerate, +# specifically showcasing how to ensure out-of-memory errors never +# interrupt training, and builds off the `nlp_example.py` script. +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# New additions from the base script can be found quickly by +# looking for the # New Code # tags +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + # New Code # + # We now can define an inner training loop function. It should take a batch size as the only parameter, + # and build the dataloaders in there. + # It also gets our decorator + @find_executable_batch_size(starting_batch_size=batch_size) + def inner_training_loop(batch_size): + # And now just move everything below under this function + # We need to bring in the Accelerator object from earlier + nonlocal accelerator + # And reset all of its attributes that could hold onto any memory: + accelerator.free_memory() + + # Then we can declare the model, optimizer, and everything else: + set_seed(seed) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs), + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + + # New Code # + # And call it at the end with no arguments + # Note: You could also refactor this outside of your training loop function + inner_training_loop() + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/multi_process_metrics.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/multi_process_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..626781ac81184ffe42ed9d2f7fd952fe1207a4f7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/multi_process_metrics.py @@ -0,0 +1,238 @@ +# Copyright 2022 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType + + +######################################################################## +# This is a fully working simple example to use Accelerate, +# specifically showcasing how to properly calculate the metrics on the +# validation dataset when in a distributed system, and builds off the +# `nlp_example.py` script. +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To help focus on the differences in the code, building `DataLoaders` +# was refactored into its own function. +# New additions from the base script can be found quickly by +# looking for the # New Code # tags +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + samples_seen = 0 + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather((predictions, batch["labels"])) + # New Code # + # First we check if it's a distributed system + if accelerator.use_distributed: + # Then see if we're on the last batch of our eval dataloader + if step == len(eval_dataloader) - 1: + # Last batch needs to be truncated on distributed systems as it contains additional samples + predictions = predictions[: len(eval_dataloader.dataset) - samples_seen] + references = references[: len(eval_dataloader.dataset) - samples_seen] + else: + # Otherwise we add the number of samples seen + samples_seen += references.shape[0] + # All of this can be avoided if you use `Accelerator.gather_for_metrics` instead of `Accelerator.gather`: + # accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/profiler.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/profiler.py new file mode 100644 index 0000000000000000000000000000000000000000..cc1843acdd3a0b81f9a90488c662268bff5c969b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/profiler.py @@ -0,0 +1,255 @@ +# Copyright 2024 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils import ProfileKwargs + + +######################################################################## +# This is a fully working simple example to use Accelerate +# and perform profiling +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # New Code # + profile_kwargs = ProfileKwargs( + record_shapes=args.record_shapes, + profile_memory=args.profile_memory, + with_flops=args.with_flops, + output_trace_dir=args.output_trace_dir, + ) + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, kwargs_handlers=[profile_kwargs]) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs), + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + # New Code # + with accelerator.profile() as prof: + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + # We use the new `accumulate` context manager to perform gradient accumulation + with accelerator.accumulate(model): + output = model(**batch) + loss = output.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + # New Code # + accelerator.print( + prof.key_averages().table( + sort_by="self_cpu_time_total" if args.cpu else "self_cuda_time_total", row_limit=-1 + ) + ) + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + # New Code # + parser.add_argument( + "--record_shapes", + action="store_true", + default=False, + help="If passed, will record shapes for profiling.", + ) + # New Code # + parser.add_argument( + "--profile_memory", + action="store_true", + default=False, + help="If passed, will profile memory.", + ) + # New Code # + parser.add_argument( + "--with_flops", + action="store_true", + default=False, + help="If passed, will profile flops.", + ) + # New Code # + parser.add_argument( + "--output_trace_dir", + type=str, + default=None, + help="If passed, will save a json trace to the specified path.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/schedule_free.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/schedule_free.py new file mode 100644 index 0000000000000000000000000000000000000000..e9cf11702c8bd6b668ee40c307259099e3ca4f76 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/schedule_free.py @@ -0,0 +1,226 @@ +# Copyright 2024 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils import is_schedulefree_available + + +if is_schedulefree_available(): + import schedulefree +else: + raise ImportError( + "This example requires the `schedulefree` library. Please install it with `pip install schedulefree`" + ) + + +######################################################################## +# This is a fully working simple example to use Accelerate and Facebook's +# scheduler-free optimizer: https://github.com/facebookresearch/schedule_free/ +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # For Torchxla, it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], + shuffle=False, + collate_fn=collate_fn, + batch_size=EVAL_BATCH_SIZE, + drop_last=(accelerator.mixed_precision == "fp8"), + ) + + return train_dataloader, eval_dataloader + + +# For testing only + + +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + # Instantiate optimizer with warmup steps + optimizer = schedulefree.AdamWScheduleFree( + model.parameters(), + lr=lr, + warmup_steps=100, + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + + model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + optimizer.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + optimizer.zero_grad() + + model.eval() + optimizer.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/tracking.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..c97c5517b3527b994111d498cd4c81a30ec3e763 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/by_feature/tracking.py @@ -0,0 +1,271 @@ +# Copyright 2021 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType + + +######################################################################## +# This is a fully working simple example to use Accelerate, +# specifically showcasing the experiment tracking capability, +# and builds off the `nlp_example.py` script. +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To help focus on the differences in the code, building `DataLoaders` +# was refactored into its own function. +# New additions from the base script can be found quickly by +# looking for the # New Code # tags +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +# For testing only +if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + from accelerate.test_utils.training import mocked_dataloaders + + get_dataloaders = mocked_dataloaders # noqa: F811 + + +def training_function(config, args): + # For testing only + if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1": + config["num_epochs"] = 2 + # Initialize Accelerator + + # New Code # + # We pass in "all" to `log_with` to grab all available trackers in the environment + # Note: If using a custom `Tracker` class, should be passed in here such as: + # >>> log_with = ["all", MyCustomTrackerClassInstance()] + if args.with_tracking: + accelerator = Accelerator( + cpu=args.cpu, mixed_precision=args.mixed_precision, log_with="all", project_dir=args.project_dir + ) + else: + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + set_seed(seed) + + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + metric = evaluate.load("glue", "mrpc") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # New Code # + # We need to initialize the trackers we use. Overall configurations can also be stored + if args.with_tracking: + run = os.path.split(__file__)[-1].split(".")[0] + accelerator.init_trackers(run, config) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + # New Code # + # For our tracking example, we will log the total loss of each epoch + if args.with_tracking: + total_loss = 0 + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + # New Code # + if args.with_tracking: + total_loss += loss.detach().float() + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True` (the default). + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + + # New Code # + # To actually log, we call `Accelerator.log` + # The values passed can be of `str`, `int`, `float` or `dict` of `str` to `float`/`int` + if args.with_tracking: + accelerator.log( + { + "accuracy": eval_metric["accuracy"], + "f1": eval_metric["f1"], + "train_loss": total_loss.item() / len(train_dataloader), + "epoch": epoch, + }, + step=epoch, + ) + + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + parser.add_argument( + "--with_tracking", + action="store_true", + help="Whether to load in all available experiment trackers from the environment and use them for logging.", + ) + parser.add_argument( + "--project_dir", + type=str, + default="logs", + help="Location on where to store experiment tracking logs` and relevent project information", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/complete_cv_example.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/complete_cv_example.py new file mode 100644 index 0000000000000000000000000000000000000000..9fa9fceb853fb08ccc567fb6be434f69e95375ee --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/complete_cv_example.py @@ -0,0 +1,329 @@ +# Copyright 2021 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. +import argparse +import os +import re + +import numpy as np +import PIL +import torch +from timm import create_model +from torch.optim.lr_scheduler import OneCycleLR +from torch.utils.data import DataLoader, Dataset +from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor + +from accelerate import Accelerator, DataLoaderConfiguration + + +######################################################################## +# This is a fully working simple example to use Accelerate +# +# This example trains a ResNet50 on the Oxford-IIT Pet Dataset +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +# Function to get the label from the filename +def extract_label(fname): + stem = fname.split(os.path.sep)[-1] + return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0] + + +class PetsDataset(Dataset): + def __init__(self, file_names, image_transform=None, label_to_id=None): + self.file_names = file_names + self.image_transform = image_transform + self.label_to_id = label_to_id + + def __len__(self): + return len(self.file_names) + + def __getitem__(self, idx): + fname = self.file_names[idx] + raw_image = PIL.Image.open(fname) + image = raw_image.convert("RGB") + if self.image_transform is not None: + image = self.image_transform(image) + label = extract_label(fname) + if self.label_to_id is not None: + label = self.label_to_id[label] + return {"image": image, "label": label} + + +def training_function(config, args): + # Initialize accelerator + dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader) + if args.with_tracking: + accelerator = Accelerator( + cpu=args.cpu, + mixed_precision=args.mixed_precision, + log_with="all", + project_dir=args.project_dir, + dataloader_config=dataloader_config, + ) + else: + accelerator = Accelerator( + cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config + ) + + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + image_size = config["image_size"] + if not isinstance(image_size, (list, tuple)): + image_size = (image_size, image_size) + + # Parse out whether we are saving every epoch or after a certain number of batches + if hasattr(args.checkpointing_steps, "isdigit"): + if args.checkpointing_steps == "epoch": + checkpointing_steps = args.checkpointing_steps + elif args.checkpointing_steps.isdigit(): + checkpointing_steps = int(args.checkpointing_steps) + else: + raise ValueError( + f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed." + ) + else: + checkpointing_steps = None + + # We need to initialize the trackers we use, and also store our configuration + if args.with_tracking: + run = os.path.split(__file__)[-1].split(".")[0] + accelerator.init_trackers(run, config) + + # Grab all the image filenames + file_names = [os.path.join(args.data_dir, fname) for fname in os.listdir(args.data_dir) if fname.endswith(".jpg")] + + # Build the label correspondences + all_labels = [extract_label(fname) for fname in file_names] + id_to_label = list(set(all_labels)) + id_to_label.sort() + label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)} + + # Set the seed before splitting the data. + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + # Split our filenames between train and validation + random_perm = np.random.permutation(len(file_names)) + cut = int(0.8 * len(file_names)) + train_split = random_perm[:cut] + eval_split = random_perm[cut:] + + # For training we use a simple RandomResizedCrop + train_tfm = Compose([RandomResizedCrop(image_size, scale=(0.5, 1.0)), ToTensor()]) + train_dataset = PetsDataset( + [file_names[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id + ) + + # For evaluation, we use a deterministic Resize + eval_tfm = Compose([Resize(image_size), ToTensor()]) + eval_dataset = PetsDataset([file_names[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id) + + # Instantiate dataloaders. + train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4) + eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size, num_workers=4) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Freezing the base model + for param in model.parameters(): + param.requires_grad = False + for param in model.get_classifier().parameters(): + param.requires_grad = True + + # We normalize the batches of images to be a bit faster. + mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None].to(accelerator.device) + std = torch.tensor(model.default_cfg["std"])[None, :, None, None].to(accelerator.device) + + # Instantiate optimizer + optimizer = torch.optim.Adam(params=model.parameters(), lr=lr / 25) + + # Instantiate learning rate scheduler + lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=lr, epochs=num_epochs, steps_per_epoch=len(train_dataloader)) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + # We need to keep track of how many total steps we have iterated over + overall_step = 0 + # We also need to keep track of the starting epoch so files are named properly + starting_epoch = 0 + + # Potentially load in the weights and states from a previous save + if args.resume_from_checkpoint: + if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": + accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}") + accelerator.load_state(args.resume_from_checkpoint) + path = os.path.basename(args.resume_from_checkpoint) + else: + # Get the most recent checkpoint + dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()] + dirs.sort(key=os.path.getctime) + path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last + # Extract `epoch_{i}` or `step_{i}` + training_difference = os.path.splitext(path)[0] + + if "epoch" in training_difference: + starting_epoch = int(training_difference.replace("epoch_", "")) + 1 + resume_step = None + else: + resume_step = int(training_difference.replace("step_", "")) + starting_epoch = resume_step // len(train_dataloader) + resume_step -= starting_epoch * len(train_dataloader) + + # Now we train the model + for epoch in range(starting_epoch, num_epochs): + model.train() + if args.with_tracking: + total_loss = 0 + if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: + # We need to skip steps until we reach the resumed step + active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step) + overall_step += resume_step + else: + # After the first iteration though, we need to go back to the original dataloader + active_dataloader = train_dataloader + for batch in active_dataloader: + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch = {k: v.to(accelerator.device) for k, v in batch.items()} + inputs = (batch["image"] - mean) / std + outputs = model(inputs) + loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) + # We keep track of the loss at each epoch + if args.with_tracking: + total_loss += loss.detach().float() + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + overall_step += 1 + if isinstance(checkpointing_steps, int): + output_dir = f"step_{overall_step}" + if overall_step % checkpointing_steps == 0: + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + model.eval() + accurate = 0 + num_elems = 0 + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch = {k: v.to(accelerator.device) for k, v in batch.items()} + inputs = (batch["image"] - mean) / std + with torch.no_grad(): + outputs = model(inputs) + predictions = outputs.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["label"])) + accurate_preds = predictions == references + num_elems += accurate_preds.shape[0] + accurate += accurate_preds.long().sum() + + eval_metric = accurate.item() / num_elems + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") + if args.with_tracking: + accelerator.log( + { + "accuracy": 100 * eval_metric, + "train_loss": total_loss.item() / len(train_dataloader), + "epoch": epoch, + }, + step=overall_step, + ) + if checkpointing_steps == "epoch": + output_dir = f"epoch_{epoch}" + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument("--data_dir", required=True, help="The data folder on disk.") + parser.add_argument("--fp16", action="store_true", help="If passed, will use FP16 training.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + parser.add_argument( + "--checkpointing_steps", + type=str, + default=None, + help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="If the training should continue from a checkpoint folder.", + ) + parser.add_argument( + "--use_stateful_dataloader", + action="store_true", + help="If the dataloader should be a resumable stateful dataloader.", + ) + parser.add_argument( + "--with_tracking", + action="store_true", + help="Whether to load in all available experiment trackers from the environment and use them for logging.", + ) + parser.add_argument( + "--project_dir", + type=str, + default="logs", + help="Location on where to store experiment tracking logs` and relevent project information", + ) + args = parser.parse_args() + config = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/complete_nlp_example.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/complete_nlp_example.py new file mode 100644 index 0000000000000000000000000000000000000000..a692cb7b773bcedb06d1e70707a55898ffb43c03 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/complete_nlp_example.py @@ -0,0 +1,324 @@ +# Copyright 2021 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. +import argparse +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DataLoaderConfiguration, DistributedType + + +######################################################################## +# This is a fully working simple example to use Accelerate +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# This example also demonstrates the checkpointing and sharding capabilities +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def training_function(config, args): + # Initialize accelerator + dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader) + if args.with_tracking: + accelerator = Accelerator( + cpu=args.cpu, + mixed_precision=args.mixed_precision, + dataloader_config=dataloader_config, + log_with="all", + project_dir=args.project_dir, + ) + else: + accelerator = Accelerator( + cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config + ) + + if hasattr(args.checkpointing_steps, "isdigit"): + if args.checkpointing_steps == "epoch": + checkpointing_steps = args.checkpointing_steps + elif args.checkpointing_steps.isdigit(): + checkpointing_steps = int(args.checkpointing_steps) + else: + raise ValueError( + f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed." + ) + else: + checkpointing_steps = None + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + # We need to initialize the trackers we use, and also store our configuration + if args.with_tracking: + run = os.path.split(__file__)[-1].split(".")[0] + accelerator.init_trackers(run, config) + + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + metric = evaluate.load("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + set_seed(seed) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # We need to keep track of how many total steps we have iterated over + overall_step = 0 + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + + # Potentially load in the weights and states from a previous save + if args.resume_from_checkpoint: + if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "": + accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}") + accelerator.load_state(args.resume_from_checkpoint) + path = os.path.basename(args.resume_from_checkpoint) + else: + # Get the most recent checkpoint + dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()] + dirs.sort(key=os.path.getctime) + path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last + # Extract `epoch_{i}` or `step_{i}` + training_difference = os.path.splitext(path)[0] + + if "epoch" in training_difference: + starting_epoch = int(training_difference.replace("epoch_", "")) + 1 + resume_step = None + else: + resume_step = int(training_difference.replace("step_", "")) + starting_epoch = resume_step // len(train_dataloader) + resume_step -= starting_epoch * len(train_dataloader) + + # Now we train the model + for epoch in range(starting_epoch, num_epochs): + model.train() + if args.with_tracking: + total_loss = 0 + if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None: + # We need to skip steps until we reach the resumed step + if not args.use_stateful_dataloader: + active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step) + else: + active_dataloader = train_dataloader + overall_step += resume_step + else: + # After the first iteration though, we need to go back to the original dataloader + active_dataloader = train_dataloader + for step, batch in enumerate(active_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + # We keep track of the loss at each epoch + if args.with_tracking: + total_loss += loss.detach().float() + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + overall_step += 1 + + if isinstance(checkpointing_steps, int): + output_dir = f"step_{overall_step}" + if overall_step % checkpointing_steps == 0: + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + if args.with_tracking: + accelerator.log( + { + "accuracy": eval_metric["accuracy"], + "f1": eval_metric["f1"], + "train_loss": total_loss.item() / len(train_dataloader), + "epoch": epoch, + }, + step=epoch, + ) + + if checkpointing_steps == "epoch": + output_dir = f"epoch_{epoch}" + if args.output_dir is not None: + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + parser.add_argument( + "--checkpointing_steps", + type=str, + default=None, + help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="If the training should continue from a checkpoint folder.", + ) + parser.add_argument( + "--use_stateful_dataloader", + action="store_true", + help="If the dataloader should be a resumable stateful dataloader.", + ) + parser.add_argument( + "--with_tracking", + action="store_true", + help="Whether to load in all available experiment trackers from the environment and use them for logging.", + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--project_dir", + type=str, + default="logs", + help="Location on where to store experiment tracking logs` and relevent project information", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/README.md b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4cfd56f2ac5e2b6bc3579acfe29ef332d3d59e7e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/README.md @@ -0,0 +1,10 @@ +# Config Zoo + +This folder contains a variety of minimal configurations for `Accelerate` achieving certain goals. You can use these +direct config YAML's, or build off of them for your own YAML's. + +These are highly annoted versions, aiming to teach you what each section does. + +Each config can be run via `accelerate launch --config_file {file} run_me.py` + +`run_me.py` will then print out how the current environment is setup (the contents of the `AcceleratorState`) \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/deepspeed.yaml b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/deepspeed.yaml new file mode 100644 index 0000000000000000000000000000000000000000..5efddd05245a18105e5934f217b9b0cdd8fe7834 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/deepspeed.yaml @@ -0,0 +1,15 @@ +# Similar to FSDP, we set the distributed type as DEEPSPEED +distributed_type: DEEPSPEED +# With DeepSpeed, we utilize a deepspeed config file for the entire configuration +deepspeed_config: + # Can also be any of the config json's in accelerate/examples/deepspeed_config_templates + deepspeed_config_file: ../deepspeed_config_templates/zero_stage1_config.json + # If using ZeRO-3 and wanting to load big models in, this should be set to `true` so + # `transformers` uses the right `init` function + zero3_init_flag: false # true + +# Finally we need to specify the number of GPUs to use +num_processes: 2 +# Optionally we can set the mixed precision now instead of in the deepspeed config file, +# however this requires the `fp16` and `bf16` options to be set to `auto` in the deepspeed config file +# mixed_precision: "bf16" diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/fp8.yaml b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/fp8.yaml new file mode 100644 index 0000000000000000000000000000000000000000..4e81ac8e9fbced87548e40cd304d06e195f27ed8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/fp8.yaml @@ -0,0 +1,18 @@ +# This config template simply setups up the TransformersEngine config (and a config for a single GPU), +# this can interop with the other configs in this folder +distributed_type: "NO" +mixed_precision: "fp8" +# Then we specify the fp8 configuration: +fp8_config: + backend: TE # Can be TE | MS-AMP + # The following are TE specific arguments. + # See https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html#common-api for more details + amax_history_length: 1024 + fp8_format: E4M3 + interval: 1 + margin: 0 + override_linear_precision: false + # Generally this should always be set to `false` to have the most realistic fp8 eval performance + use_autocast_during_eval: false + # If using MS-AMP, we ignore all of the prior and set a opt_level + #opt_level: O1 \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/fsdp.yaml b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/fsdp.yaml new file mode 100644 index 0000000000000000000000000000000000000000..07c3e1b83e085011f4ccdd6811ebd91938aa7d41 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/fsdp.yaml @@ -0,0 +1,18 @@ +# Since we are doing FSDP (even though it's multi-GPU), we need to specify the distributed type as FSDP +distributed_type: FSDP +# Can be one of "no", "fp16", or "bf16" (see `transformer_engine.yaml` for `fp8`, but it works for FSDP as well) +mixed_precision: 'bf16' +# Specify the number of GPUs to use +num_processes: 2 +# Then we can specify the FSDP config +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: false + fsdp_offload_params: false + fsdp_sharding_strategy: FULL_SHARD + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_use_orig_params: true diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/multi_gpu.yaml b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/multi_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..9d6c12bf667960e3849231b26ebcf1ae9e5432f5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/multi_gpu.yaml @@ -0,0 +1,6 @@ +# Specify distributed_type as `MULTI_GPU` for DDP +distributed_type: "MULTI_GPU" +# Can be one of "no", "fp16", or "bf16" (see `transformer_engine.yaml` for `fp8`) +mixed_precision: "bf16" +# Specify the number of GPUs to use +num_processes: 2 \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/multi_node.yaml b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/multi_node.yaml new file mode 100644 index 0000000000000000000000000000000000000000..b76699f849c815b6956eb5643ae0ea865f44ecf2 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/multi_node.yaml @@ -0,0 +1,16 @@ +# This config template is for a multi-node setup. This assumes DDP, but can be interop'd with the other configs in this folder +# Generally it's recommended to look at the SLURM config template for a more robust multi-node setup +distributed_type: MULTI_GPU +# We need to specify the current machine's rank +machine_rank: 0 +# We then need to specify the IP address and port of the main process +main_process_ip: '1234' +main_process_port: 9999 +# We need to specify the number of machines +num_machines: 2 +# We need to specify the *total* number of processes +num_processes: 8 +# And then we need to specify how rdvz comms will be handled +rdzv_backend: static # or c10d +# If the compute nodes are on the same network (cloud will more than likely be false) +same_network: false diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/run_me.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/run_me.py new file mode 100644 index 0000000000000000000000000000000000000000..70bed48cc0fc316624cf773c7271bb774ade0ec8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/run_me.py @@ -0,0 +1,26 @@ +# 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. + +""" +A base script which outputs the accelerate config for the given environment +""" +from accelerate import Accelerator + + +accelerator = Accelerator() + +accelerator.print(f"Accelerator state from the current environment:\n{accelerator.state}") +if accelerator.fp8_recipe_handler is not None: + accelerator.print(f"FP8 config:\n{accelerator.fp8_recipe_handler}") +accelerator.end_training() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/single_gpu.yaml b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/single_gpu.yaml new file mode 100644 index 0000000000000000000000000000000000000000..3d1a81cedaf0b057f91401b7532874bcab75779c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/config_yaml_templates/single_gpu.yaml @@ -0,0 +1,4 @@ +# Since this is single GPU, we don't need distributed training +distributed_type: "NO" +# Can be one of "no", "fp16", or "bf16" (see `transformer_engine.yaml` for `fp8`) +mixed_precision: "bf16" \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/cv_example.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/cv_example.py new file mode 100644 index 0000000000000000000000000000000000000000..87d1575e08e9605aa5b415333552d18f1e17657a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/cv_example.py @@ -0,0 +1,211 @@ +# Copyright 2021 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. +import argparse +import os +import re + +import numpy as np +import PIL +import torch +from timm import create_model +from torch.optim.lr_scheduler import OneCycleLR +from torch.utils.data import DataLoader, Dataset +from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor + +from accelerate import Accelerator + + +######################################################################## +# This is a fully working simple example to use Accelerate +# +# This example trains a ResNet50 on the Oxford-IIT Pet Dataset +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +# Function to get the label from the filename +def extract_label(fname): + stem = fname.split(os.path.sep)[-1] + return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0] + + +class PetsDataset(Dataset): + def __init__(self, file_names, image_transform=None, label_to_id=None): + self.file_names = file_names + self.image_transform = image_transform + self.label_to_id = label_to_id + + def __len__(self): + return len(self.file_names) + + def __getitem__(self, idx): + fname = self.file_names[idx] + raw_image = PIL.Image.open(fname) + image = raw_image.convert("RGB") + if self.image_transform is not None: + image = self.image_transform(image) + label = extract_label(fname) + if self.label_to_id is not None: + label = self.label_to_id[label] + return {"image": image, "label": label} + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + image_size = config["image_size"] + if not isinstance(image_size, (list, tuple)): + image_size = (image_size, image_size) + + # Grab all the image filenames + file_names = [os.path.join(args.data_dir, fname) for fname in os.listdir(args.data_dir) if fname.endswith(".jpg")] + + # Build the label correspondences + all_labels = [extract_label(fname) for fname in file_names] + id_to_label = list(set(all_labels)) + id_to_label.sort() + label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)} + + # Set the seed before splitting the data. + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + + # Split our filenames between train and validation + random_perm = np.random.permutation(len(file_names)) + cut = int(0.8 * len(file_names)) + train_split = random_perm[:cut] + eval_split = random_perm[cut:] + + # For training we use a simple RandomResizedCrop + train_tfm = Compose([RandomResizedCrop(image_size, scale=(0.5, 1.0)), ToTensor()]) + train_dataset = PetsDataset( + [file_names[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id + ) + + # For evaluation, we use a deterministic Resize + eval_tfm = Compose([Resize(image_size), ToTensor()]) + eval_dataset = PetsDataset([file_names[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id) + + # Instantiate dataloaders. + train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4) + eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size, num_workers=4) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + + # Freezing the base model + for param in model.parameters(): + param.requires_grad = False + for param in model.get_classifier().parameters(): + param.requires_grad = True + + # We normalize the batches of images to be a bit faster. + mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None].to(accelerator.device) + std = torch.tensor(model.default_cfg["std"])[None, :, None, None].to(accelerator.device) + + # Instantiate optimizer + optimizer = torch.optim.Adam(params=model.parameters(), lr=lr / 25) + + # Instantiate learning rate scheduler + lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=lr, epochs=num_epochs, steps_per_epoch=len(train_dataloader)) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch = {k: v.to(accelerator.device) for k, v in batch.items()} + inputs = (batch["image"] - mean) / std + outputs = model(inputs) + loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + accurate = 0 + num_elems = 0 + for _, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch = {k: v.to(accelerator.device) for k, v in batch.items()} + inputs = (batch["image"] - mean) / std + with torch.no_grad(): + outputs = model(inputs) + predictions = outputs.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["label"])) + accurate_preds = predictions == references + num_elems += accurate_preds.shape[0] + accurate += accurate_preds.long().sum() + + eval_metric = accurate.item() / num_elems + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument("--data_dir", required=True, help="The data folder on disk.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument( + "--checkpointing_steps", + type=str, + default=None, + help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 3e-2, "num_epochs": 3, "seed": 42, "batch_size": 64, "image_size": 224} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage1_config.json b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage1_config.json new file mode 100644 index 0000000000000000000000000000000000000000..674420e57fc21329cd466dc2a2e68f981c621bce --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage1_config.json @@ -0,0 +1,43 @@ +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto", + "torch_adam": true, + "adam_w_mode": true + } + }, + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto", + "total_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 1, + "allgather_partitions": true, + "allgather_bucket_size": 2e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": "auto", + "contiguous_gradients": true + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage2_config.json b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage2_config.json new file mode 100644 index 0000000000000000000000000000000000000000..9597f8485c1a96424ff91f88ab9d934c4ac07bb9 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage2_config.json @@ -0,0 +1,43 @@ +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto", + "torch_adam": true, + "adam_w_mode": true + } + }, + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto", + "total_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 2, + "allgather_partitions": true, + "allgather_bucket_size": 2e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": "auto", + "contiguous_gradients": true + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage2_offload_config.json b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage2_offload_config.json new file mode 100644 index 0000000000000000000000000000000000000000..98baedef38a86fe1cef3d5e1a8659b6b08eb275b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage2_offload_config.json @@ -0,0 +1,47 @@ +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto", + "torch_adam": true, + "adam_w_mode": true + } + }, + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto", + "total_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 2, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "allgather_partitions": true, + "allgather_bucket_size": 2e8, + "overlap_comm": true, + "reduce_scatter": true, + "reduce_bucket_size": "auto", + "contiguous_gradients": true + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage3_config.json b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage3_config.json new file mode 100644 index 0000000000000000000000000000000000000000..2ec6fff41a79b4f1ad0d1849cbba640de67b113d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage3_config.json @@ -0,0 +1,44 @@ +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto" + } + }, + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto", + "total_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 3, + "overlap_comm": true, + "contiguous_gradients": true, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "sub_group_size": 1e9, + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": "auto" + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage3_offload_config.json b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage3_offload_config.json new file mode 100644 index 0000000000000000000000000000000000000000..edae8e6286e632d40fffd990b39bbde5d7409c03 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/deepspeed_config_templates/zero_stage3_offload_config.json @@ -0,0 +1,52 @@ +{ + "fp16": { + "enabled": true, + "loss_scale": 0, + "loss_scale_window": 1000, + "initial_scale_power": 16, + "hysteresis": 2, + "min_loss_scale": 1 + }, + "optimizer": { + "type": "AdamW", + "params": { + "lr": "auto", + "weight_decay": "auto" + } + }, + "scheduler": { + "type": "WarmupDecayLR", + "params": { + "warmup_min_lr": "auto", + "warmup_max_lr": "auto", + "warmup_num_steps": "auto", + "total_num_steps": "auto" + } + }, + "zero_optimization": { + "stage": 3, + "offload_optimizer": { + "device": "cpu", + "pin_memory": true + }, + "offload_param": { + "device": "cpu", + "pin_memory": true + }, + "overlap_comm": true, + "contiguous_gradients": true, + "reduce_bucket_size": "auto", + "stage3_prefetch_bucket_size": "auto", + "stage3_param_persistence_threshold": "auto", + "sub_group_size": 1e9, + "stage3_max_live_parameters": 1e9, + "stage3_max_reuse_distance": 1e9, + "stage3_gather_16bit_weights_on_model_save": "auto" + }, + "gradient_accumulation_steps": 1, + "gradient_clipping": "auto", + "steps_per_print": 2000, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "wall_clock_breakdown": false +} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/README.md b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/README.md new file mode 100644 index 0000000000000000000000000000000000000000..d1585d522e66eac003354534011af78b67e85ef0 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/README.md @@ -0,0 +1,25 @@ +# Distributed inference examples + +This folder contains a variety of tutorials for running distributed inference with the following strategy: + +Load an entire model onto each GPU and sending chunks of a batch through each GPU’s model copy at a time + +## Installation + +```bash +pip install accelerate torch +``` + +## Running code + +You can either use `torchrun` or the recommended way of `accelerate launch` (without needing to run `accelerate config`) on each script: + +```bash +accelerate launch --num_processes {NUM_GPUS} phi2.py +``` + +Or: + +```bash +torchrun --nproc-per-node {NUM_GPUS} phi2.py +``` \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/phi2.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/phi2.py new file mode 100644 index 0000000000000000000000000000000000000000..1a24abbde0f0e1861a8909a0d68f508b71fd92fd --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/phi2.py @@ -0,0 +1,86 @@ +# Copyright 2024 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. + +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +from accelerate import PartialState +from accelerate.utils import gather_object + + +# Start up the distributed environment without needing the Accelerator. +distributed_state = PartialState() + +# You can change the model to any LLM such as mistralai/Mistral-7B-v0.1 or meta-llama/Llama-2-7b-chat-hf +model_name = "microsoft/phi-2" +model = AutoModelForCausalLM.from_pretrained( + model_name, device_map=distributed_state.device, torch_dtype=torch.float16 +) + +tokenizer = AutoTokenizer.from_pretrained(model_name) +# Need to set the padding token to the eos token for generation +tokenizer.pad_token = tokenizer.eos_token + +prompts = [ + "I would like to", + "hello how are you", + "what is going on", + "roses are red and", + "welcome to the hotel", +] + +# You can change the batch size depending on your GPU RAM +batch_size = 2 +# We set it to 8 since it is better for some hardware. More information here https://github.com/huggingface/tokenizers/issues/991 +pad_to_multiple_of = 8 + +# Split into batches +# We will get the following results: +# [ ["I would like to", "hello how are you"], [ "what is going on", "roses are red and"], [ "welcome to the hotel"] ] +formatted_prompts = [prompts[i : i + batch_size] for i in range(0, len(prompts), batch_size)] + +# Apply padding on the left since we are doing generation +padding_side_default = tokenizer.padding_side +tokenizer.padding_side = "left" +# Tokenize each batch +tokenized_prompts = [ + tokenizer(formatted_prompt, padding=True, pad_to_multiple_of=pad_to_multiple_of, return_tensors="pt") + for formatted_prompt in formatted_prompts +] +# Put back the original padding behavior +tokenizer.padding_side = padding_side_default + +completions_per_process = [] +# We automatically split the batched data we passed to it across all the processes. We also set apply_padding=True +# so that the GPUs will have the same number of prompts, and you can then gather the results. +# For example, if we have 2 gpus, the distribution will be: +# GPU 0: ["I would like to", "hello how are you"], "what is going on", "roses are red and"] +# GPU 1: ["welcome to the hotel"], ["welcome to the hotel"] -> this prompt is duplicated to ensure that all gpus have the same number of prompts +with distributed_state.split_between_processes(tokenized_prompts, apply_padding=True) as batched_prompts: + for batch in batched_prompts: + # Move the batch to the device + batch = batch.to(distributed_state.device) + # We generate the text, decode it and add it to the list completions_per_process + outputs = model.generate(**batch, max_new_tokens=20) + generated_text = tokenizer.batch_decode(outputs, skip_special_tokens=True) + completions_per_process.extend(generated_text) + +# We are gathering string, so we need to use gather_object. +# If you need to gather tensors, you can use gather from accelerate.utils +completions_gather = gather_object(completions_per_process) + +# Drop duplicates produced by apply_padding in split_between_processes +completions = completions_gather[: len(prompts)] + +distributed_state.print(completions) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/stable_diffusion.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/stable_diffusion.py new file mode 100644 index 0000000000000000000000000000000000000000..0c5e6579b94f8024eaf8815dd608cfa566593aee --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/distributed/stable_diffusion.py @@ -0,0 +1,30 @@ +# Copyright 2024 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. + +import torch +from diffusers import DiffusionPipeline + +from accelerate import PartialState # Can also be Accelerator or AcceleratorState + + +pipe = DiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5", torch_dtype=torch.float16) +distributed_state = PartialState() +pipe.to(distributed_state.device) + +# Assume two processes +# On the first GPU, the prompts will be ["a dog", "a cat"], +# and on the second GPU it will be ["a chicken", "a chicken"]. +# Make sure to drop the final sample, as it will be a duplicate of the previous one. +with distributed_state.split_between_processes(["a dog", "a cat", "a chicken"], apply_padding=True) as prompt: + result = pipe(prompt).images diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/README.md b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9bfa2741395d08e2928d4b7e82457c18961d6bb7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/README.md @@ -0,0 +1,62 @@ +# Distributed inference examples with PiPPy + +This repo contains a variety of tutorials for using the [PiPPy](https://github.com/PyTorch/PiPPy) pipeline parallelism library with accelerate. You will find examples covering: + +1. How to trace the model using `accelerate.prepare_pippy` +2. How to specify inputs based on what the model expects (when to use `kwargs`, `args`, and such) +3. How to gather the results at the end. + +## Installation + +This requires the `main` branch of accelerate (or a version at least 0.27.0), `pippy` version of 0.2.0 or greater, and at least python 3.9. Please install using `pip install .` to pull from the `setup.py` in this repo, or run manually: + +```bash +pip install 'accelerate>=0.27.0' 'torchpippy>=0.2.0' +``` + +## Running code + +You can either use `torchrun` or the recommended way of `accelerate launch` (without needing to run `accelerate config`) on each script: + +```bash +accelerate launch bert.py +``` + +Or: + +```bash +accelerate launch --num_processes {NUM_GPUS} bert.py +``` + +Or: + +```bash +torchrun --nproc-per-node {NUM_GPUS} bert.py +``` + +## General speedups + +One can expect that PiPPy will outperform native model parallism by a multiplicative factor since all GPUs are running at all times with inputs, rather than one input being passed through a GPU at a time waiting for the prior to finish. + +Below are some benchmarks we have found when using the accelerate-pippy integration for a few models when running on 2x4090's: + +### Bert + +| | Accelerate/Sequential | PiPPy + Accelerate | +|---|---|---| +| First batch | 0.2137s | 0.3119s | +| Average of 5 batches | 0.0099s | **0.0062s** | + +### GPT2 + +| | Accelerate/Sequential | PiPPy + Accelerate | +|---|---|---| +| First batch | 0.1959s | 0.4189s | +| Average of 5 batches | 0.0205s | **0.0126s** | + +### T5 + +| | Accelerate/Sequential | PiPPy + Accelerate | +|---|---|---| +| First batch | 0.2789s | 0.3809s | +| Average of 5 batches | 0.0198s | **0.0166s** | \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/bert.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/bert.py new file mode 100644 index 0000000000000000000000000000000000000000..474409f5d0f914611aa96ee8bd5dcbd960e4abd5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/bert.py @@ -0,0 +1,89 @@ +# Copyright 2024 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. +import time + +import torch +from transformers import AutoModelForMaskedLM + +from accelerate import PartialState, prepare_pippy +from accelerate.utils import set_seed + + +# Set the random seed to have reproducable outputs +set_seed(42) + +# Create an example model +model = AutoModelForMaskedLM.from_pretrained("bert-base-uncased") +model.eval() + +# Input configs +# Create example inputs for the model +input = torch.randint( + low=0, + high=model.config.vocab_size, + size=(1, 512), # bs x seq_len + device="cpu", + dtype=torch.int64, + requires_grad=False, +) + + +# Create a pipeline stage from the model +# Using `auto` is equivalent to letting `device_map="auto"` figure +# out device mapping and will also split the model according to the +# number of total GPUs available if it fits on one GPU +model = prepare_pippy(model, split_points="auto", example_args=(input,)) + +# You can pass `gather_output=True` to have the output from the model +# available on all GPUs +# model = prepare_pippy(model, split_points="auto", example_args=(input,), gather_output=True) + +# Create new inputs of the expected size (n_processes) +input = torch.randint( + low=0, + high=model.config.vocab_size, + size=(2, 512), # bs x seq_len + device="cpu", + dtype=torch.int64, + requires_grad=False, +) + +# Move the inputs to the first device +input = input.to("cuda:0") + +# Take an average of 5 times +# Measure first batch +torch.cuda.synchronize() +start_time = time.time() +with torch.no_grad(): + output = model(input) +torch.cuda.synchronize() +end_time = time.time() +first_batch = end_time - start_time + +# Now that CUDA is init, measure after +torch.cuda.synchronize() +start_time = time.time() +for i in range(5): + with torch.no_grad(): + output = model(input) +torch.cuda.synchronize() +end_time = time.time() + +# The outputs are only on the final process by default +if PartialState().is_last_process: + output = torch.stack(tuple(output[0])) + print(f"Time of first pass: {first_batch}") + print(f"Average time per batch: {(end_time - start_time) / 5}") +PartialState().destroy_process_group() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/gpt2.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/gpt2.py new file mode 100644 index 0000000000000000000000000000000000000000..d1f232b51de231b530f7163d1cf656e8a90173e7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/gpt2.py @@ -0,0 +1,88 @@ +# Copyright 2024 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. +import time + +import torch +from transformers import AutoModelForSequenceClassification + +from accelerate import PartialState, prepare_pippy +from accelerate.utils import set_seed + + +# Set the random seed to have reproducable outputs +set_seed(42) + +# Create an example model +model = AutoModelForSequenceClassification.from_pretrained("gpt2") +model.eval() + +# Input configs +# Create example inputs for the model +input = torch.randint( + low=0, + high=model.config.vocab_size, + size=(1, 1024), # bs x seq_len + device="cpu", + dtype=torch.int64, + requires_grad=False, +) + +# Create a pipeline stage from the model +# Using `auto` is equivalent to letting `device_map="auto"` figure +# out device mapping and will also split the model according to the +# number of total GPUs available if it fits on one GPU +model = prepare_pippy(model, split_points="auto", example_args=(input,)) + +# You can pass `gather_output=True` to have the output from the model +# available on all GPUs +# model = prepare_pippy(model, split_points="auto", example_args=(input,), gather_output=True) + +# Create new inputs of the expected size (n_processes) +input = torch.randint( + low=0, + high=model.config.vocab_size, + size=(2, 1024), # bs x seq_len + device="cpu", + dtype=torch.int64, + requires_grad=False, +) + +# Move the inputs to the first device +input = input.to("cuda:0") + +# Take an average of 5 times +# Measure first batch +torch.cuda.synchronize() +start_time = time.time() +with torch.no_grad(): + output = model(input) +torch.cuda.synchronize() +end_time = time.time() +first_batch = end_time - start_time + +# Now that CUDA is init, measure after +torch.cuda.synchronize() +start_time = time.time() +for i in range(5): + with torch.no_grad(): + output = model(input) +torch.cuda.synchronize() +end_time = time.time() + +# The outputs are only on the final process by default +if PartialState().is_last_process: + output = torch.stack(tuple(output[0])) + print(f"Time of first pass: {first_batch}") + print(f"Average time per batch: {(end_time - start_time) / 5}") +PartialState().destroy_process_group() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/llama.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/llama.py new file mode 100644 index 0000000000000000000000000000000000000000..631da07bfcf90ec0ad324428b14e8924a94b8431 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/llama.py @@ -0,0 +1,57 @@ +# Copyright 2024 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. +import torch +from transformers import AutoModelForCausalLM, AutoTokenizer + +from accelerate import PartialState, prepare_pippy + + +# sdpa implementation which is the default torch>2.1.2 fails with the tracing + attention mask kwarg +# with attn_implementation="eager" mode, the forward is very slow for some reason +model = AutoModelForCausalLM.from_pretrained( + "meta-llama/Llama-2-7b-chat-hf", low_cpu_mem_usage=True, attn_implementation="sdpa" +) +model.eval() + +# Input configs +# Create example inputs for the model +tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-chat-hf") +prompts = ("I would like to", "I really like to") # bs = 2, sending 2 per process +tokenizer.pad_token = tokenizer.eos_token +inputs = tokenizer(prompts, return_tensors="pt", padding=True) + +# Create a pipeline stage from the model +# Using `auto` is equivalent to letting `device_map="auto"` figure +# out device mapping and will also split the model according to the +# number of total GPUs available if it fits on one GPU +model = prepare_pippy(model, split_points="auto", example_kwargs=inputs) + +# You can pass `gather_output=True` to have the output from the model +# available on all GPUs +# model = prepare_pippy(model, split_points="auto", example_args=(input,), gather_output=True) + +# currently we don't support `model.generate` +# output = model.generate(**inputs, max_new_tokens=1) +prompts = ("I would like to", "I really like to", "The weather is pretty") # bs = 3 +inputs = tokenizer(prompts, return_tensors="pt", padding=True) +inputs = inputs.to(0) +with torch.no_grad(): + output = model(**inputs) + +# The outputs are only on the final process by default +if PartialState().is_last_process: + next_token_logits = output[0][:, -1, :] + next_token = torch.argmax(next_token_logits, dim=-1) + print(tokenizer.batch_decode(next_token)) +PartialState().destroy_process_group() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/requirements.txt b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..dcb52ec39e0dbcc08baa0a1dffc6be5f6f49cecf --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/requirements.txt @@ -0,0 +1,2 @@ +accelerate +pippy>=0.2.0 \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/t5.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/t5.py new file mode 100644 index 0000000000000000000000000000000000000000..b134eb5372c232a6cbefdef6e3aba9e36633166e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/inference/pippy/t5.py @@ -0,0 +1,99 @@ +# Copyright 2024 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. +import time + +import torch +from packaging import version +from transformers import AutoModelForSeq2SeqLM + +from accelerate import PartialState, prepare_pippy +from accelerate import __version__ as accelerate_version +from accelerate.utils import set_seed + + +if version.parse(accelerate_version) > version.parse("0.33.0"): + raise RuntimeError( + "Using encoder/decoder models is not supported with the `torch.pipelining` integration or accelerate>=0.34.0. " + "Please use a lower accelerate version and `torchpippy`, which this example uses." + ) + + +# Set the random seed to have reproducable outputs +set_seed(42) + +# Create an example model +model = AutoModelForSeq2SeqLM.from_pretrained("t5-small") +model.eval() + +# Input configs +# Create example inputs for the model +input = torch.randint( + low=0, + high=model.config.vocab_size, + size=(2, 1024), # bs x seq_len + device="cpu", + dtype=torch.int64, + requires_grad=False, +) + +example_inputs = {"input_ids": input, "decoder_input_ids": input} + +# Create a pipeline stage from the model +# Using `auto` is equivalent to letting `device_map="auto"` figure +# out device mapping and will also split the model according to the +# number of total GPUs available if it fits on one GPU +model = prepare_pippy( + model, + no_split_module_classes=["T5Block"], + example_kwargs=example_inputs, +) + +# You can pass `gather_output=True` to have the output from the model +# available on all GPUs +# model = prepare_pippy( +# model, +# no_split_module_classes=["T5Block"], +# example_kwargs=example_inputs, +# gather_outputs=True +# ) + +# The model expects a tuple during real inference +# with the data on the first device +args = (example_inputs["input_ids"].to("cuda:0"), example_inputs["decoder_input_ids"].to("cuda:0")) + +# Take an average of 5 times +# Measure first batch +torch.cuda.synchronize() +start_time = time.time() +with torch.no_grad(): + output = model(*args) +torch.cuda.synchronize() +end_time = time.time() +first_batch = end_time - start_time + +# Now that CUDA is init, measure after +torch.cuda.synchronize() +start_time = time.time() +for i in range(5): + with torch.no_grad(): + output = model(*args) +torch.cuda.synchronize() +end_time = time.time() + +# The outputs are only on the final process by default +if PartialState().is_last_process: + output = torch.stack(tuple(output[0])) + print(f"Time of first pass: {first_batch}") + print(f"Average time per batch: {(end_time - start_time) / 5}") +PartialState().destroy_process_group() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/multigpu_remote_launcher.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/multigpu_remote_launcher.py new file mode 100644 index 0000000000000000000000000000000000000000..60ee5a673fad86bacc83cc39260b1e648f64b692 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/multigpu_remote_launcher.py @@ -0,0 +1,68 @@ +# 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. +import argparse + +import runhouse as rh +import torch +from nlp_example import training_function + +from accelerate.utils import PrepareForLaunch, patch_environment + + +def launch_train(*args): + num_processes = torch.cuda.device_count() + print(f"Device count: {num_processes}") + with patch_environment( + world_size=num_processes, master_addr="127.0.0.1", master_port="29500", mixed_precision=args[1].mixed_precision + ): + launcher = PrepareForLaunch(training_function, distributed_type="MULTI_GPU") + torch.multiprocessing.start_processes(launcher, args=args, nprocs=num_processes, start_method="spawn") + + +if __name__ == "__main__": + # Refer to https://runhouse-docs.readthedocs-hosted.com/en/main/rh_primitives/cluster.html#hardware-setup + # for cloud access setup instructions (if using on-demand hardware), and for API specifications. + + # on-demand GPU + # gpu = rh.cluster(name='rh-cluster', instance_type='V100:1', provider='cheapest', use_spot=False) # single GPU + gpu = rh.cluster(name="rh-cluster", instance_type="V100:4", provider="cheapest", use_spot=False) # multi GPU + gpu.up_if_not() + + # on-prem GPU + # gpu = rh.cluster( + # ips=["ip_addr"], ssh_creds={ssh_user:"", ssh_private_key:""}, name="rh-cluster" + # ) + + # Set up remote function + reqs = [ + "pip:./", + "transformers", + "datasets", + "evaluate", + "tqdm", + "scipy", + "scikit-learn", + "tensorboard", + "torch --upgrade --extra-index-url https://download.pytorch.org/whl/cu117", + ] + launch_train_gpu = rh.function(fn=launch_train, system=gpu, reqs=reqs, name="train_bert_glue") + + # Define train args/config, run train function + train_args = argparse.Namespace(cpu=False, mixed_precision="fp16") + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + launch_train_gpu(config, train_args, stream_logs=True) + + # Alternatively, we can just run as instructed in the README (but only because there's already a wrapper CLI): + # gpu.install_packages(reqs) + # gpu.run(['accelerate launch --multi_gpu accelerate/examples/nlp_example.py']) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/nlp_example.py b/tasks/tasksmith-5d12db5414d2/environment/source/examples/nlp_example.py new file mode 100644 index 0000000000000000000000000000000000000000..3d2012f097d402b754b4e943e30bab2ce54e73c9 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/nlp_example.py @@ -0,0 +1,209 @@ +# Copyright 2021 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. +import argparse + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType + + +######################################################################## +# This is a fully working simple example to use Accelerate +# +# This example trains a Bert base model on GLUE MRPC +# in any of the following settings (with the same script): +# - single CPU or single GPU +# - multi GPUS (using PyTorch distributed mode) +# - (multi) TPUs +# - fp16 (mixed-precision) or fp32 (normal precision) +# +# To run it in each of these various modes, follow the instructions +# in the readme for examples: +# https://github.com/huggingface/accelerate/tree/main/examples +# +######################################################################## + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16): + """ + Creates a set of `DataLoader`s for the `glue` dataset, + using "bert-base-cased" as the tokenizer. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + """ + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # For Torchxla, it's best to pad everything to the same length or training will be very slow. + max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None + # When using mixed precision we want round multiples of 8/16 + if accelerator.mixed_precision == "fp8": + pad_to_multiple_of = 16 + elif accelerator.mixed_precision != "no": + pad_to_multiple_of = 8 + else: + pad_to_multiple_of = None + + return tokenizer.pad( + examples, + padding="longest", + max_length=max_length, + pad_to_multiple_of=pad_to_multiple_of, + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], + shuffle=False, + collate_fn=collate_fn, + batch_size=EVAL_BATCH_SIZE, + drop_last=(accelerator.mixed_precision == "fp8"), + ) + + return train_dataloader, eval_dataloader + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision) + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + + metric = evaluate.load("glue", "mrpc") + + # If the batch size is too big we use gradient accumulation + gradient_accumulation_steps = 1 + if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA: + gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE + batch_size = MAX_GPU_BATCH_SIZE + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True) + + # We could avoid this line since the accelerator is set with `device_placement=True` (default value). + # Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer + # creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that). + model = model.to(accelerator.device) + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=lr) + + # Instantiate scheduler + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps, + ) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"])) + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script.") + parser.add_argument( + "--mixed_precision", + type=str, + default=None, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether to use mixed precision. Choose" + "between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10." + "and an Nvidia Ampere GPU.", + ) + parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.") + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/requirements.txt b/tasks/tasksmith-5d12db5414d2/environment/source/examples/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..fd571f224cf20d551cb55b3ff30e947eae841245 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/requirements.txt @@ -0,0 +1,5 @@ +accelerate # used to be installed in Amazon SageMaker environment +evaluate +datasets==2.3.2 +schedulefree +huggingface_hub>=0.20.0 diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/fsdp_config.yaml b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/fsdp_config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1708fe20958ef8b3346069f811d0627dbe962b15 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/fsdp_config.yaml @@ -0,0 +1,12 @@ +distributed_type: FSDP +fsdp_config: + fsdp_activation_checkpointing: false + fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP + fsdp_backward_prefetch: BACKWARD_PRE + fsdp_cpu_ram_efficient_loading: true + fsdp_forward_prefetch: false + fsdp_offload_params: false + fsdp_sharding_strategy: FULL_SHARD + fsdp_state_dict_type: SHARDED_STATE_DICT + fsdp_sync_module_states: true + fsdp_use_orig_params: true diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multicpu.sh b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multicpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..5e3f817f89884750a8168a4b8f3f01d882365a9a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multicpu.sh @@ -0,0 +1,65 @@ +#!/bin/bash -l + +#SBATCH --job-name=multicpu +#SBATCH --nodes=2 # number of Nodes +#SBATCH --ntasks-per-node=1 # number of MP tasks +#SBATCH --exclusive +#SBATCH --output=O-%x.%j +#SBATCH --error=E-%x.%j + +###################### +### Set enviroment ### +###################### +source activateEnvironment.sh + +###################### +#### Set network ##### +###################### +head_node_ip=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) +###################### + +# Setup env variables for distributed jobs +export MASTER_PORT="${MASTER_PORT:-29555 }" +echo "head_node_ip=${head_node_ip}" +echo "MASTER_PORT=${MASTER_PORT}" + +INSTANCES_PER_NODE="${INSTANCES_PER_NODE:-1}" + +if [[ $SLURM_NNODES == 1 ]] && [[ $INSTANCES_PER_NODE == 1 ]]; then + export CCL_WORKER_COUNT=0 + LAUNCHER="" +else + # Setup env variables for distributed jobs + export CCL_WORKER_COUNT="${CCL_WORKER_COUNT:-2}" + echo "CCL_WORKER_COUNT=${CCL_WORKER_COUNT}" + + # Write hostfile + HOSTFILE_PATH=hostfile + scontrol show hostname $SLURM_JOB_NODELIST | perl -ne 'chomb; print "$_"x1'> ${HOSTFILE_PATH} + + export LAUNCHER="accelerate launch \ + --num_processes $((SLURM_NNODES * ${INSTANCES_PER_NODE})) \ + --num_machines $SLURM_NNODES \ + --rdzv_backend c10d \ + --main_process_ip $head_node_ip \ + --main_process_port $MASTER_PORT \ + --mpirun_hostfile $HOSTFILE_PATH \ + --mpirun_ccl $CCL_WORKER_COUNT" +fi + +# This step is necessary because accelerate launch does not handle multiline arguments properly +export ACCELERATE_DIR="${ACCELERATE_DIR:-/accelerate}" +export SCRIPT="${ACCELERATE_DIR}/examples/complete_nlp_example.py" +export SCRIPT_ARGS=" \ + --cpu \ + --output_dir ${ACCELERATE_DIR}/examples/output \ + " + +# This step is necessary because accelerate launch does not handle multiline arguments properly +export CMD="$LAUNCHER $SCRIPT $SCRIPT_ARGS" +# Print the command +echo $CMD +echo "" + +# Run the command +eval $CMD \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multigpu.sh b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multigpu.sh new file mode 100644 index 0000000000000000000000000000000000000000..514009c6d9a086ecbc955dead216ccdcc49b3a86 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multigpu.sh @@ -0,0 +1,28 @@ +#!/bin/bash + +#SBATCH --job-name=multigpu +#SBATCH -D . +#SBATCH --output=O-%x.%j +#SBATCH --error=E-%x.%j +#SBATCH --nodes=1 +#SBATCH --ntasks-per-node=1 # number of MP tasks +#SBATCH --gres=gpu:4 # number of GPUs per node +#SBATCH --cpus-per-task=160 # number of cores per tasks +#SBATCH --time=01:59:00 # maximum execution time (HH:MM:SS) + +###################### +### Set enviroment ### +###################### +source activateEnvironment.sh +export GPUS_PER_NODE=4 +###################### + +export ACCELERATE_DIR="${ACCELERATE_DIR:-/accelerate}" +export SCRIPT="${ACCELERATE_DIR}/examples/complete_nlp_example.py" +export SCRIPT_ARGS=" \ + --mixed_precision fp16 \ + --output_dir ${ACCELERATE_DIR}/examples/output \ + --with_tracking \ + " + +accelerate launch --num_processes $GPUS_PER_NODE $SCRIPT $SCRIPT_ARGS \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multinode.sh b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multinode.sh new file mode 100644 index 0000000000000000000000000000000000000000..61d5ff2c6a2c84ff9037c4262f550165008bc59d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multinode.sh @@ -0,0 +1,42 @@ +#!/bin/bash + +#SBATCH --job-name=multinode +#SBATCH -D . +#SBATCH --output=O-%x.%j +#SBATCH --error=E-%x.%j +#SBATCH --nodes=4 # number of nodes +#SBATCH --ntasks-per-node=1 # number of MP tasks +#SBATCH --gres=gpu:4 # number of GPUs per node +#SBATCH --cpus-per-task=160 # number of cores per tasks +#SBATCH --time=01:59:00 # maximum execution time (HH:MM:SS) + +###################### +### Set enviroment ### +###################### +source activateEnvironment.sh +export GPUS_PER_NODE=4 +###################### + +###################### +#### Set network ##### +###################### +head_node_ip=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) +###################### + +export LAUNCHER="accelerate launch \ + --num_processes $((SLURM_NNODES * GPUS_PER_NODE)) \ + --num_machines $SLURM_NNODES \ + --rdzv_backend c10d \ + --main_process_ip $head_node_ip \ + --main_process_port 29500 \ + " +export ACCELERATE_DIR="${ACCELERATE_DIR:-/accelerate}" +export SCRIPT="${ACCELERATE_DIR}/examples/complete_nlp_example.py" +export SCRIPT_ARGS=" \ + --mixed_precision fp16 \ + --output_dir ${ACCELERATE_DIR}/examples/output \ + " + +# This step is necessary because accelerate launch does not handle multiline arguments properly +export CMD="$LAUNCHER $PYTHON_FILE $ARGS" +srun $CMD \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multinode_fsdp.sh b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multinode_fsdp.sh new file mode 100644 index 0000000000000000000000000000000000000000..1f8ab5c914a344b89d63702dd694fa6776d91834 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/examples/slurm/submit_multinode_fsdp.sh @@ -0,0 +1,43 @@ +#!/bin/bash + +#SBATCH --job-name=multinode +#SBATCH -D . +#SBATCH --output=O-%x.%j +#SBATCH --error=E-%x.%j +#SBATCH --nodes=4 # number of nodes +#SBATCH --ntasks-per-node=1 # number of MP tasks +#SBATCH --gres=gpu:4 # number of GPUs per node +#SBATCH --cpus-per-task=160 # number of cores per tasks +#SBATCH --time=01:59:00 # maximum execution time (HH:MM:SS) + +###################### +### Set enviroment ### +###################### +source activateEnvironment.sh +export GPUS_PER_NODE=4 +###################### + +###################### +#### Set network ##### +###################### +head_node_ip=$(scontrol show hostnames $SLURM_JOB_NODELIST | head -n 1) +###################### +export ACCELERATE_DIR="${ACCELERATE_DIR:-/accelerate}" + +export LAUNCHER="accelerate launch \ + --config ${ACCELERATE_DIR}/examples/slurm/fsdp_config.yaml \ + --num_processes $((SLURM_NNODES * GPUS_PER_NODE)) \ + --num_machines $SLURM_NNODES \ + --rdzv_backend c10d \ + --main_process_ip $head_node_ip \ + --main_process_port 29500 \ + " +export SCRIPT="${ACCELERATE_DIR}/examples/complete_nlp_example.py" +export SCRIPT_ARGS=" \ + --mixed_precision fp16 \ + --output_dir ${ACCELERATE_DIR}/examples/output \ + " + +# This step is necessary because accelerate launch does not handle multiline arguments properly +export CMD="$LAUNCHER $SCRIPT $SCRIPT_ARGS" +srun $CMD \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/pyproject.toml b/tasks/tasksmith-5d12db5414d2/environment/source/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..e0d4d7db5ba00ead57fa5bbfbd892b2d879c42ef --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/pyproject.toml @@ -0,0 +1,44 @@ +[tool.ruff] +line-length = 119 +target-version = "py38" + +[tool.ruff.lint] +preview = true +ignore-init-module-imports = true +extend-select = [ + "B009", # static getattr + "B010", # static setattr + "CPY", # Copyright + "E", # PEP8 errors + "F", # PEP8 formatting + "I", # Import sorting + "TID251", # Banned API + "UP", # Pyupgrade + "W", # PEP8 warnings +] +ignore = [ + "E501", # Line length (handled by ruff-format) + "E741", # Ambiguous variable name + "W605", # Invalid escape sequence + "UP007", # X | Y type annotations +] + +[tool.ruff.lint.per-file-ignores] +"__init__.py" = [ + "F401", # Ignore seemingly unused imports (they're meant for re-export) +] +"manim_animations/*" = ["ALL"] + +[tool.ruff.lint.isort] +lines-after-imports = 2 +known-first-party = ["accelerate"] + +[tool.ruff.format] +exclude = [ + "manim_animations/*" +] + +[tool.ruff.lint.flake8-tidy-imports.banned-api] +"os.getenv".msg = "Use os.environ instead" +"os.putenv".msg = "Use os.environ instead" +"os.unsetenv".msg = "Use os.environ instead" diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/setup.py b/tasks/tasksmith-5d12db5414d2/environment/source/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..68374993e72177ab986b7acb6ef10b835daff9aa --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/setup.py @@ -0,0 +1,122 @@ +# 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. + +from setuptools import find_packages, setup + + +extras = {} +extras["quality"] = [ + "black ~= 23.1", # hf-doc-builder has a hidden dependency on `black` + "hf-doc-builder >= 0.3.0", + "ruff ~= 0.2.1", +] +extras["docs"] = [] +extras["test_prod"] = ["pytest>=7.2.0,<=8.0.0", "pytest-xdist", "pytest-subtests", "parameterized"] +extras["test_dev"] = [ + "datasets", + "diffusers", + "evaluate", + "torchdata>=0.8.0", + "torchpippy>=0.2.0", + "transformers", + "scipy", + "scikit-learn", + "tqdm", + "bitsandbytes", + "timm", +] +extras["testing"] = extras["test_prod"] + extras["test_dev"] +extras["deepspeed"] = ["deepspeed"] +extras["rich"] = ["rich"] + +extras["test_trackers"] = ["wandb", "comet-ml", "tensorboard", "dvclive"] +extras["dev"] = extras["quality"] + extras["testing"] + extras["rich"] + +extras["sagemaker"] = [ + "sagemaker", # boto3 is a required package in sagemaker +] + +setup( + name="accelerate", + version="0.35.0.dev0", + description="Accelerate", + long_description=open("README.md", encoding="utf-8").read(), + long_description_content_type="text/markdown", + keywords="deep learning", + license="Apache", + author="The HuggingFace team", + author_email="zach.mueller@huggingface.co", + url="https://github.com/huggingface/accelerate", + package_dir={"": "src"}, + packages=find_packages("src"), + entry_points={ + "console_scripts": [ + "accelerate=accelerate.commands.accelerate_cli:main", + "accelerate-config=accelerate.commands.config:main", + "accelerate-estimate-memory=accelerate.commands.estimate:main", + "accelerate-launch=accelerate.commands.launch:main", + "accelerate-merge-weights=accelerate.commands.merge:main", + ] + }, + python_requires=">=3.8.0", + install_requires=[ + "numpy>=1.17,<3.0.0", + "packaging>=20.0", + "psutil", + "pyyaml", + "torch>=1.10.0", + "huggingface_hub>=0.21.0", + "safetensors>=0.4.3", + ], + extras_require=extras, + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.8", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + ], +) + +# Release checklist +# 1. Checkout the release branch (for a patch the current release branch, for a new minor version, create one): +# git checkout -b vXX.xx-release +# The -b is only necessary for creation (so remove it when doing a patch) +# 2. Change the version in __init__.py and setup.py to the proper value. +# 3. Commit these changes with the message: "Release: v" +# 4. Add a tag in git to mark the release: +# git tag v -m 'Adds tag v for pypi' +# Push the tag and release commit to git: git push --tags origin vXX.xx-release +# 5. Run the following commands in the top-level directory: +# rm -rf dist +# rm -rf build +# python setup.py bdist_wheel +# python setup.py sdist +# 6. Upload the package to the pypi test server first: +# twine upload dist/* -r testpypi +# 7. Check that you can install it in a virtualenv by running: +# pip install accelerate +# pip uninstall accelerate +# pip install -i https://testpypi.python.org/pypi accelerate +# accelerate env +# accelerate test +# 8. Upload the final version to actual pypi: +# twine upload dist/* -r pypi +# 9. Add release notes to the tag in github once everything is looking hunky-dory. +# 10. Go back to the main branch and update the version in __init__.py, setup.py to the new version ".dev" and push to +# main. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/PKG-INFO b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/PKG-INFO new file mode 100644 index 0000000000000000000000000000000000000000..b19f43ff5407c8d06cb4914e90efe0b264dc54bc --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/PKG-INFO @@ -0,0 +1,388 @@ +Metadata-Version: 2.4 +Name: accelerate +Version: 0.35.0.dev0 +Summary: Accelerate +Home-page: https://github.com/huggingface/accelerate +Author: The HuggingFace team +Author-email: zach.mueller@huggingface.co +License: Apache +Keywords: deep learning +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: Intended Audience :: Education +Classifier: Intended Audience :: Science/Research +Classifier: License :: OSI Approved :: Apache Software License +Classifier: Operating System :: OS Independent +Classifier: Programming Language :: Python :: 3 +Classifier: Programming Language :: Python :: 3.8 +Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence +Requires-Python: >=3.8.0 +Description-Content-Type: text/markdown +License-File: LICENSE +Requires-Dist: numpy<3.0.0,>=1.17 +Requires-Dist: packaging>=20.0 +Requires-Dist: psutil +Requires-Dist: pyyaml +Requires-Dist: torch>=1.10.0 +Requires-Dist: huggingface_hub>=0.21.0 +Requires-Dist: safetensors>=0.4.3 +Provides-Extra: quality +Requires-Dist: black~=23.1; extra == "quality" +Requires-Dist: hf-doc-builder>=0.3.0; extra == "quality" +Requires-Dist: ruff~=0.2.1; extra == "quality" +Provides-Extra: docs +Provides-Extra: test-prod +Requires-Dist: pytest<=8.0.0,>=7.2.0; extra == "test-prod" +Requires-Dist: pytest-xdist; extra == "test-prod" +Requires-Dist: pytest-subtests; extra == "test-prod" +Requires-Dist: parameterized; extra == "test-prod" +Provides-Extra: test-dev +Requires-Dist: datasets; extra == "test-dev" +Requires-Dist: diffusers; extra == "test-dev" +Requires-Dist: evaluate; extra == "test-dev" +Requires-Dist: torchdata>=0.8.0; extra == "test-dev" +Requires-Dist: torchpippy>=0.2.0; extra == "test-dev" +Requires-Dist: transformers; extra == "test-dev" +Requires-Dist: scipy; extra == "test-dev" +Requires-Dist: scikit-learn; extra == "test-dev" +Requires-Dist: tqdm; extra == "test-dev" +Requires-Dist: bitsandbytes; extra == "test-dev" +Requires-Dist: timm; extra == "test-dev" +Provides-Extra: testing +Requires-Dist: pytest<=8.0.0,>=7.2.0; extra == "testing" +Requires-Dist: pytest-xdist; extra == "testing" +Requires-Dist: pytest-subtests; extra == "testing" +Requires-Dist: parameterized; extra == "testing" +Requires-Dist: datasets; extra == "testing" +Requires-Dist: diffusers; extra == "testing" +Requires-Dist: evaluate; extra == "testing" +Requires-Dist: torchdata>=0.8.0; extra == "testing" +Requires-Dist: torchpippy>=0.2.0; extra == "testing" +Requires-Dist: transformers; extra == "testing" +Requires-Dist: scipy; extra == "testing" +Requires-Dist: scikit-learn; extra == "testing" +Requires-Dist: tqdm; extra == "testing" +Requires-Dist: bitsandbytes; extra == "testing" +Requires-Dist: timm; extra == "testing" +Provides-Extra: deepspeed +Requires-Dist: deepspeed; extra == "deepspeed" +Provides-Extra: rich +Requires-Dist: rich; extra == "rich" +Provides-Extra: test-trackers +Requires-Dist: wandb; extra == "test-trackers" +Requires-Dist: comet-ml; extra == "test-trackers" +Requires-Dist: tensorboard; extra == "test-trackers" +Requires-Dist: dvclive; extra == "test-trackers" +Provides-Extra: dev +Requires-Dist: black~=23.1; extra == "dev" +Requires-Dist: hf-doc-builder>=0.3.0; extra == "dev" +Requires-Dist: ruff~=0.2.1; extra == "dev" +Requires-Dist: pytest<=8.0.0,>=7.2.0; extra == "dev" +Requires-Dist: pytest-xdist; extra == "dev" +Requires-Dist: pytest-subtests; extra == "dev" +Requires-Dist: parameterized; extra == "dev" +Requires-Dist: datasets; extra == "dev" +Requires-Dist: diffusers; extra == "dev" +Requires-Dist: evaluate; extra == "dev" +Requires-Dist: torchdata>=0.8.0; extra == "dev" +Requires-Dist: torchpippy>=0.2.0; extra == "dev" +Requires-Dist: transformers; extra == "dev" +Requires-Dist: scipy; extra == "dev" +Requires-Dist: scikit-learn; extra == "dev" +Requires-Dist: tqdm; extra == "dev" +Requires-Dist: bitsandbytes; extra == "dev" +Requires-Dist: timm; extra == "dev" +Requires-Dist: rich; extra == "dev" +Provides-Extra: sagemaker +Requires-Dist: sagemaker; extra == "sagemaker" +Dynamic: author +Dynamic: author-email +Dynamic: classifier +Dynamic: description +Dynamic: description-content-type +Dynamic: home-page +Dynamic: keywords +Dynamic: license +Dynamic: license-file +Dynamic: provides-extra +Dynamic: requires-dist +Dynamic: requires-python +Dynamic: summary + + + +

+
+ +
+

+ +

+ + License + Documentation + GitHub release + Contributor Covenant +

+ +

+

Run your *raw* PyTorch training script on any kind of device +

+ +

+ +

+ +## Easy to integrate + +🤗 Accelerate was created for PyTorch users who like to write the training loop of PyTorch models but are reluctant to write and maintain the boilerplate code needed to use multi-GPUs/TPU/fp16. + +🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged. + +Here is an example: + +```diff + import torch + import torch.nn.functional as F + from datasets import load_dataset ++ from accelerate import Accelerator + ++ accelerator = Accelerator() +- device = 'cpu' ++ device = accelerator.device + + model = torch.nn.Transformer().to(device) + optimizer = torch.optim.Adam(model.parameters()) + + dataset = load_dataset('my_dataset') + data = torch.utils.data.DataLoader(dataset, shuffle=True) + ++ model, optimizer, data = accelerator.prepare(model, optimizer, data) + + model.train() + for epoch in range(10): + for source, targets in data: + source = source.to(device) + targets = targets.to(device) + + optimizer.zero_grad() + + output = model(source) + loss = F.cross_entropy(output, targets) + +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() +``` + +As you can see in this example, by adding 5-lines to any standard PyTorch training script you can now run on any kind of single or distributed node setting (single CPU, single GPU, multi-GPUs and TPUs) as well as with or without mixed precision (fp8, fp16, bf16). + +In particular, the same code can then be run without modification on your local machine for debugging or your training environment. + +🤗 Accelerate even handles the device placement for you (which requires a few more changes to your code, but is safer in general), so you can even simplify your training loop further: + +```diff + import torch + import torch.nn.functional as F + from datasets import load_dataset ++ from accelerate import Accelerator + +- device = 'cpu' ++ accelerator = Accelerator() + +- model = torch.nn.Transformer().to(device) ++ model = torch.nn.Transformer() + optimizer = torch.optim.Adam(model.parameters()) + + dataset = load_dataset('my_dataset') + data = torch.utils.data.DataLoader(dataset, shuffle=True) + ++ model, optimizer, data = accelerator.prepare(model, optimizer, data) + + model.train() + for epoch in range(10): + for source, targets in data: +- source = source.to(device) +- targets = targets.to(device) + + optimizer.zero_grad() + + output = model(source) + loss = F.cross_entropy(output, targets) + +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() +``` + +Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples). + +## Launching script + +🤗 Accelerate also provides an optional CLI tool that allows you to quickly configure and test your training environment before launching the scripts. No need to remember how to use `torch.distributed.run` or to write a specific launcher for TPU training! +On your machine(s) just run: + +```bash +accelerate config +``` + +and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing + +```bash +accelerate launch my_script.py --args_to_my_script +``` + +For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo): + +```bash +accelerate launch examples/nlp_example.py +``` + +This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience. + +You can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`. + +For example, here is how to launch on two GPUs: + +```bash +accelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py +``` + +To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli). + +Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/) + +## Launching multi-CPU run using MPI + +🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well. +Once you have MPI setup on your cluster, just run: +```bash +accelerate config +``` +Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun. +Then, use `accelerate launch` with your script like: +```bash +accelerate launch examples/nlp_example.py +``` +Alternatively, you can use mpirun directly, without using the CLI like: +```bash +mpirun -np 2 python examples/nlp_example.py +``` + +## Launching training using DeepSpeed + +🤗 Accelerate supports training on single/multiple GPUs using DeepSpeed. To use it, you don't need to change anything in your training code; you can set everything using just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`. + +```python +from accelerate import Accelerator, DeepSpeedPlugin + +# deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it +# Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed +deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2) +accelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin) + +# How to save your 🤗 Transformer? +accelerator.wait_for_everyone() +unwrapped_model = accelerator.unwrap_model(model) +unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model)) +``` + +Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue. + +## Launching your training from a notebook + +🤗 Accelerate also provides a `notebook_launcher` function you can use in a notebook to launch a distributed training. This is especially useful for Colab or Kaggle notebooks with a TPU backend. Just define your training loop in a `training_function` then in your last cell, add: + +```python +from accelerate import notebook_launcher + +notebook_launcher(training_function) +``` + +An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb) + +## Why should I use 🤗 Accelerate? + +You should use 🤗 Accelerate when you want to easily run your training scripts in a distributed environment without having to renounce full control over your training loop. This is not a high-level framework above PyTorch, just a thin wrapper so you don't have to learn a new library. In fact, the whole API of 🤗 Accelerate is in one class, the `Accelerator` object. + +## Why shouldn't I use 🤗 Accelerate? + +You shouldn't use 🤗 Accelerate if you don't want to write a training loop yourself. There are plenty of high-level libraries above PyTorch that will offer you that, 🤗 Accelerate is not one of them. + +## Frameworks using 🤗 Accelerate + +If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around its capabilities, some frameworks and libraries that are built on top of 🤗 Accelerate are listed below: + +* [Amphion](https://github.com/open-mmlab/Amphion) is a toolkit for Audio, Music, and Speech Generation. Its purpose is to support reproducible research and help junior researchers and engineers get started in the field of audio, music, and speech generation research and development. +* [Animus](https://github.com/Scitator/animus) is a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them within [IExperiment](https://github.com/Scitator/animus/blob/main/animus/core.py#L76). +* [Catalyst](https://github.com/catalyst-team/catalyst#getting-started) is a PyTorch framework for Deep Learning Research and Development. It focuses on reproducibility, rapid experimentation, and codebase reuse so you can create something new rather than write yet another train loop. Catalyst provides a [Runner](https://catalyst-team.github.io/catalyst/api/core.html#runner) to connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic. +* [fastai](https://github.com/fastai/fastai#installing) is a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides a [Learner](https://docs.fast.ai/learner.html#Learner) to handle the training, fine-tuning, and inference of deep learning algorithms. +* [Finetuner](https://github.com/jina-ai/finetuner) is a service that enables models to create higher-quality embeddings for semantic search, visual similarity search, cross-modal text<->image search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses. +* [InvokeAI](https://github.com/invoke-ai/InvokeAI) is a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products. +* [Kornia](https://kornia.readthedocs.io/en/latest/get-started/introduction.html) is a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides a [Trainer](https://kornia.readthedocs.io/en/latest/x.html#kornia.x.Trainer) with the specific purpose to train and fine-tune the supported deep learning algorithms within the library. +* [Open Assistant](https://projects.laion.ai/Open-Assistant/) is a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so. +* [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centered around a general-purpose [Trainer](https://pytorch-accelerated.readthedocs.io/en/latest/trainer.html), that places a huge emphasis on simplicity and transparency; enabling users to understand exactly what is going on under the hood, but without having to write and maintain the boilerplate themselves! +* [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion. +* [torchkeras](https://github.com/lyhue1991/torchkeras) is a simple tool for training pytorch model just in a keras style, a dynamic and beautiful plot is provided in notebook to monitor your loss or metric. +* [transformers](https://github.com/huggingface/transformers) as a tool for helping train state-of-the-art machine learning models in PyTorch, Tensorflow, and JAX. (Accelerate is the backend for the PyTorch side). + + +## Installation + +This repository is tested on Python 3.8+ and PyTorch 1.10.0+ + +You should install 🤗 Accelerate in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). + +First, create a virtual environment with the version of Python you're going to use and activate it. + +Then, you will need to install PyTorch: refer to the [official installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows: + +```bash +pip install accelerate +``` + +## Supported integrations + +- CPU only +- multi-CPU on one node (machine) +- multi-CPU on several nodes (machines) +- single GPU +- multi-GPU on one node (machine) +- multi-GPU on several nodes (machines) +- TPU +- FP16/BFloat16 mixed precision +- FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/) +- DeepSpeed support (Experimental) +- PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental) +- Megatron-LM support (Experimental) + +## Citing 🤗 Accelerate + +If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry. + +```bibtex +@Misc{accelerate, + title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.}, + author = {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan}, + howpublished = {\url{https://github.com/huggingface/accelerate}}, + year = {2022} +} +``` diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/SOURCES.txt b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/SOURCES.txt new file mode 100644 index 0000000000000000000000000000000000000000..e763988e430bf79992e082d14776262f87f0a832 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/SOURCES.txt @@ -0,0 +1,113 @@ +LICENSE +README.md +pyproject.toml +setup.py +src/accelerate/__init__.py +src/accelerate/accelerator.py +src/accelerate/big_modeling.py +src/accelerate/checkpointing.py +src/accelerate/data_loader.py +src/accelerate/hooks.py +src/accelerate/inference.py +src/accelerate/launchers.py +src/accelerate/local_sgd.py +src/accelerate/logging.py +src/accelerate/memory_utils.py +src/accelerate/optimizer.py +src/accelerate/scheduler.py +src/accelerate/state.py +src/accelerate/tracking.py +src/accelerate.egg-info/PKG-INFO +src/accelerate.egg-info/SOURCES.txt +src/accelerate.egg-info/dependency_links.txt +src/accelerate.egg-info/entry_points.txt +src/accelerate.egg-info/requires.txt +src/accelerate.egg-info/top_level.txt +src/accelerate/commands/__init__.py +src/accelerate/commands/accelerate_cli.py +src/accelerate/commands/env.py +src/accelerate/commands/estimate.py +src/accelerate/commands/launch.py +src/accelerate/commands/merge.py +src/accelerate/commands/test.py +src/accelerate/commands/tpu.py +src/accelerate/commands/utils.py +src/accelerate/commands/config/__init__.py +src/accelerate/commands/config/cluster.py +src/accelerate/commands/config/config.py +src/accelerate/commands/config/config_args.py +src/accelerate/commands/config/config_utils.py +src/accelerate/commands/config/default.py +src/accelerate/commands/config/sagemaker.py +src/accelerate/commands/config/update.py +src/accelerate/commands/menu/__init__.py +src/accelerate/commands/menu/cursor.py +src/accelerate/commands/menu/helpers.py +src/accelerate/commands/menu/input.py +src/accelerate/commands/menu/keymap.py +src/accelerate/commands/menu/selection_menu.py +src/accelerate/test_utils/__init__.py +src/accelerate/test_utils/examples.py +src/accelerate/test_utils/testing.py +src/accelerate/test_utils/training.py +src/accelerate/test_utils/scripts/__init__.py +src/accelerate/test_utils/scripts/test_cli.py +src/accelerate/test_utils/scripts/test_ddp_comm_hook.py +src/accelerate/test_utils/scripts/test_distributed_data_loop.py +src/accelerate/test_utils/scripts/test_merge_weights.py +src/accelerate/test_utils/scripts/test_notebook.py +src/accelerate/test_utils/scripts/test_ops.py +src/accelerate/test_utils/scripts/test_script.py +src/accelerate/test_utils/scripts/test_sync.py +src/accelerate/test_utils/scripts/external_deps/__init__.py +src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py +src/accelerate/test_utils/scripts/external_deps/test_metrics.py +src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py +src/accelerate/test_utils/scripts/external_deps/test_performance.py +src/accelerate/test_utils/scripts/external_deps/test_pippy.py +src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py +src/accelerate/utils/__init__.py +src/accelerate/utils/bnb.py +src/accelerate/utils/constants.py +src/accelerate/utils/dataclasses.py +src/accelerate/utils/deepspeed.py +src/accelerate/utils/environment.py +src/accelerate/utils/fsdp_utils.py +src/accelerate/utils/imports.py +src/accelerate/utils/launch.py +src/accelerate/utils/megatron_lm.py +src/accelerate/utils/memory.py +src/accelerate/utils/modeling.py +src/accelerate/utils/offload.py +src/accelerate/utils/operations.py +src/accelerate/utils/other.py +src/accelerate/utils/random.py +src/accelerate/utils/rich.py +src/accelerate/utils/torch_xla.py +src/accelerate/utils/tqdm.py +src/accelerate/utils/transformer_engine.py +src/accelerate/utils/versions.py +tests/test_accelerator.py +tests/test_big_modeling.py +tests/test_cli.py +tests/test_cpu.py +tests/test_data_loader.py +tests/test_examples.py +tests/test_grad_sync.py +tests/test_hooks.py +tests/test_imports.py +tests/test_kwargs_handlers.py +tests/test_logging.py +tests/test_memory_utils.py +tests/test_metrics.py +tests/test_modeling_utils.py +tests/test_multigpu.py +tests/test_offload.py +tests/test_optimizer.py +tests/test_quantization.py +tests/test_sagemaker.py +tests/test_scheduler.py +tests/test_state_checkpointing.py +tests/test_tpu.py +tests/test_tracking.py +tests/test_utils.py \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/dependency_links.txt b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/dependency_links.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b137891791fe96927ad78e64b0aad7bded08bdc --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/dependency_links.txt @@ -0,0 +1 @@ + diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/entry_points.txt b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/entry_points.txt new file mode 100644 index 0000000000000000000000000000000000000000..8b9bf6b798b250a47a3febdf0e32c88507fbf86d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/entry_points.txt @@ -0,0 +1,6 @@ +[console_scripts] +accelerate = accelerate.commands.accelerate_cli:main +accelerate-config = accelerate.commands.config:main +accelerate-estimate-memory = accelerate.commands.estimate:main +accelerate-launch = accelerate.commands.launch:main +accelerate-merge-weights = accelerate.commands.merge:main diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/requires.txt b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/requires.txt new file mode 100644 index 0000000000000000000000000000000000000000..b46dedf51817512f3916b4bc6cac265e0e8e2ac1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/requires.txt @@ -0,0 +1,86 @@ +numpy<3.0.0,>=1.17 +packaging>=20.0 +psutil +pyyaml +torch>=1.10.0 +huggingface_hub>=0.21.0 +safetensors>=0.4.3 + +[deepspeed] +deepspeed + +[dev] +black~=23.1 +hf-doc-builder>=0.3.0 +ruff~=0.2.1 +pytest<=8.0.0,>=7.2.0 +pytest-xdist +pytest-subtests +parameterized +datasets +diffusers +evaluate +torchdata>=0.8.0 +torchpippy>=0.2.0 +transformers +scipy +scikit-learn +tqdm +bitsandbytes +timm +rich + +[docs] + +[quality] +black~=23.1 +hf-doc-builder>=0.3.0 +ruff~=0.2.1 + +[rich] +rich + +[sagemaker] +sagemaker + +[test_dev] +datasets +diffusers +evaluate +torchdata>=0.8.0 +torchpippy>=0.2.0 +transformers +scipy +scikit-learn +tqdm +bitsandbytes +timm + +[test_prod] +pytest<=8.0.0,>=7.2.0 +pytest-xdist +pytest-subtests +parameterized + +[test_trackers] +wandb +comet-ml +tensorboard +dvclive + +[testing] +pytest<=8.0.0,>=7.2.0 +pytest-xdist +pytest-subtests +parameterized +datasets +diffusers +evaluate +torchdata>=0.8.0 +torchpippy>=0.2.0 +transformers +scipy +scikit-learn +tqdm +bitsandbytes +timm diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/top_level.txt b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/top_level.txt new file mode 100644 index 0000000000000000000000000000000000000000..a9368375be0e0e13fdad0eea4b92541bd9e1f594 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate.egg-info/top_level.txt @@ -0,0 +1 @@ +accelerate diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/__init__.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..bc36acf7fec37d74e62e37fd0edda2d01b300488 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/__init__.py @@ -0,0 +1,50 @@ +# 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. +__version__ = "0.35.0.dev0" + +from .accelerator import Accelerator +from .big_modeling import ( + cpu_offload, + cpu_offload_with_hook, + disk_offload, + dispatch_model, + init_empty_weights, + init_on_device, + load_checkpoint_and_dispatch, +) +from .data_loader import skip_first_batches +from .inference import prepare_pippy +from .launchers import debug_launcher, notebook_launcher +from .state import PartialState +from .utils import ( + AutocastKwargs, + DataLoaderConfiguration, + DDPCommunicationHookType, + DeepSpeedPlugin, + DistributedDataParallelKwargs, + DistributedType, + FullyShardedDataParallelPlugin, + GradScalerKwargs, + InitProcessGroupKwargs, + ProfileKwargs, + find_executable_batch_size, + infer_auto_device_map, + is_rich_available, + load_checkpoint_in_model, + synchronize_rng_states, +) + + +if is_rich_available(): + from .utils import rich diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/accelerator.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/accelerator.py new file mode 100644 index 0000000000000000000000000000000000000000..ea17a060046872b2e959628350d8d391e5037009 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/accelerator.py @@ -0,0 +1,3562 @@ +# 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. + +from __future__ import annotations + +import contextlib +import functools +import json +import math +import os +import re +import shutil +import sys +import warnings +from collections import OrderedDict +from contextlib import contextmanager +from functools import partial +from types import MethodType +from typing import Any, Callable, Union + +import torch +import torch.utils.hooks as hooks +from huggingface_hub import split_torch_state_dict_into_shards + +from .checkpointing import load_accelerator_state, load_custom_state, save_accelerator_state, save_custom_state +from .data_loader import DataLoaderDispatcher, prepare_data_loader, skip_first_batches +from .hooks import AlignDevicesHook +from .logging import get_logger +from .optimizer import AcceleratedOptimizer +from .scheduler import AcceleratedScheduler +from .state import AcceleratorState, GradientState, PartialState +from .tracking import LOGGER_TYPE_TO_CLASS, GeneralTracker, filter_trackers +from .utils import ( + MODEL_NAME, + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + SAFE_WEIGHTS_PATTERN_NAME, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + WEIGHTS_PATTERN_NAME, + AutocastKwargs, + DataLoaderConfiguration, + DeepSpeedPlugin, + DistributedDataParallelKwargs, + DistributedType, + DynamoBackend, + FP8RecipeKwargs, + FullyShardedDataParallelPlugin, + GradientAccumulationPlugin, + GradScalerKwargs, + InitProcessGroupKwargs, + KwargsHandler, + LoggerType, + MegatronLMPlugin, + PrecisionType, + ProfileKwargs, + ProjectConfiguration, + RNGType, + TorchDynamoPlugin, + apply_fp8_autowrap, + check_os_kernel, + clean_state_dict_for_safetensors, + compare_versions, + convert_model, + convert_outputs_to_fp32, + extract_model_from_parallel, + gather, + gather_object, + get_mixed_precision_context_manager, + get_pretty_name, + is_bf16_available, + is_deepspeed_available, + is_ipex_available, + is_lomo_available, + is_megatron_lm_available, + is_mlu_available, + is_msamp_available, + is_musa_available, + is_npu_available, + is_torch_version, + is_torch_xla_available, + is_transformer_engine_available, + is_xpu_available, + load_fsdp_model, + load_fsdp_optimizer, + pad_across_processes, + parse_choice_from_env, + recursively_apply, + reduce, + release_memory, + save, + save_fsdp_model, + save_fsdp_optimizer, + wait_for_everyone, +) +from .utils.constants import FSDP_PYTORCH_VERSION, PROFILE_PATTERN_NAME +from .utils.modeling import get_state_dict_offloaded_model +from .utils.other import is_compiled_module + + +if is_deepspeed_available(): + from .utils import ( + DeepSpeedEngineWrapper, + DeepSpeedOptimizerWrapper, + DeepSpeedSchedulerWrapper, + DummyOptim, + DummyScheduler, + ) + +if is_megatron_lm_available(): + from .utils import ( + MegatronEngine, + MegatronLMDummyDataLoader, + MegatronLMDummyScheduler, + MegatronLMOptimizerWrapper, + MegatronLMSchedulerWrapper, + megatron_lm_initialize, + megatron_lm_prepare_data_loader, + megatron_lm_prepare_model_optimizer_scheduler, + ) + +from torch.distributed.algorithms.join import Join + + +if is_torch_xla_available(): + import torch_xla.amp as xamp + import torch_xla.core.xla_model as xm + import torch_xla.distributed.xla_multiprocessing as xmp + + +if is_npu_available(check_device=False): + import torch_npu # noqa: F401 + + +try: + from torch.optim.lr_scheduler import LRScheduler +except ImportError: + from torch.optim.lr_scheduler import _LRScheduler as LRScheduler + +logger = get_logger(__name__) + +# Sentinel values for defaults +_split_batches = object() +_dispatch_batches = object() +_even_batches = object() +_use_seedable_sampler = object() + + +class Accelerator: + """ + Creates an instance of an accelerator for distributed training (on multi-GPU, TPU) or mixed precision training. + + Args: + device_placement (`bool`, *optional*, defaults to `True`): + Whether or not the accelerator should put objects on device (tensors yielded by the dataloader, model, + etc...). + mixed_precision (`str`, *optional*): + Whether or not to use mixed precision training. Choose from 'no','fp16','bf16' or 'fp8'. Will default to + the value in the environment variable `ACCELERATE_MIXED_PRECISION`, which will use the default value in the + accelerate config of the current system or the flag passed with the `accelerate.launch` command. 'fp8' + requires the installation of transformers-engine. + gradient_accumulation_steps (`int`, *optional*, default to 1): + The number of steps that should pass before gradients are accumulated. A number > 1 should be combined with + `Accelerator.accumulate`. If not passed, will default to the value in the environment variable + `ACCELERATE_GRADIENT_ACCUMULATION_STEPS`. Can also be configured through a `GradientAccumulationPlugin`. + cpu (`bool`, *optional*): + Whether or not to force the script to execute on CPU. Will ignore GPU available if set to `True` and force + the execution on one process only. + dataloader_config (`DataLoaderConfiguration`, *optional*): + A configuration for how the dataloaders should be handled in distributed scenarios. + deepspeed_plugin ([`~utils.DeepSpeedPlugin`], *optional*): + Tweak your DeepSpeed related args using this argument. This argument is optional and can be configured + directly using *accelerate config* + fsdp_plugin ([`~utils.FullyShardedDataParallelPlugin`], *optional*): + Tweak your FSDP related args using this argument. This argument is optional and can be configured directly + using *accelerate config* + megatron_lm_plugin ([`~utils.MegatronLMPlugin`], *optional*): + Tweak your MegatronLM related args using this argument. This argument is optional and can be configured + directly using *accelerate config* + rng_types (list of `str` or [`~utils.RNGType`]): + The list of random number generators to synchronize at the beginning of each iteration in your prepared + dataloaders. Should be one or several of: + + - `"torch"`: the base torch random number generator + - `"cuda"`: the CUDA random number generator (GPU only) + - `"xla"`: the XLA random number generator (TPU only) + - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your + dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type. + + Will default to `["torch"]` for PyTorch versions <=1.5.1 and `["generator"]` for PyTorch versions >= 1.6. + log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*): + A list of loggers to be setup for experiment tracking. Should be one or several of: + + - `"all"` + - `"tensorboard"` + - `"wandb"` + - `"comet_ml"` + If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can + also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`. + project_config ([`~utils.ProjectConfiguration`], *optional*): + A configuration for how saving the state can be handled. + project_dir (`str`, `os.PathLike`, *optional*): + A path to a directory for storing data such as logs of locally-compatible loggers and potentially saved + checkpoints. + step_scheduler_with_optimizer (`bool`, *optional*, defaults to `True`): + Set `True` if the learning rate scheduler is stepped at the same time as the optimizer, `False` if only + done under certain circumstances (at the end of each epoch, for instance). + kwargs_handlers (list of [`~utils.KwargsHandler`], *optional*) + A list of [`~utils.KwargsHandler`] to customize how the objects related to distributed training, profiling + or mixed precision are created. See [kwargs](kwargs) for more information. + dynamo_backend (`str` or [`~utils.DynamoBackend`], *optional*, defaults to `"no"`): + Set to one of the possible dynamo backends to optimize your training with torch dynamo. + gradient_accumulation_plugin ([`~utils.GradientAccumulationPlugin`], *optional*): + A configuration for how gradient accumulation should be handled, if more tweaking than just the + `gradient_accumulation_steps` is needed. + + **Available attributes:** + + - **device** (`torch.device`) -- The device to use. + - **distributed_type** ([`~utils.DistributedType`]) -- The distributed training configuration. + - **local_process_index** (`int`) -- The process index on the current machine. + - **mixed_precision** (`str`) -- The configured mixed precision mode. + - **num_processes** (`int`) -- The total number of processes used for training. + - **optimizer_step_was_skipped** (`bool`) -- Whether or not the optimizer update was skipped (because of + gradient overflow in mixed precision), in which + case the learning rate should not be changed. + - **process_index** (`int`) -- The overall index of the current process among all processes. + - **state** ([`~state.AcceleratorState`]) -- The distributed setup state. + - **sync_gradients** (`bool`) -- Whether the gradients are currently being synced across all processes. + - **use_distributed** (`bool`) -- Whether the current configuration is for distributed training. + """ + + def __init__( + self, + device_placement: bool = True, + split_batches: bool = _split_batches, + mixed_precision: PrecisionType | str | None = None, + gradient_accumulation_steps: int = 1, + cpu: bool = False, + dataloader_config: DataLoaderConfiguration | None = None, + deepspeed_plugin: DeepSpeedPlugin | None = None, + fsdp_plugin: FullyShardedDataParallelPlugin | None = None, + megatron_lm_plugin: MegatronLMPlugin | None = None, + rng_types: list[str | RNGType] | None = None, + log_with: str | LoggerType | GeneralTracker | list[str | LoggerType | GeneralTracker] | None = None, + project_dir: str | os.PathLike | None = None, + project_config: ProjectConfiguration | None = None, + gradient_accumulation_plugin: GradientAccumulationPlugin | None = None, + dispatch_batches: bool | None = _dispatch_batches, + even_batches: bool = _even_batches, + use_seedable_sampler: bool = _use_seedable_sampler, + step_scheduler_with_optimizer: bool = True, + kwargs_handlers: list[KwargsHandler] | None = None, + dynamo_backend: DynamoBackend | str | None = None, + ): + self.trackers = [] + if project_config is not None: + self.project_configuration = project_config + else: + self.project_configuration = ProjectConfiguration(project_dir=project_dir) + if project_dir is not None and self.project_dir is None: + self.project_configuration.set_directories(project_dir) + if mixed_precision is not None: + mixed_precision = str(mixed_precision) + if mixed_precision not in PrecisionType: + raise ValueError( + f"Unknown mixed_precision mode: {mixed_precision}. Choose between {PrecisionType.list()}" + ) + + dynamo_plugin = TorchDynamoPlugin() if dynamo_backend is None else TorchDynamoPlugin(backend=dynamo_backend) + + if deepspeed_plugin is None: # init from env variables + deepspeed_plugin = ( + DeepSpeedPlugin() if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true" else None + ) + else: + assert isinstance( + deepspeed_plugin, DeepSpeedPlugin + ), "`deepspeed_plugin` must be an `accelerate.utils.DeepSpeedPlugin` object." + os.environ["ACCELERATE_USE_DEEPSPEED"] = "true" # use DeepSpeed if plugin is provided + if deepspeed_plugin: + if not is_deepspeed_available(): + raise ImportError("DeepSpeed is not installed => run `pip install deepspeed` or build it from source.") + if is_mlu_available(): + if compare_versions("deepspeed-mlu", "<", "0.10.1"): + raise ImportError("DeepSpeed MLU version must be >= 0.10.1. Please update DeepSpeed MLU.") + elif is_musa_available(): + if compare_versions("deepspeed", ">", "0.14.3"): + raise ImportError("DeepSpeed MUSA version must be <= 0.14.3. Please downgrade DeepSpeed.") + elif compare_versions("deepspeed", "<", "0.9.3"): + raise ImportError("DeepSpeed version must be >= 0.9.3. Please update DeepSpeed.") + + mixed_precision = ( + os.environ.get("ACCELERATE_MIXED_PRECISION", "no") if mixed_precision is None else mixed_precision + ) + deepspeed_plugin.set_mixed_precision(mixed_precision) + deepspeed_plugin.set_deepspeed_weakref() + + if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" or isinstance( + fsdp_plugin, FullyShardedDataParallelPlugin + ): + if not is_torch_version(">=", FSDP_PYTORCH_VERSION): + raise ValueError(f"FSDP requires PyTorch >= {FSDP_PYTORCH_VERSION}") + + if fsdp_plugin is None: # init from env variables + fsdp_plugin = ( + FullyShardedDataParallelPlugin() if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" else None + ) + else: + if not isinstance(fsdp_plugin, FullyShardedDataParallelPlugin): + raise TypeError("`fsdp_plugin` must be a FullyShardedDataParallelPlugin object.") + os.environ["ACCELERATE_USE_FSDP"] = "true" # use FSDP if plugin is provided + + if megatron_lm_plugin is None: # init from env variables + megatron_lm_plugin = ( + MegatronLMPlugin() if os.environ.get("ACCELERATE_USE_MEGATRON_LM", "false") == "true" else None + ) + else: + if not isinstance(megatron_lm_plugin, MegatronLMPlugin): + raise TypeError("`megatron_lm_plugin` must be a MegatronLMPlugin object.") + os.environ["ACCELERATE_USE_MEGATRON_LM"] = "true" # use MegatronLM if plugin is provided + + if megatron_lm_plugin: + if not is_megatron_lm_available(): + raise ImportError("Megatron is not installed. please build it from source.") + + # Kwargs handlers + self.ddp_handler = None + self.scaler_handler = None + self.init_handler = None + self.fp8_recipe_handler = None + self.autocast_handler = None + self.profile_handler = None + self.has_lomo_optimizer = False + + if kwargs_handlers is not None: + for handler in kwargs_handlers: + assert isinstance( + handler, KwargsHandler + ), f"Unsupported kwargs handler passed: {handler}, must be one that inherits `accelerate.utils.KwargsHandler`." + if isinstance(handler, DistributedDataParallelKwargs): + if self.ddp_handler is not None: + raise ValueError("You can only pass one `DistributedDataParallelKwargs` in `kwargs_handler`.") + else: + self.ddp_handler = handler + elif isinstance(handler, GradScalerKwargs): + if self.scaler_handler is not None: + raise ValueError("You can only pass one `GradScalerKwargs` in `kwargs_handler`.") + else: + self.scaler_handler = handler + elif isinstance(handler, InitProcessGroupKwargs): + if self.init_handler is not None: + raise ValueError("You can only pass one `InitProcessGroupKwargs` in `kwargs_handler`.") + else: + self.init_handler = handler + elif isinstance(handler, FP8RecipeKwargs): + if self.fp8_recipe_handler is not None: + raise ValueError("You can only pass one `FP8RecipeKwargs` in `kwargs_handler`.") + else: + self.fp8_recipe_handler = handler + elif isinstance(handler, AutocastKwargs): + if self.autocast_handler is not None: + raise ValueError("You can only pass one `AutocastKwargs` in `kwargs_handler`.") + else: + self.autocast_handler = handler + elif isinstance(handler, ProfileKwargs): + if self.profile_handler is not None: + raise ValueError("You can only pass one `ProfileKwargs` in `kwargs_handler`.") + else: + self.profile_handler = handler + + kwargs = self.init_handler.to_kwargs() if self.init_handler is not None else {} + self.state = AcceleratorState( + mixed_precision=mixed_precision, + cpu=cpu, + dynamo_plugin=dynamo_plugin, + deepspeed_plugin=deepspeed_plugin, + fsdp_plugin=fsdp_plugin, + megatron_lm_plugin=megatron_lm_plugin, + _from_accelerator=True, + **kwargs, + ) + + if self.state.mixed_precision == "fp8" and self.fp8_recipe_handler is None: + self.fp8_recipe_handler = FP8RecipeKwargs() + + self.delayed_fp8_autocast = False + if self.fp8_recipe_handler is not None: + # We already check if FP8 is available during `self.state` + if self.state.mixed_precision != "fp8" and ( + self.distributed_type not in (DistributedType.FSDP, DistributedType.DEEPSPEED) + ): + raise ValueError("Passing in a `FP8RecipeKwargs` object requires setting `mixed_precision='fp8'`.") + self.delayed_fp8_autocast = self.fp8_recipe_handler.backend == "TE" and self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.FSDP, + ) + + trackers = filter_trackers(log_with, self.logging_dir) + if len(trackers) < 1 and log_with is not None: + warnings.warn(f"`log_with={log_with}` was passed but no supported trackers are currently installed.") + self.log_with = trackers + + if ( + (mixed_precision != "bf16") + and getattr(self.state, "downcast_bfloat", False) + and (self.state.distributedType != DistributedType.XLA) + ): + raise ValueError("Can only use `downcast_bf16` when using `mixed_precision='bf16'` and on a TPU") + + if gradient_accumulation_plugin is not None: + if gradient_accumulation_steps != 1: + raise ValueError( + "You can only pass one of `gradient_accumulation_steps` and `gradient_accumulation_plugin`. Please only pass in the created `GradientAccumulationPlugin` object." + ) + else: + gradient_accumulation_steps = int( + parse_choice_from_env("ACCELERATE_GRADIENT_ACCUMULATION_STEPS", gradient_accumulation_steps) + ) + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=gradient_accumulation_steps) + self.gradient_state = GradientState( + gradient_accumulation_plugin=gradient_accumulation_plugin, + ) + + self.device_placement = device_placement + if dataloader_config is None: + dataloader_config = DataLoaderConfiguration() + self.dataloader_config = dataloader_config + # Deal with deprecated args + # TODO: Remove in v1.0.0 + deprecated_dl_args = {} + if dispatch_batches is not _dispatch_batches: + deprecated_dl_args["dispatch_batches"] = dispatch_batches + self.dataloader_config.dispatch_batches = dispatch_batches + if split_batches is not _split_batches: + deprecated_dl_args["split_batches"] = split_batches + self.dataloader_config.split_batches = split_batches + if even_batches is not _even_batches: + deprecated_dl_args["even_batches"] = even_batches + self.dataloader_config.even_batches = even_batches + if use_seedable_sampler is not _use_seedable_sampler: + deprecated_dl_args["use_seedable_sampler"] = use_seedable_sampler + self.dataloader_config.use_seedable_sampler = use_seedable_sampler + if len(deprecated_dl_args) > 0: + values = ", ".join([f"{k}={v}" for k, v in deprecated_dl_args.items()]) + warnings.warn( + f"Passing the following arguments to `Accelerator` is deprecated and will be removed in version 1.0 of Accelerate: {deprecated_dl_args.keys()}. " + "Please pass an `accelerate.DataLoaderConfiguration` instead: \n" + f"dataloader_config = DataLoaderConfiguration({values})", + FutureWarning, + ) + self.step_scheduler_with_optimizer = step_scheduler_with_optimizer + + # Mixed precision attributes + self.scaler = None + self.native_amp = False + if ( + self.state.mixed_precision == "fp16" + and self.device.type != "cpu" + and self.distributed_type not in (DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM) + ): + self.native_amp = True + if self.device.type not in ("xpu", "cuda", "npu", "xla", "mlu", "musa") or is_torch_xla_available( + check_is_tpu=True + ): + raise ValueError(f"fp16 mixed precision requires a GPU (not {self.device.type!r}).") + kwargs = self.scaler_handler.to_kwargs() if self.scaler_handler is not None else {} + if self.distributed_type == DistributedType.FSDP: + from torch.distributed.fsdp.sharded_grad_scaler import ShardedGradScaler + + self.scaler = ShardedGradScaler(**kwargs) + elif is_torch_xla_available(check_is_gpu=True): + self.scaler = xamp.GradScaler(**kwargs) + elif is_mlu_available(): + self.scaler = torch.mlu.amp.GradScaler(**kwargs) + elif is_musa_available(): + self.scalar = torch.musa.amp.GradScaler(**kwargs) + elif is_npu_available(): + self.scaler = torch.npu.amp.GradScaler(**kwargs) + elif is_xpu_available(): + self.scaler = torch.amp.GradScaler("xpu", **kwargs) + else: + self.scaler = torch.cuda.amp.GradScaler(**kwargs) + + elif self.state.mixed_precision == "bf16" and self.distributed_type not in ( + DistributedType.DEEPSPEED, + DistributedType.MEGATRON_LM, + ): + if self.device.type in ["cpu", "xpu"]: + self.native_amp = True + else: + self.native_amp = is_bf16_available(True) + if mixed_precision == "bf16" and not self.native_amp and not is_torch_xla_available(): + raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.") + + elif self.state.mixed_precision == "fp8": + # We always enable `native_amp` for FP8 + self.native_amp = True + + # Start of internal step tracking + self.step = 0 + + # Internal references to the training objects + self._optimizers = [] + self._models = [] + self._schedulers = [] + self._dataloaders = [] + self._custom_objects = [] + + # Hooks + self._load_model_state_pre_hook = OrderedDict() + self._save_model_state_pre_hook = OrderedDict() + + # RNG Types + self.rng_types = rng_types + if self.rng_types is None: + self.rng_types = ["generator"] + + # Set a flag tensor for early stopping and other breakpoints + self.flag_tensor = None + + check_os_kernel() + + @property + def use_distributed(self): + """ + Whether the Accelerator is configured for distributed training + """ + return self.state.use_distributed + + @property + def distributed_type(self): + return self.state.distributed_type + + @property + def num_processes(self): + return self.state.num_processes + + @property + def process_index(self): + return self.state.process_index + + @property + def local_process_index(self): + return self.state.local_process_index + + @property + def device(self): + return self.state.device + + @property + def split_batches(self): + return self.dataloader_config.split_batches + + @property + def dispatch_batches(self): + return self.dataloader_config.dispatch_batches + + @property + def even_batches(self): + return self.dataloader_config.even_batches + + @even_batches.setter + def even_batches(self, value: bool): + self.dataloader_config.even_batches = value + + @property + def use_seedable_sampler(self): + return self.dataloader_config.use_seedable_sampler + + @property + def non_blocking(self): + return self.dataloader_config.non_blocking + + @property + def use_stateful_dataloader(self): + if hasattr(self.dataloader_config, "use_stateful_dataloader"): + return self.dataloader_config.use_stateful_dataloader + return False + + @property + def project_dir(self): + return self.project_configuration.project_dir + + @property + def logging_dir(self): + return self.project_configuration.logging_dir + + @property + def save_iteration(self): + return self.project_configuration.iteration + + @property + def is_main_process(self): + """True for one process only.""" + return self.state.is_main_process + + @property + def is_local_main_process(self): + """True for one process per server.""" + return self.state.is_local_main_process + + @property + def use_fp16(self): + warnings.warn( + "The `use_fp16` property is deprecated and will be removed in version 1.0 of Accelerate use " + "`Accelerator.mixed_precision == 'fp16'` instead.", + FutureWarning, + ) + return self.mixed_precision != "no" + + @property + def is_last_process(self): + return self.process_index == self.num_processes - 1 + + @property + def mixed_precision(self): + return self.state.mixed_precision + + @contextmanager + def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False): + """ + Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing + distributed inference, such as with different prompts. + + Note that when using a `dict`, all keys need to have the same number of elements. + + Args: + inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`): + The input to split between processes. + apply_padding (`bool`, `optional`, defaults to `False`): + Whether to apply padding by repeating the last element of the input so that all processes have the same + number of elements. Useful when trying to perform actions such as `Accelerator.gather()` on the outputs + or passing in less inputs than there are processes. If so, just remember to drop the padded elements + afterwards. + + Example: + + ```python + # Assume there are two processes + from accelerate import Accelerator + + accelerator = Accelerator() + with accelerator.split_between_processes(["A", "B", "C"]) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C"] + + with accelerator.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C", "C"] + ``` + """ + with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs: + yield inputs + + def on_main_process(self, function: Callable[..., Any] = None): + """ + A decorator that will run the decorated function on the main process only. Can also be called using the + `PartialState` class. + + Args: + function (`Callable`): The function to decorate. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + + + >>> @accelerator.on_main_process + ... def print_something(): + ... print("This will be printed by process 0 only.") + + + >>> print_something() + "This will be printed by process 0 only" + ``` + """ + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_main_process(function)(*args, **kwargs) + + return _inner + + def on_local_main_process(self, function: Callable[..., Any] = None): + """ + A decorator that will run the decorated function on the local main process only. Can also be called using the + `PartialState` class. + + Args: + function (`Callable`): The function to decorate. + + Example: + ```python + # Assume we have 2 servers with 4 processes each. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_local_main_process + def print_something(): + print("This will be printed by process 0 only on each server.") + + + print_something() + # On server 1: + "This will be printed by process 0 only" + # On server 2: + "This will be printed by process 0 only" + ``` + """ + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_local_main_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_local_main_process(function)(*args, **kwargs) + + return _inner + + def on_last_process(self, function: Callable[..., Any]): + """ + A decorator that will run the decorated function on the last process only. Can also be called using the + `PartialState` class. + + Args: + function (`Callable`): The function to decorate. + + Example: + ```python + # Assume we have 4 processes. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_last_process + def print_something(): + print(f"Printed on process {accelerator.process_index}") + + + print_something() + "Printed on process 3" + ``` + """ + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_last_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_last_process(function)(*args, **kwargs) + + return _inner + + def on_process(self, function: Callable[..., Any] = None, process_index: int = None): + """ + A decorator that will run the decorated function on a given process index only. Can also be called using the + `PartialState` class. + + Args: + function (`Callable`, `optional`): + The function to decorate. + process_index (`int`, `optional`): + The index of the process on which to run the function. + + Example: + ```python + # Assume we have 4 processes. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_process(process_index=2) + def print_something(): + print(f"Printed on process {accelerator.process_index}") + + + print_something() + "Printed on process 2" + ``` + """ + # Initial construction of the decorator. + if (self is not None) and (process_index is not None) and (function is None): + return partial(self.on_process, process_index=process_index) + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_process(function, process_index)(*args, **kwargs) + + return _inner + + def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None): + """ + A decorator that will run the decorated function on a given local process index only. Can also be called using + the `PartialState` class. + + Args: + function (`Callable`, *optional*): + The function to decorate. + local_process_index (`int`, *optional*): + The index of the local process on which to run the function. + + Example: + ```python + # Assume we have 2 servers with 4 processes each. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_local_process(local_process_index=2) + def print_something(): + print(f"Printed on process {accelerator.local_process_index}") + + + print_something() + # On server 1: + "Printed on process 2" + # On server 2: + "Printed on process 2" + ``` + """ + # Initial construction of the decorator. + if (self is not None) and (local_process_index is not None) and (function is None): + return partial(self.on_local_process, local_process_index=local_process_index) + # For times when the `Accelerator` object itself utilizes this decorator. + if function is None: + if "Accelerator." in self.__qualname__: + function = self + else: + raise ValueError( + "The `on_main_process` decorator must be called with a function on an instantiated `Accelerator` object." + ) + + def _inner(*args, **kwargs): + return PartialState().on_local_process(function, local_process_index)(*args, **kwargs) + + return _inner + + @contextmanager + def main_process_first(self): + """ + Lets the main process go first inside a with block. + + The other processes will enter the with block after the main process exits. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> with accelerator.main_process_first(): + ... # This will be printed first by process 0 then in a seemingly + ... # random order by the other processes. + ... print(f"This will be printed by process {accelerator.process_index}") + ``` + """ + with self.state.main_process_first(): + yield + + @contextmanager + def local_main_process_first(self): + """ + Lets the local main process go inside a with block. + + The other processes will enter the with block after the main process exits. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> with accelerator.local_main_process_first(): + ... # This will be printed first by local process 0 then in a seemingly + ... # random order by the other processes. + ... print(f"This will be printed by process {accelerator.local_process_index}") + ``` + """ + with self.state.local_main_process_first(): + yield + + @contextmanager + def no_sync(self, model): + """ + A context manager to disable gradient synchronizations across DDP processes by calling + `torch.nn.parallel.DistributedDataParallel.no_sync`. + + If `model` is not in DDP, this context manager does nothing + + Args: + model (`torch.nn.Module`): + PyTorch Module that was prepared with `Accelerator.prepare` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer) + >>> input_a = next(iter(dataloader)) + >>> input_b = next(iter(dataloader)) + + >>> with accelerator.no_sync(): + ... outputs = model(input_a) + ... loss = loss_func(outputs) + ... accelerator.backward(loss) + ... # No synchronization across processes, only accumulate gradients + >>> outputs = model(input_b) + >>> accelerator.backward(loss) + >>> # Synchronization across all processes + >>> optimizer.step() + >>> optimizer.zero_grad() + ``` + """ + context = contextlib.nullcontext + if self.use_distributed: + context = getattr(model, "no_sync", context) + + with context(): + yield + + @staticmethod + @contextmanager + def trigger_sync_in_backward(model): + """Trigger the sync of the gradients in the next backward pass of the model after multiple forward passes under + `Accelerator.no_sync` (only applicable in multi-GPU scenarios). + + If the script is not launched in distributed mode, this context manager does nothing. + + Args: + model (`torch.nn.Module`): + The model for which to trigger the gradient synchronization. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> dataloader, model, optimizer = accelerator.prepare(dataloader, model, optimizer) + + >>> with accelerator.no_sync(): + ... loss_a = loss_func(model(input_a)) # first forward pass + ... loss_b = loss_func(model(input_b)) # second forward pass + >>> accelerator.backward(loss_a) # No synchronization across processes, only accumulate gradients + >>> with accelerator.trigger_sync_in_backward(model): + ... accelerator.backward(loss_b) # Synchronization across all processes + >>> optimizer.step() + >>> optimizer.zero_grad() + ``` + """ + if not isinstance(model, torch.nn.parallel.DistributedDataParallel): + yield + return + + old_require_backward_grad_sync = model.require_backward_grad_sync + old_require_forward_param_sync = model.require_forward_param_sync + + # EXPERIMENTAL: This will force grad sync during `backward()`, but it is unknown if it breaks other DDP features. + # https://github.com/pytorch/pytorch/blob/e1502c0cdbfd17548c612f25d5a65b1e4b86224d/torch/nn/parallel/distributed.py#L1453-L1466 + model.require_backward_grad_sync = True + model.require_forward_param_sync = True + # https://github.com/pytorch/pytorch/blob/e1502c0cdbfd17548c612f25d5a65b1e4b86224d/torch/csrc/distributed/c10d/reducer.cpp#L1371-L1402 + model.reducer.prepare_for_backward([]) + try: + yield + finally: + model.require_backward_grad_sync = old_require_backward_grad_sync + model.require_forward_param_sync = old_require_forward_param_sync + + def _do_sync(self): + "Sets the right `sync_gradients` context and either resets or increases `self.step`" + if self.gradient_state.sync_with_dataloader and self.gradient_state.end_of_dataloader: + self.step = 0 + self.gradient_state._set_sync_gradients(True) + else: + self.step += 1 + self.gradient_state._set_sync_gradients((self.step % self.gradient_state.num_steps) == 0) + + @property + def sync_gradients(self): + return self.gradient_state.sync_gradients + + @sync_gradients.setter + def sync_gradients(self, sync_gradients): + self.gradient_state.sync_gradients = sync_gradients + + @property + def gradient_accumulation_steps(self): + return self.gradient_state.num_steps + + @gradient_accumulation_steps.setter + def gradient_accumulation_steps(self, gradient_accumulation_steps): + self.gradient_state.plugin_kwargs.update({"num_steps": gradient_accumulation_steps}) + + @contextmanager + def accumulate(self, *models): + """ + A context manager that will lightly wrap around and perform gradient accumulation automatically + + Args: + *models (list of `torch.nn.Module`): + PyTorch Modules that were prepared with `Accelerator.prepare`. Models passed to `accumulate()` will + skip gradient syncing during backward pass in distributed training + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(gradient_accumulation_steps=1) + >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) + + >>> for input, output in dataloader: + ... with accelerator.accumulate(model): + ... outputs = model(input) + ... loss = loss_func(outputs) + ... loss.backward() + ... optimizer.step() + ... scheduler.step() + ... optimizer.zero_grad() + ``` + """ + self._do_sync() + + allow_gradient_sync = ( + self.sync_gradients # must sync if sync gradients need to complete an optimizer step + or ( + # the no_sync context stops the gradients from reducing during distributed training + # bringing speedup (potentially at some costs). Here, no_sync can be prevented + # by setting sync_each_batch = True. + self.use_distributed # only relevant in distributed settings + and self.gradient_state.plugin_kwargs.get("sync_each_batch", False) + ) + ) + with contextlib.ExitStack() as cm_stack: + for m in models: + cm_stack.enter_context(contextlib.nullcontext() if allow_gradient_sync else self.no_sync(m)) + yield + + @contextmanager + def join_uneven_inputs(self, joinables, even_batches=None): + """ + A context manager that facilitates distributed training or evaluation on uneven inputs, which acts as a wrapper + around `torch.distributed.algorithms.join`. This is useful when the total batch size does not evenly divide the + length of the dataset. + + Args: + joinables (`list[torch.distributed.algorithms.Joinable]`): + A list of models or optimizers that subclass `torch.distributed.algorithms.Joinable`. Most commonly, a + PyTorch Module that was prepared with `Accelerator.prepare` for DistributedDataParallel training. + even_batches (`bool`, *optional*) + If set, this will override the value of `even_batches` set in the `Accelerator`. If it is not provided, + the default `Accelerator` value wil be used. + + + + `join_uneven_inputs` is only supported for Distributed Data Parallel training on multiple GPUs. For any other + configuration, this method will have no effect. + + + + + + Overidding `even_batches` will not affect iterable-style data loaders. + + + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(even_batches=True) + >>> ddp_model, optimizer, dataloader = accelerator.prepare(model, optimizer, dataloader) + + >>> with accelerator.join_uneven_inputs([ddp_model], even_batches=False): + ... for input, output in dataloader: + ... outputs = model(input) + ... loss = loss_func(outputs) + ... loss.backward() + ... optimizer.step() + ... optimizer.zero_grad() + ``` + """ + if self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_XPU, + ): + dl_even_batches_values = [] + + if even_batches is not None: + iterable_dl_seen = False + # override value in batch sampler for map-style datasets + for dl_idx, dl in enumerate(self._dataloaders): + if isinstance(dl, DataLoaderDispatcher): + iterable_dl_seen = True + continue + dl_even_batches_values.append((dl_idx, dl.batch_sampler.even_batches)) + dl.batch_sampler.even_batches = even_batches + + if iterable_dl_seen: + warnings.warn( + "Overridding even_batches is only supported for map-style datasets, yet some dataloaders given were iterable" + ) + else: + even_batches = self.even_batches + + enable_join = False if even_batches else True + try: + with Join(joinables, enable=enable_join, throw_on_early_termination=False): + yield + finally: + # reset any batch samplers that have been modified + for dl_idx, even_batches_value in dl_even_batches_values: + self._dataloaders[dl_idx].batch_sampler.even_batches = even_batches_value + else: + # Even when disabled, Join expects models to subclass Joinable, so skip entirely for single process runs + if self.distributed_type != DistributedType.NO: + warnings.warn( + "Joining uneven inputs is only supported for multi-GPU training, as a result `join_uneven_inputs` will have no effect." + ) + + with contextlib.nullcontext(joinables): + yield + + def print(self, *args, **kwargs): + """ + Drop in replacement of `print()` to only print once per server. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> accelerator.print("Hello world!") + ``` + """ + self.state.print(*args, **kwargs) + + def _prepare_one(self, obj, first_pass=False, device_placement=None): + # First pass of preparation: DataLoader, model, optimizer + if first_pass: + if isinstance(obj, torch.utils.data.DataLoader): + return self.prepare_data_loader(obj, device_placement=device_placement) + elif isinstance(obj, torch.nn.Module): + return self.prepare_model(obj, device_placement=device_placement) + elif isinstance(obj, torch.optim.Optimizer): + optimizer = self.prepare_optimizer(obj, device_placement=device_placement) + return optimizer + # Second pass of preparation: LR scheduler (which need the full list of optimizers) + elif isinstance(obj, LRScheduler): + scheduler = self.prepare_scheduler(obj) + return scheduler + # Return the unprocessed object if previous criteria was not met + return obj + + def prepare(self, *args, device_placement=None): + """ + Prepare all objects passed in `args` for distributed training and mixed precision, then return them in the same + order. + + Args: + *args (list of objects): + Any of the following type of objects: + + - `torch.utils.data.DataLoader`: PyTorch Dataloader + - `torch.nn.Module`: PyTorch Module + - `torch.optim.Optimizer`: PyTorch Optimizer + - `torch.optim.lr_scheduler.LRScheduler`: PyTorch LR Scheduler + + device_placement (`list[bool]`, *optional*): + Used to customize whether automatic device placement should be performed for each object passed. Needs + to be a list of the same length as `args`. Not compatible with DeepSpeed or FSDP. + + + + You don't need to prepare a model if you only use it for inference without any kind of mixed precision + + + + Examples: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume a model, optimizer, data_loader and scheduler are defined + >>> model, optimizer, data_loader, scheduler = accelerator.prepare(model, optimizer, data_loader, scheduler) + ``` + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume a model, optimizer, data_loader and scheduler are defined + >>> device_placement = [True, True, False, False] + >>> # Will place the first to items passed in automatically to the right device but not the last two. + >>> model, optimizer, data_loader, scheduler = accelerator.prepare( + ... model, optimizer, data_loader, scheduler, device_placement=device_placement + ... ) + ``` + """ + if device_placement is None: + device_placement = [None for _ in args] + elif self.distributed_type in (DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM): + raise ValueError("You can't customize device placements with DeepSpeed or Megatron-LM.") + elif len(device_placement) != len(args): + raise ValueError( + f"`device_placement` should be a list with {len(args)} elements (the number of objects passed)." + ) + + for obj in args: + # TODO: Look at enabling native TP training directly with a proper config + if ( + isinstance(obj, torch.nn.Module) + and self.verify_device_map(obj) + and self.distributed_type != DistributedType.NO + and os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true" + ): + raise ValueError( + "You can't train a model that has been loaded with `device_map='auto'` in any distributed mode." + " Please rerun your script specifying `--num_processes=1` or by launching with `python {{myscript.py}}`." + ) + + if self.distributed_type == DistributedType.DEEPSPEED: + model_count = 0 + for obj in args: + if isinstance(obj, torch.nn.Module): + model_count += 1 + if model_count > 1: + raise AssertionError( + "You can't use same `Accelerator()` instance with multiple models when using DeepSpeed" + ) + + # On TPUs, putting the model on the XLA device will create new parameters, so the corresponding optimizer will + # have parameters disconnected from the model (so no training :-( ). + # If the model and optimizer have parameters on different devices we raise an error. + if self.distributed_type == DistributedType.XLA: + model_device, optimizer_device = self._get_devices() + if model_device is not None and optimizer_device is not None and model_device != optimizer_device: + raise ValueError( + "The model and the optimizer parameters are not on the same device, which probably means you " + "created an optimizer around your model **before** putting on the device. Make sure the line " + "model.to(device) is before the optimizer creation in your script or remove it entirely and use " + "the flag default value for `device_placement` in your `Accelerator` to let it handle that " + "part for you." + ) + + # If we're dealing with device placement, this deals with that by... + tpu_should_fix_optimizer = self.device_placement and self.distributed_type == DistributedType.XLA + + if tpu_should_fix_optimizer: + # 1. grabbing old model parameters + old_named_params = self._get_named_parameters(*args) + + if self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]: + if self.device.type == "cpu" and self.state.use_ipex: + args = self._prepare_ipex_or_xpu(*args) + elif self.device.type == "xpu" and is_xpu_available(): + args = self._prepare_ipex_or_xpu(*args) + if self.fp8_recipe_handler is not None and self.fp8_recipe_handler.backend == "TE": + args = self._prepare_te(*args) + if self.distributed_type == DistributedType.DEEPSPEED: + result = self._prepare_deepspeed(*args) + elif self.distributed_type == DistributedType.MEGATRON_LM: + result = self._prepare_megatron_lm(*args) + else: + if self.mixed_precision == "fp8" and self.fp8_recipe_handler.backend == "MSAMP": + args = self._prepare_msamp(*args) + # MS-AMP will handle the device placement + device_placement = [False for _ in args] + result = tuple( + self._prepare_one(obj, first_pass=True, device_placement=d) for obj, d in zip(args, device_placement) + ) + result = tuple(self._prepare_one(obj, device_placement=d) for obj, d in zip(result, device_placement)) + if tpu_should_fix_optimizer: + # 2. grabbing new model parameters + new_named_params = self._get_named_parameters(*result) + # 3. building a map from the first to the second + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + # 4. using that map to update the parameters of the optimizer + for obj in result: + if isinstance(obj, torch.optim.Optimizer): + obj._switch_parameters(mapping) + + for item in result: + if any( + item in container + for container in (self._dataloaders, self._models, self._optimizers, self._schedulers) + ): + item._is_accelerate_prepared = True + + return result if len(result) > 1 else result[0] + + def prepare_model(self, model: torch.nn.Module, device_placement: bool = None, evaluation_mode: bool = False): + """ + Prepares a PyTorch model for training in any distributed setup. It is recommended to use + [`Accelerator.prepare`] instead. + + Args: + model (`torch.nn.Module`): + A PyTorch model to prepare. You don't need to prepare a model if it is used only for inference without + any kind of mixed precision + device_placement (`bool`, *optional*): + Whether or not to place the model on the proper device. Will default to `self.device_placement`. + evaluation_mode (`bool`, *optional*, defaults to `False`): + Whether or not to set the model for evaluation only, by just applying mixed precision and + `torch.compile` (if configured in the `Accelerator` object). + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume a model is defined + >>> model = accelerator.prepare_model(model) + ``` + """ + if device_placement is None: + device_placement = self.device_placement and self.distributed_type != DistributedType.FSDP + self._models.append(model) + + # TODO: Look at enabling native TP training directly with a proper config + if ( + self.verify_device_map(model) + and self.distributed_type != DistributedType.NO + and os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true" + ): + raise ValueError( + "You can't train a model that has been loaded with `device_map='auto'` in any distributed mode." + " Please rerun your script specifying `--num_processes=1` or by launching with `python {{myscript.py}}`." + ) + + if self.native_amp: + model._original_forward = model.forward + model_forward_func = model.forward.__func__ if hasattr(model.forward, "__func__") else model.forward + autocast_context = get_mixed_precision_context_manager(self.native_amp, self.autocast_handler) + new_forward = autocast_context(model_forward_func) + if hasattr(model.forward, "__func__"): + model.forward = MethodType(new_forward, model) + model.forward = MethodType(convert_outputs_to_fp32(model.forward.__func__), model) + else: + model.forward = convert_outputs_to_fp32(new_forward) + + # We prepare fp8 after, allowing for bf16 autocast to happen first + if getattr(self.fp8_recipe_handler, "backend", None) == "TE" and not self.delayed_fp8_autocast: + model = apply_fp8_autowrap(model, self.fp8_recipe_handler) + + if (getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False)) and getattr( + model, "hf_device_map", False + ): + model_devices = set(model.hf_device_map.values()) + if len(model_devices) > 1 and self.distributed_type != DistributedType.NO: + raise ValueError( + "You can't train a model that has been loaded in 8-bit precision on multiple devices in any distributed mode." + " In order to use 8-bit models that have been loaded across multiple GPUs the solution is to use Naive Pipeline Parallelism." + " Therefore you should not specify that you are under any distributed regime in your accelerate config." + ) + elif len(model_devices) == 1: + current_device = list(model_devices)[0] + current_device_index = ( + current_device.index if isinstance(current_device, torch.device) else current_device + ) + + if torch.device(current_device_index) != self.device: + # if on the first device (GPU 0) we don't care + if (self.device.index is not None) or (current_device_index != 0): + raise ValueError( + "You can't train a model that has been loaded in 8-bit precision on a different device than the one " + "you're training on. Make sure you loaded the model on the correct device using for example `device_map={'':torch.cuda.current_device()}` or `device_map={'':torch.xpu.current_device()}`" + ) + + if "cpu" in model_devices or "disk" in model_devices: + raise ValueError( + "You can't train a model that has been loaded in 8-bit precision with CPU or disk offload." + ) + elif device_placement and not self.verify_device_map(model): + model = model.to(self.device) + if not evaluation_mode: + if self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + ): + if any(p.requires_grad for p in model.parameters()): + kwargs = self.ddp_handler.to_kwargs() if self.ddp_handler is not None else {} + # TODO: Look at enabling native TP training directly with a proper config + if os.environ.get("ACCELERATE_BYPASS_DEVICE_MAP", "false") != "true": + device_ids, output_device = [self.local_process_index], self.local_process_index + else: + device_ids, output_device = None, None + + model = torch.nn.parallel.DistributedDataParallel( + model, device_ids=device_ids, output_device=output_device, **kwargs + ) + if self.ddp_handler is not None: + self.ddp_handler.register_comm_hook(model) + elif self.distributed_type == DistributedType.FSDP: + # We need to fix the optimizer *before* sharding the model + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + + # Check if the model is already a FSDP model due to `Manual Wrapping` and if so, + # don't wrap it again + # In case the model is already compiled using PyTorch 2.0 and the wrapped model in it + # is a FSDP model, don't wrap it again + is_type_fsdp = isinstance(model, FSDP) or ( + is_compiled_module(model) and isinstance(model._orig_mod, FSDP) + ) + + if not is_type_fsdp: + self.state.fsdp_plugin.set_auto_wrap_policy(model) + fsdp_plugin = self.state.fsdp_plugin + kwargs = { + "sharding_strategy": fsdp_plugin.sharding_strategy, + "cpu_offload": fsdp_plugin.cpu_offload, + "auto_wrap_policy": fsdp_plugin.auto_wrap_policy, + "mixed_precision": fsdp_plugin.mixed_precision_policy, + "sync_module_states": fsdp_plugin.sync_module_states, + "backward_prefetch": fsdp_plugin.backward_prefetch, + "forward_prefetch": fsdp_plugin.forward_prefetch, + "use_orig_params": fsdp_plugin.use_orig_params, + "param_init_fn": fsdp_plugin.param_init_fn, + "ignored_modules": fsdp_plugin.ignored_modules, + "limit_all_gathers": fsdp_plugin.limit_all_gathers, + "device_id": self.device, + } + model = FSDP(model, **kwargs) + if fsdp_plugin.activation_checkpointing: + from torch.distributed.algorithms._checkpoint.checkpoint_wrapper import ( + CheckpointImpl, + apply_activation_checkpointing, + checkpoint_wrapper, + ) + + apply_activation_checkpointing( + model, + checkpoint_wrapper_fn=functools.partial( + checkpoint_wrapper, + checkpoint_impl=CheckpointImpl.NO_REENTRANT, + ), + auto_wrap_policy=fsdp_plugin.auto_wrap_policy, + ) + + # In the event the model had been loaded in low precision, but + # mixed precision had also been activated, then we follow DeepSpeed's + # strategy to hold the parameters in full precision. + # - assume that trainer.args.bf16 and trainer.args.fp16 are already checked against + # fsdp_plugin.mixed_precision_policy. + # - NOTE: we do not check the mixed_precision attribute on the FSDP root wrapper. + # * this attribute will always set by init_utils.init_core_state so its always not None. + # * mixed_precision.param_dtype only regards _fwd_bwd_param_dtype + # * if model is loaded in 16bit, and even if mixed_precision.param_dtype is None, + # we sill want to upcast the flat_param. + if self.mixed_precision != "no": # if mixed precision is set + upcasted_log = [] + for module in FSDP.fsdp_modules(model): + # Referencing DeepSpeed Zero3 + # - in Init, params are converted to 16bit while partitioning. + # - in accelerator.prepare, deepspeed.initalize is called to: + # * creates the DeepSpeeedEngine. + # * since zero_optimization() is True , calls engine._configure_zero_optimizer. + # + # Inside the DeepSpeed Zero3 optimizer configuration, which initalizes + # DeepSpeedZeroOptimizer_Stage3, during which: + # * trainable_param_groups are obtained from the attached optimizer + # (already partitioned in 16bit). + # * then _setup_for_real_optimizer -> _create_fp32_partitions + # which performs the fp32 upcasting. + + # To mimick DeepSeepds's casting in FSDP, we look at the (single) FlatParameter held + # within an FSDP wrapper. This FlatParameter will be seen by the optimizer. + # - even though there is a torch.device('meta') guard below, we + # expect _init_utils._init_param_handle_from_module to already + # sync the parameter. + + if not module._has_params: + continue # skip if FSDP module not managing parameters + param = module._flat_param + if ( + param.dtype != torch.float32 + and param.device != torch.device("meta") + and param.requires_grad + ): + # keep log of names_params that was upcasted + # NOTE: resorted to this because warnings.simplefilter("once") is somehow not working + name_param_log = (module.module.__class__.__name__, ", ".join(module._flat_param._fqns)) + if name_param_log not in upcasted_log: + upcasted_log.append(name_param_log) + + # this works because of FSDP's _runtime_utils.lazy_init. + # Have to be careful not to call anything before this that + # triggers lazy_init (e.g., _is_fsdp_root). + param.data = param.data.to(torch.float32) # upcasting + module._handle._orig_param_dtype = torch.float32 # update + + # report the warnings + # some messages can be quite repetitive, especially when reporting about layers that have identical architecture. + if self.is_main_process: + for name_log, param_log in upcasted_log: + warnings.warn( + f"Upcasted low precision parameters in {name_log} because mixed precision turned on in FSDP. " + f"Affects: {param_log}." + ) + + if len(upcasted_log) > 0: + warnings.warn( + "FSDP upcast of low precision parameters may affect the precision of model checkpoints." + ) + + # if the previous and current models are same, delete the previous one + if len(self._models) > 1 and (self._models[-2] is self._models[-1]): + del self._models[-2] + self._models[-1] = model + elif self.distributed_type == DistributedType.MULTI_CPU: + kwargs = self.ddp_handler.to_kwargs() if self.ddp_handler is not None else {} + model = torch.nn.parallel.DistributedDataParallel(model, **kwargs) + if self.ddp_handler is not None: + self.ddp_handler.register_comm_hook(model) + elif self.distributed_type == DistributedType.XLA and self.state.fork_launched: + model = xmp.MpModelWrapper(model).to(self.device) + # Now we can apply the FP8 autocast + if self.delayed_fp8_autocast: + model = apply_fp8_autowrap(model, self.fp8_recipe_handler) + # torch.compile should be called last and only if the model isn't already compiled. + if self.state.dynamo_plugin.backend != DynamoBackend.NO and not is_compiled_module(model): + if not is_torch_version(">=", "2.0"): + raise ValueError("Using `torch.compile` requires PyTorch 2.0 or higher.") + model = torch.compile(model, **self.state.dynamo_plugin.to_kwargs()) + return model + + def _prepare_te(self, *args): + if not is_transformer_engine_available(): + raise ImportError( + "`transformer_engine` was not found on your system. Please ensure that `transformer_engine` is installed" + ) + model, optimizer = None, None + num_models, num_optimizers = 0, 0 + result = [obj for obj in args] + for obj in result: + if isinstance(obj, torch.nn.Module): + model = obj + num_models += 1 + elif isinstance(obj, (torch.optim.Optimizer)): + optimizer = obj + num_optimizers += 1 + if optimizer is None and model is None: + return result + elif optimizer is None or model is None: + raise ValueError( + "You must pass a model and an optimizer together to `accelerate.prepare()` when using TransformerEngine." + ) + elif num_models > 1 or num_optimizers > 1: + raise ValueError( + f"You can't use multiple models ({num_models}) or optimizers {num_optimizers} with TransformerEngine." + ) + old_named_params = self._get_named_parameters(model) + with torch.no_grad(): + convert_model(model) + new_named_params = self._get_named_parameters(model) + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + # We need to switch the optimizer params to the new params *after* the model is wrapped in FSDP + for param_group in optimizer.param_groups: + param_group["params"] = [mapping[p] for p in param_group["params"]] + + return result + + def _prepare_deepspeed(self, *args): + import deepspeed + + deepspeed_plugin = self.state.deepspeed_plugin + + is_dataloader_present = any(isinstance(obj, torch.utils.data.DataLoader) for obj in args) + result = [ + self._prepare_one(obj, first_pass=True) if isinstance(obj, torch.utils.data.DataLoader) else obj + for obj in args + ] + + if deepspeed_plugin.is_auto("train_micro_batch_size_per_gpu"): + if is_dataloader_present: + batch_sizes = [obj.batch_size for obj in args if hasattr(obj, "batch_size")] + if any(bs is None for bs in batch_sizes): + raise ValueError( + "At least one of the dataloaders passed to `accelerate.prepare()` has `None` as batch size. " + "Please set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file " + "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`." + ) + if self.split_batches: + batch_sizes = [batch_size // self.num_processes for batch_size in batch_sizes] + + batch_size_per_device = min(batch_sizes) if deepspeed_plugin.is_train_batch_min else max(batch_sizes) + if len(batch_sizes) > 1: + logger.info( + "Since you passed both train and evaluation dataloader, `is_train_batch_min` (here " + f"{deepspeed_plugin.is_train_batch_min} will decide the `train_batch_size` ({batch_size_per_device})." + ) + else: + raise ValueError( + "When using DeepSpeed, `accelerate.prepare()` requires you to pass at least one of training or evaluation dataloaders " + "with `batch_size` attribute returning an integer value " + "or alternatively set an integer value in `train_micro_batch_size_per_gpu` in the deepspeed config file " + "or assign integer value to `AcceleratorState().deepspeed_plugin.deepspeed_config['train_micro_batch_size_per_gpu']`." + ) + else: + batch_size_per_device = deepspeed_plugin.get_value("train_micro_batch_size_per_gpu") + + # handle `gradient_accumulation_steps` when the value is `auto` + deepspeed_plugin.fill_match( + "gradient_accumulation_steps", + must_match=False, + gradient_accumulation_steps=self.gradient_accumulation_steps, + ) + + config_kwargs = { + "train_micro_batch_size_per_gpu": batch_size_per_device, + "train_batch_size": batch_size_per_device + * deepspeed_plugin.get_value("gradient_accumulation_steps") + * self.num_processes, + "gradient_clipping": 1.0, + "zero_optimization.stage3_gather_16bit_weights_on_model_save": False, + } + + model = None + optimizer = None + scheduler = None + for obj in result: + if isinstance(obj, torch.nn.Module): + model = obj + elif isinstance(obj, (torch.optim.Optimizer, DummyOptim)): + optimizer = obj + elif (isinstance(obj, (LRScheduler, DummyScheduler))) or ( + type(obj).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES + ): + scheduler = obj + + if optimizer is not None: + if "optimizer" in deepspeed_plugin.deepspeed_config and not isinstance(optimizer, (DummyOptim)): + raise ValueError( + "You cannot specify an optimizer in the config file and in the code at the same time. " + "Please remove the optimizer from the config file or " + "create `accelerate.utils.DummyOptim` in the code." + ) + elif "optimizer" not in deepspeed_plugin.deepspeed_config and isinstance(optimizer, (DummyOptim)): + raise ValueError( + "You cannot create a `DummyOptim` without specifying an optimizer in the config file." + ) + + if isinstance(optimizer, (torch.optim.Optimizer)): + deepspeed_plugin.deepspeed_config["zero_allow_untested_optimizer"] = True + + if scheduler is not None: + if "scheduler" in deepspeed_plugin.deepspeed_config and not isinstance(scheduler, (DummyScheduler)): + raise ValueError( + "You cannot specify a scheduler in the config file and in the code at the same time. " + "Please remove the scheduler from the config file or " + "create `accelerate.utils.DummyScheduler` in the code." + ) + elif ( + "scheduler" not in deepspeed_plugin.deepspeed_config + and isinstance(scheduler, (DummyScheduler)) + and scheduler.lr_scheduler_callable is None + ): + raise ValueError( + "Either specify a scheduler in the config file or " + "pass in the `lr_scheduler_callable` parameter when using `accelerate.utils.DummyScheduler`." + ) + + if optimizer is not None and scheduler is not None: + if isinstance(optimizer, (DummyOptim)) and not isinstance(scheduler, (DummyScheduler)): + raise ValueError( + "You can only specify `accelerate.utils.DummyScheduler` in the code when using " + "`accelerate.utils.DummyOptim`." + ) + + if model is not None: + # If we are using FP8, we need to apply the autowrap now + if getattr(self.fp8_recipe_handler, "backend", None) == "TE": + model = apply_fp8_autowrap(model, self.fp8_recipe_handler) + # if the model is an MOE, set the appropriate MOE layers as leaf Z3 modules + deepspeed_plugin.set_moe_leaf_modules(model) + # deal with config keys that use `auto` value and rely on model's hidden_size + hidden_size_based_keys = [ + "zero_optimization.reduce_bucket_size", + "zero_optimization.stage3_prefetch_bucket_size", + "zero_optimization.stage3_param_persistence_threshold", + ] + hidden_size_auto_keys = [x for x in hidden_size_based_keys if deepspeed_plugin.is_auto(x)] + if len(hidden_size_auto_keys) > 0: + reasoning = ( + "therefore it's not possible to automatically fill out the following `auto` entries " + + f"in the DeepSpeed config file: {hidden_size_auto_keys}. You can fix that by replacing " + + "`auto` values for these keys with an integer value of your choice." + ) + if not hasattr(model, "config"): + raise ValueError("Can't find `model.config` entry, " + reasoning) + + if hasattr(model.config, "hidden_size"): + hidden_size = model.config.hidden_size + elif hasattr(model.config, "hidden_sizes"): + # if there are many hidden sizes pick the largest one + hidden_size = max(model.config.hidden_sizes) + else: + raise ValueError( + "Can find neither `model.config.hidden_size` nor `model.config.hidden_sizes`, " + reasoning + ) + + config_kwargs.update( + { + "zero_optimization.reduce_bucket_size": hidden_size * hidden_size, + "zero_optimization.stage3_prefetch_bucket_size": int(0.9 * hidden_size * hidden_size), + "zero_optimization.stage3_param_persistence_threshold": 10 * hidden_size, + } + ) + + if isinstance(optimizer, (DummyOptim)): + config_kwargs.update( + {"optimizer.params.lr": optimizer.lr, "optimizer.params.weight_decay": optimizer.weight_decay} + ) + if isinstance(scheduler, (DummyScheduler)) and scheduler.lr_scheduler_callable is None: + max_lr = ( + getattr(scheduler.optimizer, "lr", None) + if getattr(scheduler.optimizer, "defaults", None) is None + else scheduler.optimizer.defaults["lr"] + ) + config_kwargs.update( + { + "scheduler.params.warmup_min_lr": 0, + "scheduler.params.warmup_max_lr": max_lr, + "scheduler.params.warmup_num_steps": scheduler.warmup_num_steps, + } + ) + if scheduler.total_num_steps is not None: + config_kwargs["scheduler.params.total_num_steps"] = ( + math.ceil(scheduler.total_num_steps / self.num_processes) + if not self.split_batches + else scheduler.total_num_steps + ) + deepspeed_plugin.deepspeed_config_process(must_match=False, **config_kwargs) + self.deepspeed_config = deepspeed_plugin.deepspeed_config + kwargs = dict(model=model, config_params=self.deepspeed_config) + if optimizer is not None: + if isinstance(optimizer, (DummyOptim)): + kwargs["model_parameters"] = optimizer.params + if isinstance(scheduler, (DummyScheduler)) and scheduler.lr_scheduler_callable is not None: + kwargs["lr_scheduler"] = scheduler.lr_scheduler_callable + else: + if self.deepspeed_config["zero_optimization"].get("offload_optimizer", {}).get( + "device", "none" + ) != "none" and self.deepspeed_config.get("zero_force_ds_cpu_optimizer", True): + from deepspeed.ops.adam import DeepSpeedCPUAdam + + defaults = {k: v for k, v in optimizer.defaults.items() if k in ["lr", "weight_decay"]} + optimizer = DeepSpeedCPUAdam(optimizer.param_groups, **defaults) + kwargs["optimizer"] = optimizer + if scheduler is not None: + if type(scheduler).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES: + kwargs["lr_scheduler"] = scheduler + + engine, optimizer, _, lr_scheduler = deepspeed.initialize(**kwargs) + if optimizer is not None: + optimizer = DeepSpeedOptimizerWrapper(optimizer) + if scheduler is not None: + if lr_scheduler is None: + scheduler = AcceleratedScheduler( + scheduler, + optimizer, + step_with_optimizer=self.step_scheduler_with_optimizer, + split_batches=self.split_batches, + ) + else: + scheduler = DeepSpeedSchedulerWrapper(lr_scheduler, optimizer) + + for i in range(len(result)): + if isinstance(result[i], torch.nn.Module): + result[i] = engine + elif isinstance(result[i], (torch.optim.Optimizer, DummyOptim)): + result[i] = optimizer + elif (isinstance(result[i], (LRScheduler, DummyScheduler))) or ( + type(result[i]).__name__ in deepspeed.runtime.lr_schedules.VALID_LR_SCHEDULES + ): + result[i] = scheduler + # pointing for deepspeed_engine_wrapped.backward() + self.deepspeed_engine_wrapped = DeepSpeedEngineWrapper(engine) + self._models.append(engine) + if optimizer is not None: + self._optimizers.append(optimizer) + if scheduler is not None: + self._schedulers.append(scheduler) + if len(self._models) > 1: + raise AssertionError( + "You can't use same `Accelerator()` instance with multiple models when using DeepSpeed" + ) + return tuple(result) + + def _prepare_megatron_lm(self, *args): + megatron_lm_plugin = self.state.megatron_lm_plugin + micro_batch_size = None + if not megatron_lm_plugin.megatron_dataset_flag: + batch_sizes = [obj.batch_size for obj in args if hasattr(obj, "batch_size")] + if len(batch_sizes) == 0: + raise ValueError( + "You must specify a training or evaluation dataloader in `accelerate.prepare()` when using Megatron-LM." + ) + + micro_batch_size = min(batch_sizes) if megatron_lm_plugin.is_train_batch_min else max(batch_sizes) + if len(batch_sizes) > 1: + logger.info( + "Since you passed both train and evaluation dataloader, `is_train_batch_min` (here " + f"{megatron_lm_plugin.is_train_batch_min} will decide the `train_batch_size` ({micro_batch_size})." + ) + else: + for obj in args: + if isinstance(obj, MegatronLMDummyDataLoader): + micro_batch_size = obj.dataset_args["micro_batch_size"] + break + if micro_batch_size is not None: + dp_degree = self.num_processes // (megatron_lm_plugin.tp_degree * megatron_lm_plugin.pp_degree) + megatron_lm_plugin.set_training_args(micro_batch_size, dp_degree) + else: + raise ValueError( + "When you do not pass the dataloader parameter, the `data_parallel_size`, " + "`micro_batch_size`, and `global_batch_size` megatron parameters will not be updated." + ) + model = None + optimizer = None + scheduler = None + batch_data = None + for obj in args: + if isinstance(obj, torch.utils.data.DataLoader) and batch_data is None: + batch_data = next(iter(obj)) + elif isinstance(obj, torch.nn.Module): + model = obj + elif isinstance(obj, (torch.optim.Optimizer)): + optimizer = obj + elif isinstance(obj, (LRScheduler, MegatronLMDummyScheduler)): + scheduler = obj + + if model is not None: + megatron_lm_plugin.set_network_size_args(model, batch_data) + if optimizer is not None: + megatron_lm_plugin.set_optimizer_type(optimizer) + if scheduler is not None: + if not isinstance(scheduler, MegatronLMDummyScheduler): + raise ValueError( + "You can't use a custom scheduler with Megatron-LM. Please use the `accelerate.utils.MegatronLMDummyScheduler` instead." + ) + megatron_lm_plugin.set_scheduler_args(scheduler) + + # initialize megatron-lm + megatron_lm_initialize(self, args_defaults=megatron_lm_plugin.megatron_lm_default_args) + + (model, optimizer, scheduler) = megatron_lm_prepare_model_optimizer_scheduler(self) + self.wait_for_everyone() + + counter = 0 + result = [] + for obj in args: + if isinstance(obj, torch.utils.data.DataLoader): + result.append(megatron_lm_prepare_data_loader(self, obj)) + counter += 1 + elif isinstance(obj, MegatronLMDummyDataLoader): + if counter == 0: + obj.set_megatron_data_args() + dataloaders = megatron_lm_prepare_data_loader(self, obj) + result.append(dataloaders[counter]) + counter += 1 + else: + result.append(obj) + + if model is not None: + model = MegatronEngine(self, model, optimizer, scheduler) + if optimizer is not None: + optimizer = MegatronLMOptimizerWrapper(optimizer) + if scheduler is not None: + scheduler = MegatronLMSchedulerWrapper(scheduler, optimizer) + + for i in range(len(result)): + if isinstance(result[i], torch.nn.Module): + result[i] = model + elif isinstance(result[i], torch.optim.Optimizer): + result[i] = optimizer + elif isinstance(result[i], MegatronLMDummyScheduler): + result[i] = scheduler + + if model is not None: + self._models.append(model) + if len(self._models) > 1: + raise AssertionError( + "You can't use same `Accelerator()` instance with multiple models when using Megatron-LM" + ) + if optimizer is not None: + self._optimizers.append(optimizer) + if scheduler is not None: + self._schedulers.append(scheduler) + + return tuple(result) + + def _prepare_ipex_or_xpu(self, *args): + """ + Prepares model and optimizer for training with IPEX or XPU acceleration. This covers 3 cases, IPEX compiled + with CPU only support, IPEX compiled with XPU support and training with XPU pytorch backend available in stock + pytorch starting from version 2.4. + """ + if self.state.use_ipex: + if not is_ipex_available(): + raise ImportError( + "IPEX is not installed or IPEX's version does not match current PyTorch version. Please refer" + " to https://github.com/intel/intel-extension-for-pytorch." + ) + + model = None + optimizer = None + result = [obj for obj in args] + for obj in result: + if isinstance(obj, torch.nn.Module): + model = obj + model.train() + elif isinstance(obj, (torch.optim.Optimizer)): + optimizer = obj + if optimizer is not None and model is not None: + dtype = torch.bfloat16 if self.state.mixed_precision == "bf16" else None + if self.device.type == "xpu": + model = model.to(self.device) + # ipex.optimize() is available only for IPEX, both IPEX-CPU and IPEX-XPU + if is_ipex_available(): + import intel_extension_for_pytorch as ipex + + model, optimizer = ipex.optimize(model, optimizer=optimizer, dtype=dtype, inplace=True, level="O1") + for i in range(len(result)): + if isinstance(result[i], torch.nn.Module): + result[i] = model + elif isinstance(result[i], (torch.optim.Optimizer)): + result[i] = optimizer + return tuple(result) + + def _prepare_msamp(self, *args): + if not is_msamp_available(): + raise ImportError( + "MS-AMP was not found on your system. Please ensure that MS-AMP is available " + " or choose `'te'` as the backend for FP8 mixed precision training." + ) + else: + import msamp + + model, optimizer = None, None + num_models, num_optimizers = 0, 0 + result = [obj for obj in args] + for obj in result: + if isinstance(obj, torch.nn.Module): + model = obj + num_models += 1 + elif isinstance(obj, (torch.optim.Optimizer)): + optimizer = obj + num_optimizers += 1 + if optimizer is None or model is None: + raise ValueError( + "You must pass a model and an optimizer together to `accelerate.prepare()` when using MS-AMP." + ) + elif num_models > 1 or num_optimizers > 1: + raise ValueError( + f"You can't use multiple models ({num_models}) or optimizers {num_optimizers} with MS-AMP." + ) + else: + model, optimizer = msamp.initialize(model, optimizer, opt_level=self.fp8_recipe_handler.opt_level) + for i in range(len(result)): + if isinstance(result[i], torch.nn.Module): + result[i] = model + elif isinstance(result[i], (torch.optim.Optimizer)): + result[i] = optimizer + return tuple(result) + + def prepare_data_loader( + self, data_loader: torch.utils.data.DataLoader, device_placement=None, slice_fn_for_dispatch=None + ): + """ + Prepares a PyTorch DataLoader for training in any distributed setup. It is recommended to use + [`Accelerator.prepare`] instead. + + Args: + data_loader (`torch.utils.data.DataLoader`): + A vanilla PyTorch DataLoader to prepare + device_placement (`bool`, *optional*): + Whether or not to place the batches on the proper device in the prepared dataloader. Will default to + `self.device_placement`. + slice_fn_for_dispatch (`Callable`, *optional*`): + If passed, this function will be used to slice tensors across `num_processes`. Will default to + [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will + be ignored otherwise. + + Example: + + ```python + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> data_loader = torch.utils.data.DataLoader(...) + >>> data_loader = accelerator.prepare_data_loader(data_loader, device_placement=True) + ``` + """ + # Ensure we can't double wrap a DataLoader due to `find_batch_size` + if getattr(data_loader, "_is_accelerate_prepared", False): + if data_loader not in self._dataloaders: + self._dataloaders.append(data_loader) + return data_loader + if device_placement is None: + device_placement = self.device_placement if self.distributed_type != DistributedType.XLA else False + prepared_data_loader = prepare_data_loader( + data_loader, + self.device, + num_processes=self.num_processes, + process_index=self.process_index, + split_batches=self.split_batches, + put_on_device=device_placement, + rng_types=self.rng_types.copy(), + dispatch_batches=self.dispatch_batches, + even_batches=self.even_batches, + slice_fn_for_dispatch=slice_fn_for_dispatch, + use_seedable_sampler=self.use_seedable_sampler, + non_blocking=self.non_blocking, + use_stateful_dataloader=self.use_stateful_dataloader, + ) + self._dataloaders.append(prepared_data_loader) + return prepared_data_loader + + def prepare_optimizer(self, optimizer: torch.optim.Optimizer, device_placement=None): + """ + Prepares a PyTorch Optimizer for training in any distributed setup. It is recommended to use + [`Accelerator.prepare`] instead. + + Args: + optimizer (`torch.optim.Optimizer`): + A vanilla PyTorch optimizer to prepare + device_placement (`bool`, *optional*): + Whether or not to place the optimizer on the proper device. Will default to `self.device_placement`. + + Example: + + ```python + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> optimizer = torch.optim.Adam(...) + >>> optimizer = accelerator.prepare_optimizer(optimizer, device_placement=True) + ``` + """ + if is_lomo_available(): + # We need to import locally to avoid circular imports since lomo imports stuff from + # transformers & accelerate + from lomo_optim import AdaLomo, Lomo + + # Support multiple optimizers: https://github.com/huggingface/accelerate/pull/2695#discussion_r1589164607 + self.has_lomo_optimizer |= isinstance(optimizer, (Lomo, AdaLomo)) + + # Ensure we can't double wrap an optimizer due to `find_batch_size` + if getattr(optimizer, "_is_accelerate_prepared", False): + if optimizer not in self._optimizers: + self._optimizers.append(optimizer) + return optimizer + if device_placement is None: + device_placement = self.device_placement + optimizer = AcceleratedOptimizer(optimizer, device_placement=device_placement, scaler=self.scaler) + self._optimizers.append(optimizer) + return optimizer + + def prepare_scheduler(self, scheduler: LRScheduler): + """ + Prepares a PyTorch Scheduler for training in any distributed setup. It is recommended to use + [`Accelerator.prepare`] instead. + + Args: + scheduler (`torch.optim.lr_scheduler.LRScheduler`): + A vanilla PyTorch scheduler to prepare + + Example: + + ```python + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> optimizer = torch.optim.Adam(...) + >>> scheduler = torch.optim.lr_scheduler.LambdaLR(optimizer, ...) + >>> scheduler = accelerator.prepare_scheduler(scheduler) + ``` + """ + # Ensure we can't double wrap a scheduler due to `find_batch_size` + if getattr(scheduler, "_is_accelerate_prepared", False): + if scheduler not in self._schedulers: + self._schedulers.append(scheduler) + return scheduler + # We try to find the optimizer associated with `scheduler`, the default is the full list. + optimizer = self._optimizers + for opt in self._optimizers: + if getattr(scheduler, "optimizer", None) == opt.optimizer: + optimizer = opt + break + scheduler = AcceleratedScheduler( + scheduler, + optimizer, + step_with_optimizer=self.step_scheduler_with_optimizer, + split_batches=self.split_batches, + ) + self._schedulers.append(scheduler) + return scheduler + + def backward(self, loss, **kwargs): + """ + Scales the gradients in accordance to the `GradientAccumulationPlugin` and calls the correct `backward()` based + on the configuration. + + Should be used in lieu of `loss.backward()`. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(gradient_accumulation_steps=2) + >>> outputs = model(inputs) + >>> loss = loss_fn(outputs, labels) + >>> accelerator.backward(loss) + ``` + """ + learning_rate = kwargs.get("learning_rate") + + if self.distributed_type != DistributedType.DEEPSPEED: + # deepspeed handles loss scaling by gradient_accumulation_steps in its `backward` + loss = loss / self.gradient_accumulation_steps + if self.distributed_type == DistributedType.DEEPSPEED: + self.deepspeed_engine_wrapped.backward(loss, **kwargs) + elif self.distributed_type == DistributedType.MEGATRON_LM: + return + elif self.scaler is not None: + self.scaler.scale(loss).backward(**kwargs) + elif learning_rate is not None and self.has_lomo_optimizer: + self.lomo_backward(loss, learning_rate) + else: + loss.backward(**kwargs) + + def set_trigger(self): + """ + Sets the internal trigger tensor to 1 on the current process. A latter check should follow using this which + will check across all processes. + + Note: + Does not require `wait_for_everyone()` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume later in the training script + >>> # `should_do_breakpoint` is a custom function to monitor when to break, + >>> # e.g. when the loss is NaN + >>> if should_do_breakpoint(loss): + ... accelerator.set_trigger() + >>> # Assume later in the training script + >>> if accelerator.check_breakpoint(): + ... break + ``` + """ + self.flag_tensor = torch.tensor(1, device=self.device) + + def check_trigger(self): + """ + Checks if the internal trigger tensor has been set to 1 in any of the processes. If so, will return `True` and + reset the trigger tensor to 0. + + Note: + Does not require `wait_for_everyone()` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume later in the training script + >>> # `should_do_breakpoint` is a custom function to monitor when to break, + >>> # e.g. when the loss is NaN + >>> if should_do_breakpoint(loss): + ... accelerator.set_trigger() + >>> # Assume later in the training script + >>> if accelerator.check_trigger(): + ... break + ``` + """ + # Now that we are outside `__init__`, we can initialize it if it is `None` on device + if self.flag_tensor is None: + self.flag_tensor = torch.tensor(0, device=self.device) + flag_tensor = self.reduce(self.flag_tensor) + if flag_tensor.item() >= 1: + self.flag_tensor = torch.tensor(0, device=self.device) + return True + return False + + def unscale_gradients(self, optimizer=None): + """ + Unscale the gradients in mixed precision training with AMP. This is a noop in all other settings. + + Likely should be called through [`Accelerator.clip_grad_norm_`] or [`Accelerator.clip_grad_value_`] + + Args: + optimizer (`torch.optim.Optimizer` or `list[torch.optim.Optimizer]`, *optional*): + The optimizer(s) for which to unscale gradients. If not set, will unscale gradients on all optimizers + that were passed to [`~Accelerator.prepare`]. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer = accelerator.prepare(model, optimizer) + >>> outputs = model(inputs) + >>> loss = loss_fn(outputs, labels) + >>> accelerator.backward(loss) + >>> accelerator.unscale_gradients(optimizer=optimizer) + ``` + """ + if self.native_amp and self.mixed_precision == "fp16": + if optimizer is None: + # TODO: this unscales all optimizers where we should only unscale the one where parameters are. + optimizer = self._optimizers + elif not isinstance(optimizer, (tuple, list)): + optimizer = [optimizer] + for opt in optimizer: + while isinstance(opt, AcceleratedOptimizer): + opt = opt.optimizer + self.scaler.unscale_(opt) + + def clip_grad_norm_(self, parameters, max_norm, norm_type=2): + """ + Should be used in place of `torch.nn.utils.clip_grad_norm_`. + + Returns: + `torch.Tensor`: Total norm of the parameter gradients (viewed as a single vector). + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(gradient_accumulation_steps=2) + >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) + + >>> for input, target in dataloader: + ... optimizer.zero_grad() + ... output = model(input) + ... loss = loss_func(output, target) + ... accelerator.backward(loss) + ... if accelerator.sync_gradients: + ... accelerator.clip_grad_norm_(model.parameters(), max_grad_norm) + ... optimizer.step() + ``` + """ + if self.distributed_type == DistributedType.FSDP: + self.unscale_gradients() + parameters = [p for p in parameters] + for model in self._models: + if parameters == [p for p in model.parameters()]: + return model.clip_grad_norm_(max_norm, norm_type) + elif self.distributed_type == DistributedType.DEEPSPEED: + # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed + # We cannot return the gradient norm because DeepSpeed does it. + return None + elif self.distributed_type == DistributedType.XLA: + # Reduce gradients first for XLA + for acc_opt in self._optimizers: + if not acc_opt.gradient_state.is_xla_gradients_synced: + opt = acc_opt + while isinstance(opt, AcceleratedOptimizer): + opt = opt.optimizer + gradients = xm._fetch_gradients(opt) + # Use xm.all_reduce to perform an in-place all-reduce. Recusrsive all-reduce each tensor + # one by one in self.reduce is non-inplace. + xm.all_reduce("sum", gradients, scale=1.0 / self.num_processes) + # Set is_xla_gradients_synced to True to avoid all-reduce twice in the AcceleratedOptimizer step. + acc_opt.gradient_state.is_xla_gradients_synced = True + if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true": + self.unscale_gradients() + parameters = [p for p in parameters] + for model in self._models: + if parameters == [p for p in model.parameters()]: + return model.clip_grad_norm_(max_norm, norm_type) + self.unscale_gradients() + return torch.nn.utils.clip_grad_norm_(parameters, max_norm, norm_type=norm_type) + + def clip_grad_value_(self, parameters, clip_value): + """ + Should be used in place of `torch.nn.utils.clip_grad_value_`. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(gradient_accumulation_steps=2) + >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) + + >>> for input, target in dataloader: + ... optimizer.zero_grad() + ... output = model(input) + ... loss = loss_func(output, target) + ... accelerator.backward(loss) + ... if accelerator.sync_gradients: + ... accelerator.clip_grad_value_(model.parameters(), clip_value) + ... optimizer.step() + ``` + """ + if self.distributed_type in [DistributedType.DEEPSPEED, DistributedType.FSDP]: + raise Exception("DeepSpeed and FSDP do not support `clip_grad_value_`. Use `clip_grad_norm_` instead.") + self.unscale_gradients() + torch.nn.utils.clip_grad_value_(parameters, clip_value) + + def gather(self, tensor): + """ + Gather the values in *tensor* across all processes and concatenate them on the first dimension. Useful to + regroup the predictions from all processes when doing evaluation. + + Note: + This gather happens in all processes. + + Args: + tensor (`torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`): + The tensors to gather across all processes. + + Returns: + `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: The gathered tensor(s). Note that the + first dimension of the result is *num_processes* multiplied by the first dimension of the input tensors. + + Example: + + ```python + >>> # Assuming four processes + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> process_tensor = torch.tensor([accelerator.process_index]) + >>> gathered_tensor = accelerator.gather(process_tensor) + >>> gathered_tensor + tensor([0, 1, 2, 3]) + ``` + """ + return gather(tensor) + + def gather_for_metrics(self, input_data, use_gather_object=False): + """ + Gathers `input_data` and potentially drops duplicates in the last batch if on a distributed system. Should be + used for gathering the inputs and targets for metric calculation. + + Args: + input (`torch.Tensor`, `object`, a nested tuple/list/dictionary of `torch.Tensor`, or a nested tuple/list/dictionary of `object`): + The tensors or objects for calculating metrics across all processes + use_gather_object(`bool`): + Whether to forcibly use gather_object instead of gather (which is already done if all objects passed do + not contain tensors). This flag can be useful for gathering tensors with different sizes that we don't + want to pad and concatenate along the first dimension. Using it with GPU tensors is not well supported + and inefficient as it incurs GPU -> CPU transfer since tensors would be pickled. + + Example: + + ```python + >>> # Assuming two processes, with a batch size of 5 on a dataset with 9 samples + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> dataloader = torch.utils.data.DataLoader(range(9), batch_size=5) + >>> dataloader = accelerator.prepare(dataloader) + >>> batch = next(iter(dataloader)) + >>> gathered_items = accelerator.gather_for_metrics(batch) + >>> len(gathered_items) + 9 + ``` + """ + + try: + recursively_apply(lambda x: x, input_data, error_on_other_type=True) + all_tensors = True + except TypeError: + all_tensors = False + + use_gather_object = use_gather_object or not all_tensors + + if use_gather_object: + data = gather_object(input_data) + else: + data = self.gather(input_data) + + try: + if self.gradient_state.end_of_dataloader: + # at the end of a dataloader, `gather_for_metrics` regresses to + # `gather` unless the dataset has a remainder so log. + if self.gradient_state.remainder == -1: + logger.info( + "The used dataset had no length, returning gathered tensors. You should drop the remainder yourself." + ) + return data + elif self.gradient_state.remainder > 0: + # Last batch needs to be truncated on distributed systems as it contains additional samples + def _adjust_samples(tensor): + return tensor[: self.gradient_state.remainder] + + if use_gather_object: + # gather_object put the objects in a list + return _adjust_samples(data) + else: + return recursively_apply(_adjust_samples, data) + else: # remainder is 0 + # no remainder even though at end of dataloader, so nothing to do. + return data + else: + # Not at the end of the dataloader, no need to adjust the tensors + return data + except Exception: + # Dataset had no length or raised an error + return data + + def reduce(self, tensor, reduction="sum", scale=1.0): + """ + Reduce the values in *tensor* across all processes based on *reduction*. + + Note: + All processes get the reduced value. + + Args: + tensor (`torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`): + The tensors to reduce across all processes. + reduction (`str`, *optional*, defaults to "sum"): + A reduction type, can be one of 'sum', 'mean', or 'none'. If 'none', will not perform any operation. + scale (`float`, *optional*, defaults to 1.0): + A default scaling value to be applied after the reduce, only valied on XLA. + + Returns: + `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: + The reduced tensor(s). + + Example: + + ```python + >>> # Assuming two processes + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> process_tensor = torch.arange(accelerator.num_processes) + 1 + (2 * accelerator.process_index) + >>> process_tensor = process_tensor.to(accelerator.device) + >>> reduced_tensor = accelerator.reduce(process_tensor, reduction="sum") + >>> reduced_tensor + tensor([4, 6]) + ``` + """ + return reduce(tensor, reduction, scale) + + def pad_across_processes(self, tensor, dim=0, pad_index=0, pad_first=False): + """ + Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so + they can safely be gathered. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather. + dim (`int`, *optional*, defaults to 0): + The dimension on which to pad. + pad_index (`int`, *optional*, defaults to 0): + The value with which to pad. + pad_first (`bool`, *optional*, defaults to `False`): + Whether to pad at the beginning or the end. + + Returns: + `torch.Tensor`, or a nested tuple/list/dictionary of `torch.Tensor`: + The padded tensor(s). + + Example: + + ```python + >>> # Assuming two processes, with the first processes having a tensor of size 1 and the second of size 2 + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> process_tensor = torch.arange(accelerator.process_index + 1).to(accelerator.device) + >>> padded_tensor = accelerator.pad_across_processes(process_tensor) + >>> padded_tensor.shape + torch.Size([2]) + ``` + """ + return pad_across_processes(tensor, dim=dim, pad_index=pad_index, pad_first=pad_first) + + def unwrap_model(self, model, keep_fp32_wrapper: bool = True): + """ + Unwraps the `model` from the additional layer possible added by [`~Accelerator.prepare`]. Useful before saving + the model. + + Args: + model (`torch.nn.Module`): + The model to unwrap. + keep_fp32_wrapper (`bool`, *optional*, defaults to `True`): + Whether to not remove the mixed precision hook if it was added. + + Returns: + `torch.nn.Module`: The unwrapped model. + + Example: + + ```python + >>> # Assuming two GPU processes + >>> from torch.nn.parallel import DistributedDataParallel + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model = accelerator.prepare(MyModel()) + >>> print(model.__class__.__name__) + DistributedDataParallel + + >>> model = accelerator.unwrap_model(model) + >>> print(model.__class__.__name__) + MyModel + ``` + """ + return extract_model_from_parallel(model, keep_fp32_wrapper) + + def wait_for_everyone(self): + """ + Will stop the execution of the current process until every other process has reached that point (so this does + nothing when the script is only run in one process). Useful to do before saving a model. + + Example: + + ```python + >>> # Assuming two GPU processes + >>> import time + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> if accelerator.is_main_process: + ... time.sleep(2) + >>> else: + ... print("I'm waiting for the main process to finish its sleep...") + >>> accelerator.wait_for_everyone() + >>> # Should print on every process at the same time + >>> print("Everyone is here") + ``` + """ + wait_for_everyone() + + @on_main_process + def init_trackers(self, project_name: str, config: dict | None = None, init_kwargs: dict | None = {}): + """ + Initializes a run for all trackers stored in `self.log_with`, potentially with starting configurations + + Args: + project_name (`str`): + The name of the project. All trackers will save their data based on this + config (`dict`, *optional*): + Optional starting configuration to be logged. + init_kwargs (`dict`, *optional*): + A nested dictionary of kwargs to be passed to a specific tracker's `__init__` function. Should be + formatted like so: + ```python + {"wandb": {"tags": ["tag_a", "tag_b"]}} + ``` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(log_with="tensorboard") + >>> accelerator.init_trackers( + ... project_name="my_project", + ... config={"learning_rate": 0.001, "batch_size": 32}, + ... init_kwargs={"tensorboard": {"flush_secs": 60}}, + ... ) + ``` + """ + for tracker in self.log_with: + if issubclass(type(tracker), GeneralTracker): + # Custom trackers are already initialized + self.trackers.append(tracker) + else: + tracker_init = LOGGER_TYPE_TO_CLASS[str(tracker)] + if tracker_init.requires_logging_directory: + # We can skip this check since it was done in `__init__` + self.trackers.append( + tracker_init(project_name, self.logging_dir, **init_kwargs.get(str(tracker), {})) + ) + else: + self.trackers.append(tracker_init(project_name, **init_kwargs.get(str(tracker), {}))) + if config is not None: + for tracker in self.trackers: + tracker.store_init_configuration(config) + + def get_tracker(self, name: str, unwrap: bool = False): + """ + Returns a `tracker` from `self.trackers` based on `name` on the main process only. + + Args: + name (`str`): + The name of a tracker, corresponding to the `.name` property. + unwrap (`bool`): + Whether to return the internal tracking mechanism or to return the wrapped tracker instead + (recommended). + + Returns: + `GeneralTracker`: The tracker corresponding to `name` if it exists. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(log_with="tensorboard") + >>> accelerator.init_trackers("my_project") + >>> tensorboard_tracker = accelerator.get_tracker("tensorboard") + ``` + """ + if len(self.trackers) > 0: + for tracker in self.trackers: + if tracker.name == name: + return tracker.tracker if unwrap else tracker + raise ValueError(f"{name} is not an available tracker stored inside the `Accelerator`.") + # Handle tracker only made on main process + return GeneralTracker(_blank=True) + + @on_main_process + def log(self, values: dict, step: int | None = None, log_kwargs: dict | None = {}): + """ + Logs `values` to all stored trackers in `self.trackers` on the main process only. + + Args: + values (`dict`): + Values should be a dictionary-like object containing only types `int`, `float`, or `str`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + log_kwargs (`dict`, *optional*): + A nested dictionary of kwargs to be passed to a specific tracker's `log` function. Should be formatted + like so: + ```python + {"wandb": {"tags": ["tag_a", "tag_b"]}} + ``` + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(log_with="tensorboard") + >>> accelerator.init_trackers("my_project") + >>> accelerator.log({"loss": 0.5, "accuracy": 0.9}) + ``` + """ + for tracker in self.trackers: + tracker.log(values, step=step, **log_kwargs.get(tracker.name, {})) + + def end_training(self): + """ + Runs any special end training behaviors, such as stopping trackers on the main process only or destoying + process group. Should always be called at the end of your script if using experiment tracking. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(log_with="tensorboard") + >>> accelerator.init_trackers("my_project") + >>> # Do training + >>> accelerator.end_training() + ``` + """ + for tracker in self.trackers: + tracker.finish() + + self.state.destroy_process_group() + + def save(self, obj, f, safe_serialization=False): + """ + Save the object passed to disk once per machine. Use in place of `torch.save`. + + Args: + obj (`object`): The object to save. + f (`str` or `os.PathLike`): Where to save the content of `obj`. + safe_serialization (`bool`, *optional*, defaults to `False`): Whether to save `obj` using `safetensors` + + Note: + If `save_on_each_node` was passed in as a `ProjectConfiguration`, will save the object once per node, + rather than only once on the main node. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> arr = [0, 1, 2, 3] + >>> accelerator.save(arr, "array.pkl") + ``` + """ + save( + obj, + f, + save_on_each_node=self.project_configuration.save_on_each_node, + safe_serialization=safe_serialization, + ) + + def save_model( + self, + model: torch.nn.Module, + save_directory: Union[str, os.PathLike], + max_shard_size: Union[int, str] = "10GB", + safe_serialization: bool = True, + ): + """ + Save a model so that it can be re-loaded using load_checkpoint_in_model + + Arguments: + model: (`torch.nn.Module`): + Model to be saved. The model can be wrapped or unwraped. + save_directory (`str` or `os.PathLike`): + Directory to which to save. Will be created if it doesn't exist. + max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): + The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size + lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5MB"`). + + + + If a single weight of the model is bigger than `max_shard_size`, it will be in its own checkpoint shard + which will be bigger than `max_shard_size`. + + + + safe_serialization (`bool`, *optional*, defaults to `True`): + Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model = ... + >>> accelerator.save_model(model, save_directory) + ``` + """ + + if os.path.isfile(save_directory): + logger.error(f"Provided path ({save_directory}) should be a directory, not a file") + return + + os.makedirs(save_directory, exist_ok=True) + + # get the state_dict of the model + if any( + [ + module._hf_hook.offload + for module in model.modules() + if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) + ] + ): + state_dict = get_state_dict_offloaded_model(model) + else: + if any(param.device == torch.device("meta") for param in model.parameters()): + raise RuntimeError("You can't save the model since some parameters are on the meta device.") + state_dict = self.get_state_dict(model) + + if safe_serialization: + state_dict = clean_state_dict_for_safetensors(state_dict) + weights_name = SAFE_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME + filename_pattern = SAFE_WEIGHTS_PATTERN_NAME if safe_serialization else WEIGHTS_PATTERN_NAME + + state_dict_split = split_torch_state_dict_into_shards( + state_dict, filename_pattern=filename_pattern, max_shard_size=max_shard_size + ) + + # Clean the folder from a previous save + for filename in os.listdir(save_directory): + full_filename = os.path.join(save_directory, filename) + # If we have a shard file that is not going to be replaced, we delete it, but only from the main process + # in distributed settings to avoid race conditions. + weights_no_suffix = weights_name.replace(".bin", "") + + # make sure that file to be deleted matches format of sharded file, e.g. pytorch_model-00001-of-00005 + filename_no_suffix = filename.replace(".bin", "") + reg = re.compile(r"(.*?)-\d{5}-of-\d{5}") + + if ( + filename.startswith(weights_no_suffix) + and os.path.isfile(full_filename) + and filename not in state_dict_split.filename_to_tensors.keys() + and reg.fullmatch(filename_no_suffix) is not None + and PartialState().is_main_process + ): + os.remove(full_filename) + + # Save the model + for filename, tensors in state_dict_split.filename_to_tensors.items(): + shard = {tensor: state_dict[tensor] for tensor in tensors} + self.save(shard, os.path.join(save_directory, filename), safe_serialization=safe_serialization) + + # Save index if sharded + if state_dict_split.is_sharded: + index = { + "metadata": state_dict_split.metadata, + "weight_map": state_dict_split.tensor_to_filename, + } + save_index_file = SAFE_WEIGHTS_INDEX_NAME if safe_serialization else WEIGHTS_INDEX_NAME + save_index_file = os.path.join(save_directory, save_index_file) + with open(save_index_file, "w", encoding="utf-8") as f: + content = json.dumps(index, indent=2, sort_keys=True) + "\n" + f.write(content) + logger.info( + f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be " + f"split in {len(state_dict_split.filename_to_tensors)} checkpoint shards. You can find where each parameters has been saved in the " + f"index located at {save_index_file}." + ) + else: + path_to_weights = os.path.join(save_directory, WEIGHTS_NAME) + logger.info(f"Model weights saved in {path_to_weights}") + + def register_save_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle: + """ + Registers a pre hook to be run before `save_checkpoint` is called in [`Accelerator.save_state`]. + + Args: + hook (`Callable`): + A function to be called in [`Accelerator.save_state`] before `save_checkpoint`. + + The hook should have the following signature: + + `hook(models: list[torch.nn.Module], weights: list[dict[str, torch.Tensor]], input_dir: str) -> None` + + The `models` argument are the models as saved in the accelerator state under `accelerator._models`, `weigths` + argument are the state dicts of the `models`, and the `input_dir` argument is the `input_dir` argument passed + to [`Accelerator.load_state`]. + + + + Should only be used in conjunction with [`Accelerator.register_load_state_pre_hook`]. Can be useful to save + configurations in addition to model weights. Can also be used to overwrite model saving with a customized + method. In this case, make sure to remove already loaded weights from the weights list. + + + + Returns: + `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling + `handle.remove()` + """ + handle = hooks.RemovableHandle(self._save_model_state_pre_hook) + self._save_model_state_pre_hook[handle.id] = hook + return handle + + def save_state(self, output_dir: str = None, safe_serialization: bool = True, **save_model_func_kwargs): + """ + Saves the current states of the model, optimizer, scaler, RNG generators, and registered objects to a folder. + + If a `ProjectConfiguration` was passed to the `Accelerator` object with `automatic_checkpoint_naming` enabled + then checkpoints will be saved to `self.project_dir/checkpoints`. If the number of current saves is greater + than `total_limit` then the oldest save is deleted. Each checkpoint is saved in seperate folders named + `checkpoint_`. + + Otherwise they are just saved to `output_dir`. + + + + Should only be used when wanting to save a checkpoint during training and restoring the state in the same + environment. + + + + Args: + output_dir (`str` or `os.PathLike`): + The name of the folder to save all relevant weights and states. + safe_serialization (`bool`, *optional*, defaults to `True`): + Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). + save_model_func_kwargs (`dict`, *optional*): + Additional keyword arguments for saving model which can be passed to the underlying save function, such + as optional arguments for DeepSpeed's `save_checkpoint` function. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer, lr_scheduler = ... + >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) + >>> accelerator.save_state(output_dir="my_checkpoint") + ``` + """ + if self.project_configuration.automatic_checkpoint_naming: + output_dir = os.path.join(self.project_dir, "checkpoints") + os.makedirs(output_dir, exist_ok=True) + if self.project_configuration.automatic_checkpoint_naming: + folders = [os.path.join(output_dir, folder) for folder in os.listdir(output_dir)] + if ( + self.project_configuration.total_limit is not None + and (len(folders) + 1 > self.project_configuration.total_limit) + and self.is_main_process + ): + + def _inner(folder): + return list(map(int, re.findall(r"[\/]?([0-9]+)(?=[^\/]*$)", folder)))[0] + + folders.sort(key=_inner) + logger.warning( + f"Deleting {len(folders) + 1 - self.project_configuration.total_limit} checkpoints to make room for new checkpoint." + ) + for folder in folders[: len(folders) + 1 - self.project_configuration.total_limit]: + shutil.rmtree(folder) + output_dir = os.path.join(output_dir, f"checkpoint_{self.save_iteration}") + if os.path.exists(output_dir): + raise ValueError( + f"Checkpoint directory {output_dir} ({self.save_iteration}) already exists. Please manually override `self.save_iteration` with what iteration to start with." + ) + self.wait_for_everyone() + os.makedirs(output_dir, exist_ok=True) + logger.info(f"Saving current state to {output_dir}") + + if self.distributed_type == DistributedType.XLA: + # Finish running the previous step before checkpointing + xm.mark_step() + + # Save the models taking care of FSDP and DeepSpeed nuances + weights = [] + for i, model in enumerate(self._models): + if self.distributed_type == DistributedType.FSDP: + logger.info("Saving FSDP model") + save_fsdp_model(self.state.fsdp_plugin, self, model, output_dir, i) + logger.info(f"FSDP Model saved to output dir {output_dir}") + elif self.distributed_type == DistributedType.DEEPSPEED: + logger.info("Saving DeepSpeed Model and Optimizer") + ckpt_id = f"{MODEL_NAME}" if i == 0 else f"{MODEL_NAME}_{i}" + model.save_checkpoint(output_dir, ckpt_id, **save_model_func_kwargs) + logger.info(f"DeepSpeed Model and Optimizer saved to output dir {os.path.join(output_dir, ckpt_id)}") + elif self.distributed_type == DistributedType.MEGATRON_LM: + logger.info("Saving Megatron-LM Model, Optimizer and Scheduler") + model.save_checkpoint(output_dir) + logger.info(f"Megatron-LM Model , Optimizer and Scheduler saved to output dir {output_dir}") + else: + weights.append(self.get_state_dict(model, unwrap=False)) + + # Save the optimizers taking care of FSDP and DeepSpeed nuances + optimizers = [] + if self.distributed_type == DistributedType.FSDP: + for i, opt in enumerate(self._optimizers): + logger.info("Saving FSDP Optimizer") + save_fsdp_optimizer(self.state.fsdp_plugin, self, opt, self._models[i], output_dir, i) + logger.info(f"FSDP Optimizer saved to output dir {output_dir}") + elif self.distributed_type not in [DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]: + optimizers = self._optimizers + + # Save the lr schedulers taking care of DeepSpeed nuances + schedulers = [] + if self.distributed_type == DistributedType.DEEPSPEED: + for i, scheduler in enumerate(self._schedulers): + if isinstance(scheduler, DeepSpeedSchedulerWrapper): + continue + schedulers.append(scheduler) + elif self.distributed_type not in [DistributedType.MEGATRON_LM]: + schedulers = self._schedulers + + # Save the samplers of the dataloaders + dataloaders = self._dataloaders + + # Call model loading hooks that might have been registered with + # accelerator.register_model_state_hook + for hook in self._save_model_state_pre_hook.values(): + hook(self._models, weights, output_dir) + + save_location = save_accelerator_state( + output_dir, + weights, + optimizers, + schedulers, + dataloaders, + self.state.process_index, + self.step, + self.scaler, + save_on_each_node=self.project_configuration.save_on_each_node, + safe_serialization=safe_serialization, + ) + for i, obj in enumerate(self._custom_objects): + save_custom_state(obj, output_dir, i, save_on_each_node=self.project_configuration.save_on_each_node) + self.project_configuration.iteration += 1 + return save_location + + def register_load_state_pre_hook(self, hook: Callable[..., None]) -> hooks.RemovableHandle: + """ + Registers a pre hook to be run before [`load_checkpoint`] is called in [`Accelerator.load_state`]. + + Args: + hook (`Callable`): + A function to be called in [`Accelerator.load_state`] before `load_checkpoint`. + + The hook should have the following signature: + + `hook(models: list[torch.nn.Module], input_dir: str) -> None` + + The `models` argument are the models as saved in the accelerator state under `accelerator._models`, and the + `input_dir` argument is the `input_dir` argument passed to [`Accelerator.load_state`]. + + + + Should only be used in conjunction with [`Accelerator.register_save_state_pre_hook`]. Can be useful to load + configurations in addition to model weights. Can also be used to overwrite model loading with a customized + method. In this case, make sure to remove already loaded models from the models list. + + + + Returns: + `torch.utils.hooks.RemovableHandle`: a handle that can be used to remove the added hook by calling + `handle.remove()` + """ + handle = hooks.RemovableHandle(self._load_model_state_pre_hook) + self._load_model_state_pre_hook[handle.id] = hook + return handle + + def load_state(self, input_dir: str = None, **load_model_func_kwargs): + """ + Loads the current states of the model, optimizer, scaler, RNG generators, and registered objects. + + + + Should only be used in conjunction with [`Accelerator.save_state`]. If a file is not registered for + checkpointing, it will not be loaded if stored in the directory. + + + + Args: + input_dir (`str` or `os.PathLike`): + The name of the folder all relevant weights and states were saved in. Can be `None` if + `automatic_checkpoint_naming` is used, and will pick up from the latest checkpoint. + load_model_func_kwargs (`dict`, *optional*): + Additional keyword arguments for loading model which can be passed to the underlying load function, + such as optional arguments for DeepSpeed's `load_checkpoint` function or a `map_location` to load the + model and optimizer on. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer, lr_scheduler = ... + >>> model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) + >>> accelerator.load_state("my_checkpoint") + ``` + """ + if input_dir is not None: + # Check if folder exists + input_dir = os.path.expanduser(input_dir) + if not os.path.isdir(input_dir): + raise ValueError(f"Tried to find {input_dir} but folder does not exist") + elif self.project_configuration.automatic_checkpoint_naming: + # Pick up from automatic checkpoint naming + input_dir = os.path.join(self.project_dir, "checkpoints") + folders = [os.path.join(input_dir, folder) for folder in os.listdir(input_dir)] + + def _inner(folder): + return list(map(int, re.findall(r"[\/]?([0-9]+)(?=[^\/]*$)", folder)))[0] + + folders.sort(key=_inner) + input_dir = folders[-1] + else: + raise ValueError("No input_dir provided and automatic checkpoint naming is disabled.") + logger.info(f"Loading states from {input_dir}") + + # Load the models taking care of FSDP and DeepSpeed nuances + models = [] + for i, model in enumerate(self._models): + if self.distributed_type == DistributedType.FSDP: + logger.info("Loading FSDP model") + load_fsdp_model(self.state.fsdp_plugin, self, model, input_dir, i) + logger.info(f"FSDP Model loaded from input dir {input_dir}") + elif self.distributed_type == DistributedType.DEEPSPEED: + logger.info("Loading DeepSpeed Model and Optimizer") + ckpt_id = f"{MODEL_NAME}" if i == 0 else f"{MODEL_NAME}_{i}" + model.load_checkpoint(input_dir, ckpt_id, **load_model_func_kwargs) + logger.info(f"DeepSpeed Model and Optimizer loaded from input dir {os.path.join(input_dir, ckpt_id)}") + elif self.distributed_type == DistributedType.MEGATRON_LM: + logger.info("Loading Megatron-LM Model, Optimizer and Scheduler") + model.load_checkpoint(input_dir) + logger.info(f"Megatron-LM Model , Optimizer and Scheduler loaded from input dir {input_dir}") + else: + models.append(model) + + # Load the optimizers taking care of FSDP and DeepSpeed nuances + optimizers = [] + if self.distributed_type == DistributedType.FSDP: + for i, opt in enumerate(self._optimizers): + logger.info("Loading FSDP Optimizer") + load_fsdp_optimizer(self.state.fsdp_plugin, self, opt, self._models[i], input_dir, i) + logger.info(f"FSDP Optimizer loaded from input dir {input_dir}") + elif self.distributed_type not in [DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]: + optimizers = self._optimizers + + # Load the lr schedulers taking care of DeepSpeed nuances + schedulers = [] + if self.distributed_type == DistributedType.DEEPSPEED: + for i, scheduler in enumerate(self._schedulers): + if isinstance(scheduler, DeepSpeedSchedulerWrapper): + continue + schedulers.append(scheduler) + elif self.distributed_type not in [DistributedType.MEGATRON_LM]: + schedulers = self._schedulers + + dataloaders = self._dataloaders + + # Call model loading hooks that might have been registered with + # accelerator.register_model_state_hook + for hook in self._load_model_state_pre_hook.values(): + hook(models, input_dir) + + map_location = load_model_func_kwargs.pop("map_location", None) + if map_location is None: + if self.num_processes > 1 and self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + ): + map_location = "on_device" + else: + map_location = "cpu" + + override_attributes = load_accelerator_state( + input_dir, + models, + optimizers, + schedulers, + dataloaders, + self.state.process_index, + self.scaler, + map_location, + **load_model_func_kwargs, + ) + if "step" in override_attributes: + self.step = override_attributes["step"] + custom_checkpoints = [ + f for f in os.listdir(input_dir) if re.search(r"^custom_checkpoint_\d+\.pkl$", f) is not None + ] + if len(custom_checkpoints) != len(self._custom_objects): + err = ( + f"Number of custom checkpoints in folder {input_dir} does not match the number of registered objects:" + ) + err += f"\n\tFound checkpoints: {len(custom_checkpoints)}" + err += f"\n\tRegistered objects: {len(self._custom_objects)}\n" + err += "Please make sure to only load checkpoints from folders that were created with the same set of registered objects," + err += "or avoid using `custom_checkpoint` in the filename for files in that same directory and load them in manually." + raise RuntimeError(err) + else: + logger.info(f"Loading in {len(custom_checkpoints)} custom states") + for index, obj in enumerate(self._custom_objects): + load_custom_state(obj, input_dir, index) + + def free_memory(self, *objects): + """ + Will release all references to the internal objects stored and call the garbage collector. You should call this + method between two trainings with different models/optimizers. Also will reset `Accelerator.step` to 0. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer, scheduler = ... + >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) + >>> model, optimizer, scheduler = accelerator.free_memory(model, optimizer, scheduler) + ``` + """ + # Deepspeed needs a bit more prep that should be done first + if hasattr(self, "deepspeed_engine_wrapped"): + if self.deepspeed_engine_wrapped is not None: + self.deepspeed_engine_wrapped.engine.destroy() + self.deepspeed_engine_wrapped = None + objects = release_memory(*objects) + self._schedulers = [] + self._optimizers = [] + self._models = [] + self._dataloaders = [] + self.step = 0 + return objects + + def clear(self, *objects): + """ + Alias for [`Accelerate.free_memory`], releases all references to the internal objects stored and call the + garbage collector. You should call this method between two trainings with different models/optimizers. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> model, optimizer, scheduler = ... + >>> model, optimizer, scheduler = accelerator.prepare(model, optimizer, scheduler) + >>> model, optimizer, scheduler = accelerator.clear(model, optimizer, scheduler) + ``` + """ + return self.free_memory(*objects) + + def _get_named_parameters(self, *args): + named_parameters = {} + for obj in args: + if isinstance(obj, torch.nn.Module): + obj = extract_model_from_parallel(obj) + named_parameters.update({n: p for n, p in obj.named_parameters()}) + return named_parameters + + def _get_devices(self, *args): + model_device = None + optimizer_device = None + for obj in args: + # Loop through model parameters and stop at the first once we have its device. + if isinstance(obj, torch.nn.Module): + for param in obj.parameters(): + model_device = param.device + break + # Loop through optimizer parameters groups and stop at the first once we have its device. + if isinstance(obj, torch.optim.Optimizer): + for param_group in obj.param_groups: + if len(param_group["params"]) > 0: + optimizer_device = param_group["params"][0].device + break + return (model_device, optimizer_device) + + def get_state_dict(self, model, unwrap=True): + """ + Returns the state dictionary of a model sent through [`Accelerator.prepare`] potentially without full + precision. + + Args: + model (`torch.nn.Module`): + A PyTorch model sent through [`Accelerator.prepare`] + unwrap (`bool`, *optional*, defaults to `True`): + Whether to return the original underlying state_dict of `model` or to return the wrapped state_dict + + Returns: + `dict`: The state dictionary of the model potentially without full precision. + + Example: + + ```python + >>> import torch + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> net = torch.nn.Linear(2, 2) + >>> net = accelerator.prepare(net) + >>> state_dict = accelerator.get_state_dict(net) + ``` + """ + + if self.distributed_type == DistributedType.DEEPSPEED: + if self.deepspeed_config["zero_optimization"]["stage"] == 3: + if model.zero_gather_16bit_weights_on_model_save(): + state_dict = model._zero3_consolidated_16bit_state_dict() + else: + raise ValueError( + "Cannot get 16bit model weights because `stage3_gather_16bit_weights_on_model_save` in DeepSpeed config is False. " + "To save the model weights in 16bit, set `stage3_gather_16bit_weights_on_model_save` to True in DeepSpeed config file or " + "set `zero3_save_16bit_model` to True when using `accelerate config`. " + "To save the full checkpoint, run `model.save_checkpoint(save_dir)` and use `zero_to_fp32.py` to recover weights." + ) + else: + from deepspeed.checkpoint.utils import clone_tensors_for_torch_save + + state_dict = clone_tensors_for_torch_save(self.unwrap_model(model).state_dict()) + elif self.distributed_type == DistributedType.FSDP: + from torch.distributed.fsdp import FullStateDictConfig, StateDictType + from torch.distributed.fsdp import FullyShardedDataParallel as FSDP + + if unwrap: + model = self.unwrap_model(model) + full_state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + with FSDP.state_dict_type(model, StateDictType.FULL_STATE_DICT, full_state_dict_config): + state_dict = model.state_dict() + else: + if unwrap: + model = self.unwrap_model(model) + state_dict = model.state_dict() + + return state_dict + + def register_for_checkpointing(self, *objects): + """ + Makes note of `objects` and will save or load them in during `save_state` or `load_state`. + + These should be utilized when the state is being loaded or saved in the same script. It is not designed to be + used in different scripts. + + + + Every `object` must have a `load_state_dict` and `state_dict` function to be stored. + + + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> # Assume `CustomObject` has a `state_dict` and `load_state_dict` function. + >>> obj = CustomObject() + >>> accelerator.register_for_checkpointing(obj) + >>> accelerator.save_state("checkpoint.pt") + ``` + """ + invalid_objects = [] + for obj in objects: + if not hasattr(obj, "state_dict") or not hasattr(obj, "load_state_dict"): + invalid_objects.append(obj) + if len(invalid_objects) > 0: + err = "All `objects` must include a `state_dict` and `load_state_dict` function to be stored. The following inputs are invalid:" + for index, obj in enumerate(invalid_objects): + err += f"\n\t- Item at index {index}, `{get_pretty_name(obj)}`" + raise ValueError(err) + self._custom_objects.extend(objects) + + @contextmanager + def autocast(self, cache_enabled: bool = False, autocast_handler: AutocastKwargs = None): + """ + Will apply automatic mixed-precision inside the block inside this context manager, if it is enabled. Nothing + different will happen otherwise. + + A different `autocast_handler` can be passed in to override the one set in the `Accelerator` object. This is + useful in blocks under `autocast` where you want to revert to fp32. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator(mixed_precision="fp16") + >>> with accelerator.autocast(): + ... train() + ``` + """ + if cache_enabled: + warnings.warn( + "Passing `cache_enabled=True` to `accelerator.autocast` is deprecated and will be removed in v0.23.0. " + "Please use the `AutocastKwargs` class instead and pass it to the `Accelerator` as a `kwarg_handler`.", + FutureWarning, + ) + if self.autocast_handler is not None: + self.autocast_handler.cache_enabled = True + else: + self.autocast_handler = AutocastKwargs(cache_enabled=True) + if autocast_handler is None: + autocast_handler = self.autocast_handler + autocast_context = get_mixed_precision_context_manager(self.native_amp, autocast_handler) + autocast_context.__enter__() + # TODO: should the `yield` be in a try/finally block? + yield + autocast_context.__exit__(*sys.exc_info()) + + @contextmanager + def profile(self, profile_handler: ProfileKwargs | None = None): + """ + Will profile the code inside the context manager. The profile will be saved to a Chrome Trace file if + `profile_handler.output_trace_dir` is set. + + A different `profile_handler` can be passed in to override the one set in the `Accelerator` object. + + Args: + profile_handler (`ProfileKwargs`, *optional*): + The profile handler to use for this context manager. If not passed, will use the one set in the + `Accelerator` object. + + Example: + + ```python + # Profile with default settings + from accelerate import Accelerator + from accelerate.utils import ProfileKwargs + + accelerator = Accelerator() + with accelerator.profile() as prof: + train() + accelerator.print(prof.key_averages().table()) + + + # Profile with the custom handler + def custom_handler(prof): + print(prof.key_averages().table(sort_by="self_cpu_time_total", row_limit=10)) + + + kwargs = ProfileKwargs(schedule_option=dict(wait=1, warmup=1, active=1), on_trace_ready=custom_handler) + accelerator = Accelerator(kwarg_handler=[kwargs]) + with accelerator.profile() as prof: + for _ in range(10): + train_iteration() + prof.step() + + + # Profile and export to Chrome Trace + kwargs = ProfileKwargs(output_trace_dir="output_trace") + accelerator = Accelerator(kwarg_handler=[kwargs]) + with accelerator.profile(): + train() + ``` + """ + profile_handler = profile_handler or self.profile_handler or ProfileKwargs() + + with profile_handler.build() as profiler: + yield profiler + + if profile_handler.output_trace_dir is None: + return + + os.makedirs(profile_handler.output_trace_dir, exist_ok=True) + profiler.export_chrome_trace( + os.path.join(profile_handler.output_trace_dir, PROFILE_PATTERN_NAME.format(suffix=self.process_index)) + ) + self.wait_for_everyone() + + @property + def optimizer_step_was_skipped(self): + """ + Whether or not the optimizer update was skipped (because of gradient overflow in mixed precision), in which + case the learning rate should not be changed. + """ + for optimizer in self._optimizers: + if optimizer.step_was_skipped: + return True + return False + + def skip_first_batches(self, dataloader, num_batches: int = 0): + """ + Creates a new `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. + + Args: + dataloader (`torch.utils.data.DataLoader`): The data loader in which to skip batches. + num_batches (`int`, *optional*, defaults to 0): The number of batches to skip + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> dataloader, model, optimizer, scheduler = accelerator.prepare(dataloader, model, optimizer, scheduler) + >>> skipped_dataloader = accelerator.skip_first_batches(dataloader, num_batches=2) + >>> # for the first epoch only + >>> for input, target in skipped_dataloader: + ... optimizer.zero_grad() + ... output = model(input) + ... loss = loss_func(output, target) + ... accelerator.backward(loss) + ... optimizer.step() + + >>> # subsequent epochs + >>> for input, target in dataloader: + ... optimizer.zero_grad() + ... ... + ``` + """ + return skip_first_batches(dataloader, num_batches=num_batches) + + def __deepcopy__(self, memo): + logger.info("Deep copying the `Accelerator` object, note that this will point to the same original object.") + return self + + def verify_device_map(self, model: torch.nn.Module) -> bool: + """ + Verifies that `model` has not been prepared with big model inference with a device-map resembling `auto`. + """ + # Checks if any of the child modules has the attribute `hf_device_map` and this map has more than one entry. + for m in model.modules(): + if hasattr(m, "hf_device_map") and len(m.hf_device_map) > 1: + return True + + return False + + def lomo_backward(self, loss: torch.Tensor, learning_rate: float) -> None: + """ + Runs backward pass on LOMO optimizers. + """ + if is_lomo_available(): + # We need to import locally to avoid circular imports since lomo imports stuff from + # transformers & accelerate + from lomo_optim import AdaLomo, Lomo + + if learning_rate is None: + raise ValueError("A learning rate must be passed in order to call backward pass with LOMO optimizers.") + + _backward_called = False + + for optimizer in self._optimizers: + if isinstance(optimizer.optimizer, (Lomo, AdaLomo)): + optimizer.optimizer.fused_backward(loss, learning_rate) + _backward_called = True + + if not _backward_called: + raise ValueError( + "Backward pass not properly called on LOMO optimizers. Are you sure you passed a LOMO optimizer in accelerator.prepare()?" + ) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/big_modeling.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/big_modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..065d6ad6eab7ed72844ea1f8186809bed783ccfa --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/big_modeling.py @@ -0,0 +1,633 @@ +# 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. + +import logging +import os +from contextlib import contextmanager +from functools import wraps +from typing import Dict, List, Optional, Union + +import torch +import torch.nn as nn + +from .hooks import ( + AlignDevicesHook, + CpuOffload, + UserCpuOffloadHook, + add_hook_to_module, + attach_align_device_hook, + attach_align_device_hook_on_blocks, +) +from .utils import ( + OffloadedWeightsLoader, + check_cuda_p2p_ib_support, + check_device_map, + extract_submodules_state_dict, + find_tied_parameters, + get_balanced_memory, + infer_auto_device_map, + is_mlu_available, + is_musa_available, + is_npu_available, + is_torch_version, + is_xpu_available, + load_checkpoint_in_model, + offload_state_dict, + parse_flag_from_env, + retie_parameters, +) +from .utils.other import recursive_getattr + + +logger = logging.getLogger(__name__) + + +@contextmanager +def init_empty_weights(include_buffers: bool = None): + """ + A context manager under which models are initialized with all parameters on the meta device, therefore creating an + empty model. Useful when just initializing the model would blow the available RAM. + + Args: + include_buffers (`bool`, *optional*): + Whether or not to also put all buffers on the meta device while initializing. + + Example: + + ```python + import torch.nn as nn + from accelerate import init_empty_weights + + # Initialize a model with 100 billions parameters in no time and without using any RAM. + with init_empty_weights(): + tst = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) + ``` + + + + Any model created under this context manager has no weights. As such you can't do something like + `model.to(some_device)` with it. To load weights inside your empty model, see [`load_checkpoint_and_dispatch`]. + Make sure to overwrite the default device_map param for [`load_checkpoint_and_dispatch`], otherwise dispatch is not + called. + + + """ + if include_buffers is None: + include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False) + with init_on_device(torch.device("meta"), include_buffers=include_buffers) as f: + yield f + + +@contextmanager +def init_on_device(device: torch.device, include_buffers: bool = None): + """ + A context manager under which models are initialized with all parameters on the specified device. + + Args: + device (`torch.device`): + Device to initialize all parameters on. + include_buffers (`bool`, *optional*): + Whether or not to also put all buffers on the meta device while initializing. + + Example: + + ```python + import torch.nn as nn + from accelerate import init_on_device + + with init_on_device(device=torch.device("cuda")): + tst = nn.Liner(100, 100) # on `cuda` device + ``` + """ + if include_buffers is None: + include_buffers = parse_flag_from_env("ACCELERATE_INIT_INCLUDE_BUFFERS", False) + + # TODO(shingjan): remove the torch version check once older versions are deprecated + if is_torch_version(">=", "2.0") and include_buffers: + with device: + yield + return + + old_register_parameter = nn.Module.register_parameter + if include_buffers: + old_register_buffer = nn.Module.register_buffer + + def register_empty_parameter(module, name, param): + old_register_parameter(module, name, param) + if param is not None: + param_cls = type(module._parameters[name]) + kwargs = module._parameters[name].__dict__ + kwargs["requires_grad"] = param.requires_grad + module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs) + + def register_empty_buffer(module, name, buffer, persistent=True): + old_register_buffer(module, name, buffer, persistent=persistent) + if buffer is not None: + module._buffers[name] = module._buffers[name].to(device) + + # Patch tensor creation + if include_buffers: + tensor_constructors_to_patch = { + torch_function_name: getattr(torch, torch_function_name) + for torch_function_name in ["empty", "zeros", "ones", "full"] + } + else: + tensor_constructors_to_patch = {} + + def patch_tensor_constructor(fn): + def wrapper(*args, **kwargs): + kwargs["device"] = device + return fn(*args, **kwargs) + + return wrapper + + try: + nn.Module.register_parameter = register_empty_parameter + if include_buffers: + nn.Module.register_buffer = register_empty_buffer + for torch_function_name in tensor_constructors_to_patch.keys(): + setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name))) + yield + finally: + nn.Module.register_parameter = old_register_parameter + if include_buffers: + nn.Module.register_buffer = old_register_buffer + for torch_function_name, old_torch_function in tensor_constructors_to_patch.items(): + setattr(torch, torch_function_name, old_torch_function) + + +def cpu_offload( + model: nn.Module, + execution_device: Optional[torch.device] = None, + offload_buffers: bool = False, + state_dict: Optional[Dict[str, torch.Tensor]] = None, + preload_module_classes: Optional[List[str]] = None, +): + """ + Activates full CPU offload for a model. As a result, all parameters of the model will be offloaded and only one + copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that + state dict and put on the execution device passed as they are needed, then offloaded again. + + Args: + model (`torch.nn.Module`): + The model to offload. + execution_device (`torch.device`, *optional*): + The device on which the forward pass of the model will be executed (should be a GPU). Will default to the + model first parameter device. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to offload the buffers with the model parameters. + state_dict (`Dict[str, torch.Tensor]`, *optional*): + The state dict of the model that will be kept on CPU. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + """ + if execution_device is None: + execution_device = next(iter(model.parameters())).device + if state_dict is None: + state_dict = {n: p.to("cpu") for n, p in model.state_dict().items()} + + add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True) + attach_align_device_hook( + model, + execution_device=execution_device, + offload=True, + offload_buffers=offload_buffers, + weights_map=state_dict, + preload_module_classes=preload_module_classes, + ) + + return model + + +def cpu_offload_with_hook( + model: torch.nn.Module, + execution_device: Optional[Union[int, str, torch.device]] = None, + prev_module_hook: Optional[UserCpuOffloadHook] = None, +): + """ + Offloads a model on the CPU and puts it back to an execution device when executed. The difference with + [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when + the `offload` method of the returned `hook` is called. Useful for pipelines running a model in a loop. + + Args: + model (`torch.nn.Module`): + The model to offload. + execution_device(`str`, `int` or `torch.device`, *optional*): + The device on which the model should be executed. Will default to the MPS device if it's available, then + GPU 0 if there is a GPU, and finally to the CPU. + prev_module_hook (`UserCpuOffloadHook`, *optional*): + The hook sent back by this function for a previous model in the pipeline you are running. If passed, its + offload method will be called just before the forward of the model to which this hook is attached. + + Example: + + ```py + model_1, hook_1 = cpu_offload_with_hook(model_1, cuda_device) + model_2, hook_2 = cpu_offload_with_hook(model_2, cuda_device, prev_module_hook=hook_1) + model_3, hook_3 = cpu_offload_with_hook(model_3, cuda_device, prev_module_hook=hook_2) + + hid_1 = model_1(input) + for i in range(50): + # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop. + hid_2 = model_2(hid_1) + # model2 is offloaded to the CPU just before this forward. + hid_3 = model_3(hid_3) + + # For model3, you need to manually call the hook offload method. + hook_3.offload() + ``` + """ + hook = CpuOffload(execution_device=execution_device, prev_module_hook=prev_module_hook) + add_hook_to_module(model, hook, append=True) + user_hook = UserCpuOffloadHook(model, hook) + return model, user_hook + + +def disk_offload( + model: nn.Module, + offload_dir: Union[str, os.PathLike], + execution_device: Optional[torch.device] = None, + offload_buffers: bool = False, + preload_module_classes: Optional[List[str]] = None, +): + """ + Activates full disk offload for a model. As a result, all parameters of the model will be offloaded as + memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and + put on the execution device passed as they are needed, then offloaded again. + + Args: + model (`torch.nn.Module`): The model to offload. + offload_dir (`str` or `os.PathLike`): + The folder in which to offload the model weights (or where the model weights are already offloaded). + execution_device (`torch.device`, *optional*): + The device on which the forward pass of the model will be executed (should be a GPU). Will default to the + model's first parameter device. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to offload the buffers with the model parameters. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + """ + if not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json")): + offload_state_dict(offload_dir, model.state_dict()) + if execution_device is None: + execution_device = next(iter(model.parameters())).device + weights_map = OffloadedWeightsLoader(save_folder=offload_dir) + + add_hook_to_module(model, AlignDevicesHook(io_same_device=True), append=True) + attach_align_device_hook( + model, + execution_device=execution_device, + offload=True, + offload_buffers=offload_buffers, + weights_map=weights_map, + preload_module_classes=preload_module_classes, + ) + + return model + + +def dispatch_model( + model: nn.Module, + device_map: Dict[str, Union[str, int, torch.device]], + main_device: Optional[torch.device] = None, + state_dict: Optional[Dict[str, torch.Tensor]] = None, + offload_dir: Optional[Union[str, os.PathLike]] = None, + offload_index: Optional[Dict[str, str]] = None, + offload_buffers: bool = False, + skip_keys: Optional[Union[str, List[str]]] = None, + preload_module_classes: Optional[List[str]] = None, + force_hooks: bool = False, +): + """ + Dispatches a model according to a given device map. Layers of the model might be spread across GPUs, offloaded on + the CPU or even the disk. + + Args: + model (`torch.nn.Module`): + The model to dispatch. + device_map (`Dict[str, Union[str, int, torch.device]]`): + A dictionary mapping module names in the models `state_dict` to the device they should go to. Note that + `"disk"` is accepted even if it's not a proper value for `torch.device`. + main_device (`str`, `int` or `torch.device`, *optional*): + The main execution device. Will default to the first device in the `device_map` different from `"cpu"` or + `"disk"`. + state_dict (`Dict[str, torch.Tensor]`, *optional*): + The state dict of the part of the model that will be kept on CPU. + offload_dir (`str` or `os.PathLike`): + The folder in which to offload the model weights (or where the model weights are already offloaded). + offload_index (`Dict`, *optional*): + A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default + to the index saved in `save_folder`. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to offload the buffers with the model parameters. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + force_hooks (`bool`, *optional*, defaults to `False`): + Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a + single device. + """ + # Error early if the device map is incomplete. + check_device_map(model, device_map) + + # for backward compatibility + is_bnb_quantized = ( + getattr(model, "is_quantized", False) or getattr(model, "is_loaded_in_8bit", False) + ) and getattr(model, "quantization_method", "bitsandbytes") == "bitsandbytes" + + # We attach hooks if the device_map has at least 2 different devices or if + # force_hooks is set to `True`. Otherwise, the model in already loaded + # in the unique device and the user can decide where to dispatch the model. + # If the model is quantized, we always force-dispatch the model + if (len(set(device_map.values())) > 1) or is_bnb_quantized or force_hooks: + if main_device is None: + if set(device_map.values()) == {"cpu"} or set(device_map.values()) == {"cpu", "disk"}: + main_device = "cpu" + else: + main_device = [d for d in device_map.values() if d not in ["cpu", "disk"]][0] + + if main_device != "cpu": + cpu_modules = [name for name, device in device_map.items() if device == "cpu"] + if state_dict is None and len(cpu_modules) > 0: + state_dict = extract_submodules_state_dict(model.state_dict(), cpu_modules) + + disk_modules = [name for name, device in device_map.items() if device == "disk"] + if offload_dir is None and offload_index is None and len(disk_modules) > 0: + raise ValueError( + "We need an `offload_dir` to dispatch this model according to this `device_map`, the following submodules " + f"need to be offloaded: {', '.join(disk_modules)}." + ) + if ( + len(disk_modules) > 0 + and offload_index is None + and (not os.path.isdir(offload_dir) or not os.path.isfile(os.path.join(offload_dir, "index.json"))) + ): + disk_state_dict = extract_submodules_state_dict(model.state_dict(), disk_modules) + offload_state_dict(offload_dir, disk_state_dict) + + execution_device = { + name: main_device if device in ["cpu", "disk"] else device for name, device in device_map.items() + } + execution_device[""] = main_device + offloaded_devices = ["disk"] if main_device == "cpu" or main_device == "mps" else ["cpu", "disk"] + offload = {name: device in offloaded_devices for name, device in device_map.items()} + save_folder = offload_dir if len(disk_modules) > 0 else None + if state_dict is not None or save_folder is not None or offload_index is not None: + device = main_device if offload_index is not None else None + weights_map = OffloadedWeightsLoader( + state_dict=state_dict, save_folder=save_folder, index=offload_index, device=device + ) + else: + weights_map = None + + # When dispatching the model's parameters to the devices specified in device_map, we want to avoid allocating memory several times for the + # tied parameters. The dictionary tied_params_map keeps track of the already allocated data for a given tied parameter (represented by its + # original pointer) on each devices. + tied_params = find_tied_parameters(model) + + tied_params_map = {} + for group in tied_params: + for param_name in group: + # data_ptr() is enough here, as `find_tied_parameters` finds tied params simply by comparing `param1 is param2`, so we don't need + # to care about views of tensors through storage_offset. + data_ptr = recursive_getattr(model, param_name).data_ptr() + tied_params_map[data_ptr] = {} + + # Note: To handle the disk offloading case, we can not simply use weights_map[param_name].data_ptr() as the reference pointer, + # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer. + + attach_align_device_hook_on_blocks( + model, + execution_device=execution_device, + offload=offload, + offload_buffers=offload_buffers, + weights_map=weights_map, + skip_keys=skip_keys, + preload_module_classes=preload_module_classes, + tied_params_map=tied_params_map, + ) + + # warn if there is any params on the meta device + offloaded_devices_str = " and ".join( + [device for device in set(device_map.values()) if device in ("cpu", "disk")] + ) + if len(offloaded_devices_str) > 0: + logger.warning( + f"Some parameters are on the meta device because they were offloaded to the {offloaded_devices_str}." + ) + + # Attaching the hook may break tied weights, so we retie them + retie_parameters(model, tied_params) + + # add warning to cuda and to method + def add_warning(fn, model): + @wraps(fn) + def wrapper(*args, **kwargs): + warning_msg = "You shouldn't move a model that is dispatched using accelerate hooks." + if str(fn.__name__) == "to": + to_device = torch._C._nn._parse_to(*args, **kwargs)[0] + if to_device is not None: + logger.warning(warning_msg) + else: + logger.warning(warning_msg) + for param in model.parameters(): + if param.device == torch.device("meta"): + raise RuntimeError("You can't move a model that has some modules offloaded to cpu or disk.") + return fn(*args, **kwargs) + + return wrapper + + # Make sure to update _accelerate_added_attributes in hooks.py if you add any hook + model.to = add_warning(model.to, model) + if is_npu_available(): + model.npu = add_warning(model.npu, model) + elif is_mlu_available(): + model.mlu = add_warning(model.mlu, model) + elif is_musa_available(): + model.musa = add_warning(model.musa, model) + elif is_xpu_available(): + model.xpu = add_warning(model.xpu, model) + else: + model.cuda = add_warning(model.cuda, model) + + # Check if we are using multi-gpus with RTX 4000 series + use_multi_gpu = len([device for device in set(device_map.values()) if device not in ("cpu", "disk")]) > 1 + if use_multi_gpu and not check_cuda_p2p_ib_support(): + logger.warning( + "We've detected an older driver with an RTX 4000 series GPU. These drivers have issues with P2P. " + "This can affect the multi-gpu inference when using accelerate device_map." + "Please make sure to update your driver to the latest version which resolves this." + ) + else: + device = list(device_map.values())[0] + # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)). + if is_npu_available() and isinstance(device, int): + device = f"npu:{device}" + elif is_mlu_available() and isinstance(device, int): + device = f"mlu:{device}" + elif is_musa_available() and isinstance(device, int): + device = f"musa:{device}" + elif is_xpu_available() and isinstance(device, int): + device = f"xpu:{device}" + if device != "disk": + model.to(device) + else: + raise ValueError( + "You are trying to offload the whole model to the disk. Please use the `disk_offload` function instead." + ) + # Convert OrderedDict back to dict for easier usage + model.hf_device_map = dict(device_map) + return model + + +def load_checkpoint_and_dispatch( + model: nn.Module, + checkpoint: Union[str, os.PathLike], + device_map: Optional[Union[str, Dict[str, Union[int, str, torch.device]]]] = None, + max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None, + no_split_module_classes: Optional[List[str]] = None, + offload_folder: Optional[Union[str, os.PathLike]] = None, + offload_buffers: bool = False, + dtype: Optional[Union[str, torch.dtype]] = None, + offload_state_dict: Optional[bool] = None, + skip_keys: Optional[Union[str, List[str]]] = None, + preload_module_classes: Optional[List[str]] = None, + force_hooks: bool = False, + strict: bool = False, +): + """ + Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are + loaded and adds the various hooks that will make this model run properly (even if split across devices). + + Args: + model (`torch.nn.Module`): The model in which we want to load a checkpoint. + checkpoint (`str` or `os.PathLike`): + The folder checkpoint to load. It can be: + - a path to a file containing a whole model state dict + - a path to a `.json` file containing the index to a sharded checkpoint + - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint. + device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): + A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer + name, once a given module name is inside, every submodule of it will be sent to the same device. + + To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For more + information about each option see [here](../concept_guides/big_model_inference#designing-a-device-map). + Defaults to None, which means [`dispatch_model`] will not be called. + max_memory (`Dict`, *optional*): + A dictionary device identifier to maximum memory. Will default to the maximum memory available for each GPU + and the available CPU RAM if unset. + no_split_module_classes (`List[str]`, *optional*): + A list of layer class names that should never be split across device (for instance any layer that has a + residual connection). + offload_folder (`str` or `os.PathLike`, *optional*): + If the `device_map` contains any value `"disk"`, the folder where we will offload weights. + offload_buffers (`bool`, *optional*, defaults to `False`): + In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as + well as the parameters. + dtype (`str` or `torch.dtype`, *optional*): + If provided, the weights will be converted to that type when loaded. + offload_state_dict (`bool`, *optional*): + If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if + the weight of the CPU state dict + the biggest shard does not fit. Will default to `True` if the device map + picked contains `"disk"` values. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + force_hooks (`bool`, *optional*, defaults to `False`): + Whether or not to force device hooks to be attached to the model even if all layers are dispatched to a + single device. + strict (`bool`, *optional*, defaults to `False`): + Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's + state_dict. + + Example: + + ```python + >>> from accelerate import init_empty_weights, load_checkpoint_and_dispatch + >>> from huggingface_hub import hf_hub_download + >>> from transformers import AutoConfig, AutoModelForCausalLM + + >>> # Download the Weights + >>> checkpoint = "EleutherAI/gpt-j-6B" + >>> weights_location = hf_hub_download(checkpoint, "pytorch_model.bin") + + >>> # Create a model and initialize it with empty weights + >>> config = AutoConfig.from_pretrained(checkpoint) + >>> with init_empty_weights(): + ... model = AutoModelForCausalLM.from_config(config) + + >>> # Load the checkpoint and dispatch it to the right devices + >>> model = load_checkpoint_and_dispatch( + ... model, weights_location, device_map="auto", no_split_module_classes=["GPTJBlock"] + ... ) + ``` + """ + if isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: + raise ValueError( + "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " + "'sequential'." + ) + if isinstance(device_map, str): + if device_map != "sequential": + max_memory = get_balanced_memory( + model, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + dtype=dtype, + low_zero=(device_map == "balanced_low_0"), + ) + device_map = infer_auto_device_map( + model, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + dtype=dtype, + offload_buffers=offload_buffers, + ) + if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): + offload_state_dict = True + load_checkpoint_in_model( + model, + checkpoint, + device_map=device_map, + offload_folder=offload_folder, + dtype=dtype, + offload_state_dict=offload_state_dict, + offload_buffers=offload_buffers, + strict=strict, + ) + if device_map is None: + return model + return dispatch_model( + model, + device_map=device_map, + offload_dir=offload_folder, + offload_buffers=offload_buffers, + skip_keys=skip_keys, + preload_module_classes=preload_module_classes, + force_hooks=force_hooks, + ) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/checkpointing.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..04fe527e21c4f802132cee5e720021b3f71a9cb9 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/checkpointing.py @@ -0,0 +1,302 @@ +# 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. + +import random +from pathlib import Path +from typing import List + +import numpy as np +import torch +from safetensors.torch import load_model +from torch.cuda.amp import GradScaler + +from .utils import ( + MODEL_NAME, + OPTIMIZER_NAME, + RNG_STATE_NAME, + SAFE_MODEL_NAME, + SAFE_WEIGHTS_NAME, + SAMPLER_NAME, + SCALER_NAME, + SCHEDULER_NAME, + WEIGHTS_NAME, + get_pretty_name, + is_mlu_available, + is_torch_xla_available, + is_xpu_available, + save, +) + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + +from .logging import get_logger +from .state import PartialState + + +logger = get_logger(__name__) + + +def save_accelerator_state( + output_dir: str, + model_states: List[dict], + optimizers: list, + schedulers: list, + dataloaders: list, + process_index: int, + step: int, + scaler: GradScaler = None, + save_on_each_node: bool = False, + safe_serialization: bool = True, +): + """ + Saves the current states of the models, optimizers, scaler, and RNG generators to a given directory. + + + + If `safe_serialization` is `True`, models will be saved with `safetensors` while the rest are saved using native + `pickle`. + + + + Args: + output_dir (`str` or `os.PathLike`): + The name of the folder to save all relevant weights and states. + model_states (`List[torch.nn.Module]`): + A list of model states + optimizers (`List[torch.optim.Optimizer]`): + A list of optimizer instances + schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`): + A list of learning rate schedulers + dataloaders (`List[torch.utils.data.DataLoader]`): + A list of dataloader instances to save their sampler states + process_index (`int`): + The current process index in the Accelerator state + step (`int`): + The current step in the internal step tracker + scaler (`torch.cuda.amp.GradScaler`, *optional*): + An optional gradient scaler instance to save + save_on_each_node (`bool`, *optional*): + Whether to save on every node, or only the main node. + safe_serialization (`bool`, *optional*, defaults to `True`): + Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`). + """ + output_dir = Path(output_dir) + # Model states + for i, state in enumerate(model_states): + weights_name = WEIGHTS_NAME if not safe_serialization else SAFE_WEIGHTS_NAME + if i > 0: + weights_name = weights_name.replace(".", f"_{i}.") + output_model_file = output_dir.joinpath(weights_name) + save(state, output_model_file, save_on_each_node=save_on_each_node, safe_serialization=safe_serialization) + logger.info(f"Model weights saved in {output_model_file}") + # Optimizer states + for i, opt in enumerate(optimizers): + state = opt.state_dict() + optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin" + output_optimizer_file = output_dir.joinpath(optimizer_name) + save(state, output_optimizer_file, save_on_each_node=save_on_each_node, safe_serialization=False) + logger.info(f"Optimizer state saved in {output_optimizer_file}") + # Scheduler states + for i, scheduler in enumerate(schedulers): + state = scheduler.state_dict() + scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin" + output_scheduler_file = output_dir.joinpath(scheduler_name) + save(state, output_scheduler_file, save_on_each_node=save_on_each_node, safe_serialization=False) + logger.info(f"Scheduler state saved in {output_scheduler_file}") + # DataLoader states + for i, dataloader in enumerate(dataloaders): + sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin" + output_sampler_file = output_dir.joinpath(sampler_name) + # Only save if we have our custom sampler + from .data_loader import IterableDatasetShard, SeedableRandomSampler + + if isinstance(dataloader.dataset, IterableDatasetShard): + sampler = dataloader.get_sampler() + if isinstance(sampler, SeedableRandomSampler): + save(sampler, output_sampler_file, save_on_each_node=save_on_each_node, safe_serialization=False) + if getattr(dataloader, "use_stateful_dataloader", False): + dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin" + output_dataloader_state_dict_file = output_dir.joinpath(dataloader_state_dict_name) + state_dict = dataloader.state_dict() + torch.save(state_dict, output_dataloader_state_dict_file) + logger.info(f"Sampler state for dataloader {i} saved in {output_sampler_file}") + + # GradScaler state + if scaler is not None: + state = scaler.state_dict() + output_scaler_file = output_dir.joinpath(SCALER_NAME) + torch.save(state, output_scaler_file) + logger.info(f"Gradient scaler state saved in {output_scaler_file}") + # Random number generator states + states = {} + states_name = f"{RNG_STATE_NAME}_{process_index}.pkl" + states["step"] = step + states["random_state"] = random.getstate() + states["numpy_random_seed"] = np.random.get_state() + states["torch_manual_seed"] = torch.get_rng_state() + if is_xpu_available(): + states["torch_xpu_manual_seed"] = torch.xpu.get_rng_state_all() + if is_mlu_available(): + states["torch_mlu_manual_seed"] = torch.mlu.get_rng_state_all() + else: + states["torch_cuda_manual_seed"] = torch.cuda.get_rng_state_all() + if is_torch_xla_available(): + states["xm_seed"] = xm.get_rng_state() + output_states_file = output_dir.joinpath(states_name) + torch.save(states, output_states_file) + logger.info(f"Random states saved in {output_states_file}") + return output_dir + + +def load_accelerator_state( + input_dir, + models, + optimizers, + schedulers, + dataloaders, + process_index, + scaler=None, + map_location=None, + **load_model_func_kwargs, +): + """ + Loads states of the models, optimizers, scaler, and RNG generators from a given directory. + + Args: + input_dir (`str` or `os.PathLike`): + The name of the folder to load all relevant weights and states. + models (`List[torch.nn.Module]`): + A list of model instances + optimizers (`List[torch.optim.Optimizer]`): + A list of optimizer instances + schedulers (`List[torch.optim.lr_scheduler._LRScheduler]`): + A list of learning rate schedulers + process_index (`int`): + The current process index in the Accelerator state + scaler (`torch.cuda.amp.GradScaler`, *optional*): + An optional *GradScaler* instance to load + map_location (`str`, *optional*): + What device to load the optimizer state onto. Should be one of either "cpu" or "on_device". + load_model_func_kwargs (`dict`, *optional*): + Additional arguments that can be passed to the model's `load_state_dict` method. + + Returns: + `dict`: Contains the `Accelerator` attributes to override while loading the state. + """ + # stores the `Accelerator` attributes to override + override_attributes = dict() + if map_location not in [None, "cpu", "on_device"]: + raise TypeError( + "Unsupported optimizer map location passed, please choose one of `None`, `'cpu'`, or `'on_device'`" + ) + if map_location is None: + map_location = "cpu" + elif map_location == "on_device": + map_location = PartialState().device + + input_dir = Path(input_dir) + # Model states + for i, model in enumerate(models): + ending = f"_{i}" if i > 0 else "" + input_model_file = input_dir.joinpath(f"{SAFE_MODEL_NAME}{ending}.safetensors") + if input_model_file.exists(): + load_model(model, input_model_file, device=str(map_location), **load_model_func_kwargs) + else: + # Load with torch + input_model_file = input_dir.joinpath(f"{MODEL_NAME}{ending}.bin") + state_dict = torch.load(input_model_file, map_location=map_location) + model.load_state_dict(state_dict, **load_model_func_kwargs) + logger.info("All model weights loaded successfully") + + # Optimizer states + for i, opt in enumerate(optimizers): + optimizer_name = f"{OPTIMIZER_NAME}.bin" if i == 0 else f"{OPTIMIZER_NAME}_{i}.bin" + input_optimizer_file = input_dir.joinpath(optimizer_name) + optimizer_state = torch.load(input_optimizer_file, map_location=map_location) + optimizers[i].load_state_dict(optimizer_state) + logger.info("All optimizer states loaded successfully") + + # Scheduler states + for i, scheduler in enumerate(schedulers): + scheduler_name = f"{SCHEDULER_NAME}.bin" if i == 0 else f"{SCHEDULER_NAME}_{i}.bin" + input_scheduler_file = input_dir.joinpath(scheduler_name) + scheduler.load_state_dict(torch.load(input_scheduler_file)) + logger.info("All scheduler states loaded successfully") + + for i, dataloader in enumerate(dataloaders): + sampler_name = f"{SAMPLER_NAME}.bin" if i == 0 else f"{SAMPLER_NAME}_{i}.bin" + input_sampler_file = input_dir.joinpath(sampler_name) + # Only load if we have our custom sampler + from .data_loader import IterableDatasetShard, SeedableRandomSampler + + if isinstance(dataloader.dataset, IterableDatasetShard): + sampler = dataloader.get_sampler() + if isinstance(sampler, SeedableRandomSampler): + sampler = dataloader.set_sampler(torch.load(input_sampler_file)) + if getattr(dataloader, "use_stateful_dataloader", False): + dataloader_state_dict_name = "dl_state_dict.bin" if i == 0 else f"dl_state_dict_{i}.bin" + input_dataloader_state_dict_file = input_dir.joinpath(dataloader_state_dict_name) + if input_dataloader_state_dict_file.exists(): + state_dict = torch.load(input_dataloader_state_dict_file) + dataloader.load_state_dict(state_dict) + logger.info("All dataloader sampler states loaded successfully") + + # GradScaler state + if scaler is not None: + input_scaler_file = input_dir.joinpath(SCALER_NAME) + scaler.load_state_dict(torch.load(input_scaler_file)) + logger.info("GradScaler state loaded successfully") + + # Random states + try: + states = torch.load(input_dir.joinpath(f"{RNG_STATE_NAME}_{process_index}.pkl")) + if "step" in states: + override_attributes["step"] = states["step"] + random.setstate(states["random_state"]) + np.random.set_state(states["numpy_random_seed"]) + torch.set_rng_state(states["torch_manual_seed"]) + if is_xpu_available(): + torch.xpu.set_rng_state_all(states["torch_xpu_manual_seed"]) + if is_mlu_available(): + torch.mlu.set_rng_state_all(states["torch_mlu_manual_seed"]) + else: + torch.cuda.set_rng_state_all(states["torch_cuda_manual_seed"]) + if is_torch_xla_available(): + xm.set_rng_state(states["xm_seed"]) + logger.info("All random states loaded successfully") + except Exception: + logger.info("Could not load random states") + + return override_attributes + + +def save_custom_state(obj, path, index: int = 0, save_on_each_node: bool = False): + """ + Saves the state of `obj` to `{path}/custom_checkpoint_{index}.pkl` + """ + # Should this be the right way to get a qual_name type value from `obj`? + save_location = Path(path) / f"custom_checkpoint_{index}.pkl" + logger.info(f"Saving the state of {get_pretty_name(obj)} to {save_location}") + save(obj.state_dict(), save_location, save_on_each_node=save_on_each_node) + + +def load_custom_state(obj, path, index: int = 0): + """ + Loads the state of `obj` at `{path}/custom_checkpoint_{index}.pkl` + """ + load_location = f"{path}/custom_checkpoint_{index}.pkl" + logger.info(f"Loading the state of {get_pretty_name(obj)} from {load_location}") + obj.load_state_dict(torch.load(load_location, map_location="cpu")) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/__init__.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/accelerate_cli.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/accelerate_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..d9790e5805c225f78c073595f7f38e9f22cc9dbf --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/accelerate_cli.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# 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. + +from accelerate.commands.config import get_config_parser +from accelerate.commands.env import env_command_parser +from accelerate.commands.estimate import estimate_command_parser +from accelerate.commands.launch import launch_command_parser +from accelerate.commands.merge import merge_command_parser +from accelerate.commands.test import test_command_parser +from accelerate.commands.tpu import tpu_command_parser +from accelerate.commands.utils import CustomArgumentParser + + +def main(): + parser = CustomArgumentParser("Accelerate CLI tool", usage="accelerate []", allow_abbrev=False) + subparsers = parser.add_subparsers(help="accelerate command helpers") + + # Register commands + get_config_parser(subparsers=subparsers) + estimate_command_parser(subparsers=subparsers) + env_command_parser(subparsers=subparsers) + launch_command_parser(subparsers=subparsers) + merge_command_parser(subparsers=subparsers) + tpu_command_parser(subparsers=subparsers) + test_command_parser(subparsers=subparsers) + + # Let's go + args = parser.parse_args() + + if not hasattr(args, "func"): + parser.print_help() + exit(1) + + # Run + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/__init__.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..649a15888cccd070b3d4ca9a600457c6ad59d4d3 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/__init__.py @@ -0,0 +1,52 @@ +#!/usr/bin/env python + +# 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. + +import argparse + +from .config import config_command_parser +from .config_args import default_config_file, load_config_from_file # noqa: F401 +from .default import default_command_parser +from .update import update_command_parser + + +def get_config_parser(subparsers=None): + parent_parser = argparse.ArgumentParser(add_help=False, allow_abbrev=False) + # The main config parser + config_parser = config_command_parser(subparsers) + # The subparser to add commands to + subcommands = config_parser.add_subparsers(title="subcommands", dest="subcommand") + + # Then add other parsers with the parent parser + default_command_parser(subcommands, parents=[parent_parser]) + update_command_parser(subcommands, parents=[parent_parser]) + + return config_parser + + +def main(): + config_parser = get_config_parser() + args = config_parser.parse_args() + + if not hasattr(args, "func"): + config_parser.print_help() + exit(1) + + # Run + args.func(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/cluster.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/cluster.py new file mode 100644 index 0000000000000000000000000000000000000000..0862b9c9b09a0be7b393e0d79035cd0ee70a0867 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/cluster.py @@ -0,0 +1,828 @@ +#!/usr/bin/env python + +# 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. + +import os + +from ...utils import ( + ComputeEnvironment, + DistributedType, + is_deepspeed_available, + is_fp8_available, + is_mlu_available, + is_mps_available, + is_msamp_available, + is_musa_available, + is_npu_available, + is_transformer_engine_available, + is_transformers_available, + is_xpu_available, +) +from ...utils.constants import ( + DEEPSPEED_MULTINODE_LAUNCHERS, + FSDP_AUTO_WRAP_POLICY, + FSDP_BACKWARD_PREFETCH, + FSDP_SHARDING_STRATEGY, + FSDP_STATE_DICT_TYPE, + TORCH_DYNAMO_MODES, +) +from .config_args import ClusterConfig +from .config_utils import ( + DYNAMO_BACKENDS, + _ask_field, + _ask_options, + _convert_distributed_mode, + _convert_dynamo_backend, + _convert_fp8_backend, + _convert_mixed_precision, + _convert_yes_no_to_bool, +) + + +def get_cluster_input(): + distributed_type = _ask_options( + "Which type of machine are you using?", + [ + "No distributed training", + "multi-CPU", + "multi-XPU", + "multi-GPU", + "multi-NPU", + "multi-MLU", + "multi-MUSA", + "TPU", + ], + _convert_distributed_mode, + ) + + machine_rank = 0 + num_machines = 1 + num_processes = 1 + gpu_ids = None + main_process_ip = None + main_process_port = None + rdzv_backend = "static" + same_network = True + debug = False + + if distributed_type in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_CPU, + ]: + num_machines = _ask_field( + "How many different machines will you use (use more than 1 for multi-node training)? [1]: ", + int, + default=1, + ) + if num_machines > 1: + machine_rank = _ask_options( + "What is the rank of this machine?", + list(range(num_machines)), + int, + ) + main_process_ip = _ask_field( + "What is the IP address of the machine that will host the main process? ", + ) + main_process_port = _ask_field( + "What is the port you will use to communicate with the main process? ", + int, + ) + same_network = _ask_field( + "Are all the machines on the same local network? Answer `no` if nodes are on the cloud and/or on different network hosts [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + if not same_network: + rdzv_backend = _ask_field( + "What rendezvous backend will you use? ('static', 'c10d', ...): ", default="static" + ) + debug = _ask_field( + "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + if distributed_type == DistributedType.NO: + use_cpu = _ask_field( + "Do you want to run your training on CPU only (even if a GPU / Apple Silicon / Ascend NPU device is available)? [yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + elif distributed_type == DistributedType.MULTI_CPU: + use_cpu = True + else: + use_cpu = False + + ipex_config = {} + mpirun_config = {} + if use_cpu: + ipex_config["ipex"] = _ask_field( + "Do you want to use Intel PyTorch Extension (IPEX) to speed up training on CPU? [yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if distributed_type == DistributedType.MULTI_CPU: + use_mpirun = _ask_field( + "Do you want accelerate to launch mpirun? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_mpirun: + mpirun_hostfile = _ask_field( + "Please enter the path to the hostfile to use with mpirun [~/hostfile]: ", + str, + default="~/hostfile", + ) + mpirun_config["mpirun_hostfile"] = os.path.expanduser(mpirun_hostfile.strip()) + mpirun_config["mpirun_ccl"] = _ask_field("Enter the number of oneCCL worker threads [1]: ", default=1) + if ( + not use_cpu + and is_xpu_available() + and distributed_type + not in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.XLA, + DistributedType.MULTI_MUSA, + ] + ): + ipex_config["use_xpu"] = _ask_field( + "Do you want to use XPU plugin to speed up training on XPU? [yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + dynamo_config = {} + use_dynamo = _ask_field( + "Do you wish to optimize your script with torch dynamo?[yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_dynamo: + prefix = "dynamo_" + dynamo_config[prefix + "backend"] = _ask_options( + "Which dynamo backend would you like to use?", + [x.lower() for x in DYNAMO_BACKENDS], + _convert_dynamo_backend, + default=2, + ) + use_custom_options = _ask_field( + "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + if use_custom_options: + dynamo_config[prefix + "mode"] = _ask_options( + "Which mode do you want to use?", + TORCH_DYNAMO_MODES, + lambda x: TORCH_DYNAMO_MODES[int(x)], + default=0, + ) + dynamo_config[prefix + "use_fullgraph"] = _ask_field( + "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + dynamo_config[prefix + "use_dynamic"] = _ask_field( + "Do you want to enable dynamic shape tracing? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + use_mps = not use_cpu and is_mps_available() + deepspeed_config = {} + if ( + distributed_type + in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.NO, + ] + and not use_mps + ): + use_deepspeed = _ask_field( + "Do you want to use DeepSpeed? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_deepspeed: + distributed_type = DistributedType.DEEPSPEED + assert ( + is_deepspeed_available() + ), "DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source" + + if distributed_type == DistributedType.DEEPSPEED: + use_deepspeed_config = _ask_field( + "Do you want to specify a json file to a DeepSpeed config? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_deepspeed_config: + deepspeed_config["deepspeed_config_file"] = _ask_field( + "Please enter the path to the json DeepSpeed config file: ", + str, + default="none", + ) + else: + deepspeed_config["zero_stage"] = _ask_options( + "What should be your DeepSpeed's ZeRO optimization stage?", + [0, 1, 2, 3], + int, + default=2, + ) + + deepspeed_devices = ["none", "cpu", "nvme"] + if deepspeed_config["zero_stage"] >= 2: + deepspeed_config["offload_optimizer_device"] = _ask_options( + "Where to offload optimizer states?", deepspeed_devices, lambda x: deepspeed_devices[int(x)] + ) + deepspeed_config["offload_param_device"] = _ask_options( + "Where to offload parameters?", deepspeed_devices, lambda x: deepspeed_devices[int(x)] + ) + if deepspeed_config["offload_param_device"] == "nvme": + deepspeed_config["offload_param_nvme_path"] = _ask_field( + "Nvme Path to offload parameters?", + str, + default="/nvme", + ) + if deepspeed_config["offload_optimizer_device"] == "nvme": + deepspeed_config["offload_optimizer_nvme_path"] = _ask_field( + "Nvme Path to offload optimizer states?", + str, + default="/nvme", + ) + deepspeed_config["gradient_accumulation_steps"] = _ask_field( + "How many gradient accumulation steps you're passing in your script? [1]: ", + int, + default=1, + ) + use_gradient_clipping = _ask_field( + "Do you want to use gradient clipping? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_gradient_clipping: + deepspeed_config["gradient_clipping"] = _ask_field( + "What is the gradient clipping value? [1.0]: ", + float, + default=1.0, + ) + if deepspeed_config["zero_stage"] == 3: + deepspeed_config["zero3_save_16bit_model"] = _ask_field( + "Do you want to save 16-bit model weights when using ZeRO Stage-3? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + deepspeed_config["zero3_init_flag"] = _ask_field( + "Do you want to enable `deepspeed.zero.Init` when using ZeRO Stage-3 for constructing massive models? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if deepspeed_config["zero3_init_flag"]: + if not is_transformers_available(): + raise Exception( + "When `zero3_init_flag` is set, it requires Transformers to be installed. " + "Please run `pip3 install transformers`." + ) + use_moe = _ask_field( + "Do you want to enable Mixture-of-Experts training (MoE)? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_moe: + deepspeed_config["deepspeed_moe_layer_cls_names"] = _ask_field( + "Specify the comma-separated list of transformers MoE layer class names (case-sensitive), e.g : " + " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ... : ", + str, + ) + + if num_machines > 1: + launcher_query = "Which Type of launcher do you want to use?" + deepspeed_config["deepspeed_multinode_launcher"] = _ask_options( + launcher_query, + DEEPSPEED_MULTINODE_LAUNCHERS, + lambda x: DEEPSPEED_MULTINODE_LAUNCHERS[int(x)], + ) + + if deepspeed_config["deepspeed_multinode_launcher"] != DEEPSPEED_MULTINODE_LAUNCHERS[1]: + deepspeed_config["deepspeed_hostfile"] = _ask_field( + "DeepSpeed configures multi-node compute resources with hostfile. " + "Each row is of the format `hostname slots=[num_gpus]`, e.g., `localhost slots=2`; " + "for more information please refer official [documentation]" + "(https://www.deepspeed.ai/getting-started/#resource-configuration-multi-node). " + "Please specify the location of hostfile: ", + str, + ) + + is_exclusion_filter = _ask_field( + "Do you want to specify exclusion filter string? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if is_exclusion_filter: + deepspeed_config["deepspeed_exclusion_filter"] = _ask_field( + "DeepSpeed exclusion filter string: ", + str, + ) + + is_inclusion_filter = _ask_field( + "Do you want to specify inclusion filter string? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if is_inclusion_filter: + deepspeed_config["deepspeed_inclusion_filter"] = _ask_field( + "DeepSpeed inclusion filter string: ", + str, + ) + + fsdp_config = {} + if distributed_type in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_XPU, + ]: + use_fsdp = _ask_field( + "Do you want to use FullyShardedDataParallel? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_fsdp: + distributed_type = DistributedType.FSDP + if distributed_type == DistributedType.FSDP: + sharding_strategy_query = "What should be your sharding strategy?" + fsdp_config["fsdp_sharding_strategy"] = _ask_options( + sharding_strategy_query, + FSDP_SHARDING_STRATEGY, + lambda x: FSDP_SHARDING_STRATEGY[int(x)], + ) + fsdp_config["fsdp_offload_params"] = _ask_field( + "Do you want to offload parameters and gradients to CPU? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + fsdp_wrap_query = "What should be your auto wrap policy?" + fsdp_config["fsdp_auto_wrap_policy"] = _ask_options( + fsdp_wrap_query, + FSDP_AUTO_WRAP_POLICY, + lambda x: FSDP_AUTO_WRAP_POLICY[int(x)], + ) + if fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[0]: + use_no_split_modules = _ask_field( + "Do you want to use the model's `_no_split_modules` to wrap. Only applicable for 🤗 Transformers [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if not use_no_split_modules: + fsdp_config["fsdp_transformer_layer_cls_to_wrap"] = _ask_field( + "Specify the comma-separated list of transformer layer class names (case-sensitive) to wrap ,e.g, :" + "`BertLayer`, `GPTJBlock`, `T5Block`, `BertLayer,BertEmbeddings,BertSelfOutput` ...? : ", + str, + ) + elif fsdp_config["fsdp_auto_wrap_policy"] == FSDP_AUTO_WRAP_POLICY[1]: + fsdp_config["fsdp_min_num_params"] = _ask_field( + "What should be your FSDP's minimum number of parameters for Default Auto Wrapping Policy? [1e8]: ", + int, + default=100000000, + ) + fsdp_backward_prefetch_query = "What should be your FSDP's backward prefetch policy?" + fsdp_config["fsdp_backward_prefetch"] = _ask_options( + fsdp_backward_prefetch_query, + FSDP_BACKWARD_PREFETCH, + lambda x: FSDP_BACKWARD_PREFETCH[int(x)], + ) + fsdp_state_dict_type_query = "What should be your FSDP's state dict type?" + fsdp_config["fsdp_state_dict_type"] = _ask_options( + fsdp_state_dict_type_query, + FSDP_STATE_DICT_TYPE, + lambda x: FSDP_STATE_DICT_TYPE[int(x)], + default=2, + ) + fsdp_config["fsdp_forward_prefetch"] = _ask_field( + "Do you want to enable FSDP's forward prefetch policy? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + fsdp_config["fsdp_use_orig_params"] = _ask_field( + "Do you want to enable FSDP's `use_orig_params` feature? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + fsdp_config["fsdp_cpu_ram_efficient_loading"] = _ask_field( + "Do you want to enable CPU RAM efficient model loading? Only applicable for 🤗 Transformers models. [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + if fsdp_config["fsdp_cpu_ram_efficient_loading"]: + fsdp_config["fsdp_sync_module_states"] = True + else: + fsdp_config["fsdp_sync_module_states"] = _ask_field( + "Do you want each individually wrapped FSDP unit to broadcast module parameters from rank 0 at the start? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + fsdp_config["fsdp_activation_checkpointing"] = _ask_field( + "Do you want to enable FSDP activation checkpointing? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + megatron_lm_config = {} + if distributed_type in [DistributedType.MULTI_GPU]: + use_megatron_lm = _ask_field( + "Do you want to use Megatron-LM ? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_megatron_lm: + distributed_type = DistributedType.MEGATRON_LM + if distributed_type == DistributedType.MEGATRON_LM: + prefix = "megatron_lm_" + megatron_lm_config[prefix + "tp_degree"] = _ask_field( + "What is the Tensor Parallelism degree/size? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + if megatron_lm_config[prefix + "tp_degree"] > 1: + megatron_lm_config[prefix + "sequence_parallelism"] = _ask_field( + "Do you want to enable Sequence Parallelism? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + + megatron_lm_config[prefix + "pp_degree"] = _ask_field( + "What is the Pipeline Parallelism degree/size? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + if megatron_lm_config[prefix + "pp_degree"] > 1: + megatron_lm_config[prefix + "num_micro_batches"] = _ask_field( + "What is the number of micro-batches? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + + megatron_lm_config[prefix + "recompute_activations"] = _ask_field( + "Do you want to enable selective activation recomputation? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + + megatron_lm_config[prefix + "use_distributed_optimizer"] = _ask_field( + "Do you want to use distributed optimizer " + "which shards optimizer state and gradients across data parallel ranks? [YES/no]: ", + _convert_yes_no_to_bool, + default=True, + error_message="Please enter yes or no.", + ) + + megatron_lm_config[prefix + "gradient_clipping"] = _ask_field( + "What is the gradient clipping value based on global L2 Norm (0 to disable)? [1.0]: ", + float, + default=1.0, + ) + # TPU specific defaults + tpu_commands = None + tpu_command_file = None + tpu_downcast_bf16 = "no" + tpu_env = [] + tpu_name = None + tpu_vm = None + tpu_zone = None + tpu_use_sudo = False + tpu_use_cluster = False + + if distributed_type in [ + DistributedType.MULTI_CPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.XLA, + ]: + machine_type = str(distributed_type).split(".")[1].replace("MULTI_", "") + if machine_type == "TPU": + machine_type += " cores" + elif machine_type == "CPU": + machine_type = "processes" + else: + machine_type += "(s)" + num_processes = _ask_field( + f"How many {machine_type} should be used for distributed training? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + elif distributed_type in [DistributedType.FSDP, DistributedType.DEEPSPEED, DistributedType.MEGATRON_LM]: + num_processes = _ask_field( + "How many GPU(s) should be used for distributed training? [1]:", + int, + default=1, + error_message="Please enter an integer.", + ) + else: + num_processes = 1 + + if (distributed_type == DistributedType.MULTI_GPU) and (num_machines == 1) and (num_processes == 1): + raise ValueError( + f"Specified distributed type {distributed_type} but only using 1 GPU on a single machine. Please select `No distributed training` for the type of machine you are using." + ) + + if ( + distributed_type + in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.NO, + ] + and not use_cpu + and not use_mps + ): + if is_npu_available(): + machine_type = "NPU(s)" + elif is_mlu_available(): + machine_type = "MLU(s)" + elif is_musa_available(): + machine_type = "MUSA(s)" + else: + machine_type = "GPU(s)" + gpu_ids = _ask_field( + f"What {machine_type} (by id) should be used for training on this machine as a comma-seperated list? [all]:", + default="all", + ) + + # CPU affinity is only supported on NVIDIA hardware for now + enable_cpu_affinity = False + if distributed_type in (DistributedType.NO, DistributedType.MULTI_GPU) and not use_cpu and not use_mps: + enable_cpu_affinity = _ask_field( + "Would you like to enable numa efficiency? (Currently only supported on NVIDIA hardware). [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + fp8_config = None + if distributed_type == DistributedType.XLA: + mixed_precision = "no" + main_training_function = _ask_field( + "What is the name of the function in your script that should be launched in all parallel scripts? [main]: ", + default="main", + ) + tpu_use_cluster = _ask_field( + "Are you using a TPU cluster? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if tpu_use_cluster: + tpu_name = _ask_field( + "What is the name of your TPU cluster? ", + default=None, + error_message="Please enter the name of your TPU cluster.", + ) + tpu_zone = _ask_field( + "What is the zone of your TPU cluster? ", + default=None, + error_message="Please enter the zone of your TPU cluster.", + ) + tpu_use_sudo = _ask_field( + "To run a python script in a TPU pod, should `sudo` be used? [yes/NO]: ", + default=False, + error_message="Please enter yes or no.", + ) + run_commands = _ask_field( + "Do you have code you wish to run on startup in each pod? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if run_commands: + use_command_file = _ask_field( + "Is this code located in a bash script? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_command_file: + tpu_command_file = _ask_field( + "What is the path to your bash script? ", + default=None, + error_message="Please enter the path to your bash script.", + ) + tpu_command_file = os.path.abspath(tpu_command_file) + else: + print("Please enter each command seperately you wish to run on startup in each pod.") + tpu_commands = [] + another_command = True + while another_command: + tpu_commands.append( + _ask_field( + "Please enter a single command to be ran ", + default=None, + error_message="Please enter the commands you wish to run on startup in each pod as a single string.", + ) + ) + another_command = _ask_field( + "Do you wish to add another command? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + tpu_vm = _ask_field( + "If not using an instance group, what are the names of the Compute VM instances to be used, seperated by a comma: ", + default="", + ).split(",") + tpu_env = _ask_field( + "What environment variables do you wish to set in each pod, seperated by a comma: ", + default="", + ).split(",") + + else: + main_training_function = "main" + if distributed_type == DistributedType.DEEPSPEED and use_deepspeed_config: + mixed_precision = None + else: + mixed_precision = _ask_options( + "Do you wish to use mixed precision?", + ["no", "fp16", "bf16", "fp8"], + _convert_mixed_precision, + ) + if mixed_precision == "fp8": + if not is_fp8_available(): + raise ValueError("FP8 (either Transformer Engine or MSAMP) is not installed on this machine.") + fp8_config = {} + fp8_config["backend"] = _ask_options( + "Which FP8 backend do you want to use?", + ["te", "msamp"], + _convert_fp8_backend, + ) + if fp8_config["backend"] == "TE": + if not is_transformer_engine_available(): + raise ValueError("TransformersEngine was selected, but it is not installed on this machine.") + fp8_config["use_autocast_during_eval"] = _ask_field( + "Do you want to use FP8 autocast during eval mode? Generally better metrics are found when this is disabled [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + fp8_config["margin"] = _ask_field( + "What margin should be used for gradient scaling? [0]: ", + int, + default=0, + ) + fp8_config["interval"] = _ask_field( + "What interval should be used for for how often the scaling factor is recomputed? [1]: ", + int, + default=1, + ) + fp8_config["fp8_format"] = _ask_options( + "Which weight format should be used?", + ["HYBRID", "E4M3"], + lambda x: "HYBRID" if x == 0 else "E4M3", + default=0, + ) + fp8_config["amax_history_length"] = _ask_field( + "What length of history should be used for the amax scaling factor computation? [1024]: ", + int, + default=1024, + ) + fp8_config["amax_compute_algorithm"] = _ask_options( + "Which algorithm should be used for the amax scaling factor computation?", + ["max", "most_recent"], + lambda x: "max" if x == 0 else "most_recent", + default=0, + ) + fp8_config["override_linear_precision"] = _ask_field( + "Do you want to to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + if fp8_config["override_linear_precision"]: + fprop = _ask_field( + "Should `fprop` be executed in higher precision? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + dgrad = _ask_field( + "Should `dgrad` be executed in higher precision? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + wgrad = _ask_field( + "Should `wgrad` be executed in higher precision? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + ) + fp8_config["override_linear_precision"] = (fprop, dgrad, wgrad) + + elif fp8_config["backend"] == "MSAMP": + if not is_msamp_available(): + raise ValueError("MSAMP was selected, but it is not installed on this machine.") + fp8_config["optimization_level"] = _ask_options( + "Which optimization level should be used?", + ["O1", "O2"], + lambda x: "O1" if x == 0 else "O2", + default=1, + ) + + if use_dynamo and mixed_precision == "no" and not use_cpu: + print( + "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." + ) + + if distributed_type == DistributedType.XLA and mixed_precision == "bf16": + tpu_downcast_bf16 = _ask_field( + "Should `torch.float` be cast as `bfloat16` and `torch.double` remain `float32` on TPUs?", default="no" + ) + + return ClusterConfig( + compute_environment=ComputeEnvironment.LOCAL_MACHINE, + distributed_type=distributed_type, + num_processes=num_processes, + gpu_ids=gpu_ids, + mixed_precision=mixed_precision, + downcast_bf16=tpu_downcast_bf16, + machine_rank=machine_rank, + num_machines=num_machines, + main_process_ip=main_process_ip, + main_process_port=main_process_port, + main_training_function=main_training_function, + fp8_config=fp8_config, + deepspeed_config=deepspeed_config, + fsdp_config=fsdp_config, + megatron_lm_config=megatron_lm_config, + ipex_config=ipex_config, + mpirun_config=mpirun_config, + use_cpu=use_cpu, + rdzv_backend=rdzv_backend, + same_network=same_network, + commands=tpu_commands, + command_file=tpu_command_file, + tpu_env=tpu_env, + tpu_name=tpu_name, + tpu_vm=tpu_vm, + tpu_zone=tpu_zone, + tpu_use_sudo=tpu_use_sudo, + tpu_use_cluster=tpu_use_cluster, + dynamo_config=dynamo_config, + debug=debug, + enable_cpu_affinity=enable_cpu_affinity, + ) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config.py new file mode 100644 index 0000000000000000000000000000000000000000..72414f2abe62d76bd5133f4b0ed99bf34133f6f6 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config.py @@ -0,0 +1,89 @@ +#!/usr/bin/env python + +# 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. + +import argparse +import os + +from accelerate.utils import ComputeEnvironment + +from .cluster import get_cluster_input +from .config_args import cache_dir, default_config_file, default_yaml_config_file, load_config_from_file # noqa: F401 +from .config_utils import _ask_field, _ask_options, _convert_compute_environment # noqa: F401 +from .sagemaker import get_sagemaker_input + + +description = "Launches a series of prompts to create and save a `default_config.yaml` configuration file for your training system. Should always be ran first on your machine" + + +def get_user_input(): + compute_environment = _ask_options( + "In which compute environment are you running?", + ["This machine", "AWS (Amazon SageMaker)"], + _convert_compute_environment, + ) + if compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: + config = get_sagemaker_input() + else: + config = get_cluster_input() + return config + + +def config_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("config", description=description) + else: + parser = argparse.ArgumentParser("Accelerate config command", description=description) + + parser.add_argument( + "--config_file", + default=None, + help=( + "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " + "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " + "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " + "with 'huggingface'." + ), + ) + + if subparsers is not None: + parser.set_defaults(func=config_command) + return parser + + +def config_command(args): + config = get_user_input() + if args.config_file is not None: + config_file = args.config_file + else: + if not os.path.isdir(cache_dir): + os.makedirs(cache_dir) + config_file = default_yaml_config_file + + if config_file.endswith(".json"): + config.to_json_file(config_file) + else: + config.to_yaml_file(config_file) + print(f"accelerate configuration saved at {config_file}") + + +def main(): + parser = config_command_parser() + args = parser.parse_args() + config_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config_args.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config_args.py new file mode 100644 index 0000000000000000000000000000000000000000..a3991b2808dc715676e147f8b7d6d1440d9fb6e1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config_args.py @@ -0,0 +1,252 @@ +#!/usr/bin/env python + +# 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. + +import json +import os +from dataclasses import dataclass +from enum import Enum +from typing import List, Optional, Union + +import yaml + +from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType +from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION + + +hf_cache_home = os.path.expanduser( + os.environ.get("HF_HOME", os.path.join(os.environ.get("XDG_CACHE_HOME", "~/.cache"), "huggingface")) +) +cache_dir = os.path.join(hf_cache_home, "accelerate") +default_json_config_file = os.path.join(cache_dir, "default_config.yaml") +default_yaml_config_file = os.path.join(cache_dir, "default_config.yaml") + +# For backward compatibility: the default config is the json one if it's the only existing file. +if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file): + default_config_file = default_yaml_config_file +else: + default_config_file = default_json_config_file + + +def load_config_from_file(config_file): + if config_file is not None: + if not os.path.isfile(config_file): + raise FileNotFoundError( + f"The passed configuration file `{config_file}` does not exist. " + "Please pass an existing file to `accelerate launch`, or use the default one " + "created through `accelerate config` and run `accelerate launch` " + "without the `--config_file` argument." + ) + else: + config_file = default_config_file + with open(config_file, encoding="utf-8") as f: + if config_file.endswith(".json"): + if ( + json.load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE) + == ComputeEnvironment.LOCAL_MACHINE + ): + config_class = ClusterConfig + else: + config_class = SageMakerConfig + return config_class.from_json_file(json_file=config_file) + else: + if ( + yaml.safe_load(f).get("compute_environment", ComputeEnvironment.LOCAL_MACHINE) + == ComputeEnvironment.LOCAL_MACHINE + ): + config_class = ClusterConfig + else: + config_class = SageMakerConfig + return config_class.from_yaml_file(yaml_file=config_file) + + +@dataclass +class BaseConfig: + compute_environment: ComputeEnvironment + distributed_type: Union[DistributedType, SageMakerDistributedType] + mixed_precision: str + use_cpu: bool + debug: bool + + def to_dict(self): + result = self.__dict__ + # For serialization, it's best to convert Enums to strings (or their underlying value type). + + def _convert_enums(value): + if isinstance(value, Enum): + return value.value + if isinstance(value, dict): + if not bool(value): + return None + for key1, value1 in value.items(): + value[key1] = _convert_enums(value1) + return value + + for key, value in result.items(): + result[key] = _convert_enums(value) + result = {k: v for k, v in result.items() if v is not None} + return result + + @staticmethod + def process_config(config_dict): + """ + Processes `config_dict` and sets default values for any missing keys + """ + if "compute_environment" not in config_dict: + config_dict["compute_environment"] = ComputeEnvironment.LOCAL_MACHINE + if "distributed_type" not in config_dict: + raise ValueError("A `distributed_type` must be specified in the config file.") + if "num_processes" not in config_dict and config_dict["distributed_type"] == DistributedType.NO: + config_dict["num_processes"] = 1 + if "mixed_precision" not in config_dict: + config_dict["mixed_precision"] = "fp16" if ("fp16" in config_dict and config_dict["fp16"]) else None + if "fp16" in config_dict: # Convert the config to the new format. + del config_dict["fp16"] + if "dynamo_backend" in config_dict: # Convert the config to the new format. + dynamo_backend = config_dict.pop("dynamo_backend") + config_dict["dynamo_config"] = {} if dynamo_backend == "NO" else {"dynamo_backend": dynamo_backend} + if "use_cpu" not in config_dict: + config_dict["use_cpu"] = False + if "debug" not in config_dict: + config_dict["debug"] = False + if "enable_cpu_affinity" not in config_dict: + config_dict["enable_cpu_affinity"] = False + return config_dict + + @classmethod + def from_json_file(cls, json_file=None): + json_file = default_json_config_file if json_file is None else json_file + with open(json_file, encoding="utf-8") as f: + config_dict = json.load(f) + config_dict = cls.process_config(config_dict) + extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys())) + if len(extra_keys) > 0: + raise ValueError( + f"The config file at {json_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`" + " version or fix (and potentially remove) these keys from your config file." + ) + + return cls(**config_dict) + + def to_json_file(self, json_file): + with open(json_file, "w", encoding="utf-8") as f: + content = json.dumps(self.to_dict(), indent=2, sort_keys=True) + "\n" + f.write(content) + + @classmethod + def from_yaml_file(cls, yaml_file=None): + yaml_file = default_yaml_config_file if yaml_file is None else yaml_file + with open(yaml_file, encoding="utf-8") as f: + config_dict = yaml.safe_load(f) + config_dict = cls.process_config(config_dict) + extra_keys = sorted(set(config_dict.keys()) - set(cls.__dataclass_fields__.keys())) + if len(extra_keys) > 0: + raise ValueError( + f"The config file at {yaml_file} had unknown keys ({extra_keys}), please try upgrading your `accelerate`" + " version or fix (and potentially remove) these keys from your config file." + ) + return cls(**config_dict) + + def to_yaml_file(self, yaml_file): + with open(yaml_file, "w", encoding="utf-8") as f: + yaml.safe_dump(self.to_dict(), f) + + def __post_init__(self): + if isinstance(self.compute_environment, str): + self.compute_environment = ComputeEnvironment(self.compute_environment) + if isinstance(self.distributed_type, str): + if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: + self.distributed_type = SageMakerDistributedType(self.distributed_type) + else: + self.distributed_type = DistributedType(self.distributed_type) + if getattr(self, "dynamo_config", None) is None: + self.dynamo_config = {} + + +@dataclass +class ClusterConfig(BaseConfig): + num_processes: int = -1 # For instance if we use SLURM and the user manually passes it in + machine_rank: int = 0 + num_machines: int = 1 + gpu_ids: Optional[str] = None + main_process_ip: Optional[str] = None + main_process_port: Optional[int] = None + rdzv_backend: Optional[str] = "static" + same_network: Optional[bool] = False + main_training_function: str = "main" + enable_cpu_affinity: bool = False + + # args for FP8 training + fp8_config: dict = None + # args for deepspeed_plugin + deepspeed_config: dict = None + # args for fsdp + fsdp_config: dict = None + # args for megatron_lm + megatron_lm_config: dict = None + # args for ipex + ipex_config: dict = None + # args for mpirun + mpirun_config: dict = None + # args for TPU + downcast_bf16: bool = False + + # args for TPU pods + tpu_name: str = None + tpu_zone: str = None + tpu_use_cluster: bool = False + tpu_use_sudo: bool = False + command_file: str = None + commands: List[str] = None + tpu_vm: List[str] = None + tpu_env: List[str] = None + + # args for dynamo + dynamo_config: dict = None + + def __post_init__(self): + if self.deepspeed_config is None: + self.deepspeed_config = {} + if self.fsdp_config is None: + self.fsdp_config = {} + if self.megatron_lm_config is None: + self.megatron_lm_config = {} + if self.ipex_config is None: + self.ipex_config = {} + if self.mpirun_config is None: + self.mpirun_config = {} + if self.fp8_config is None: + self.fp8_config = {} + return super().__post_init__() + + +@dataclass +class SageMakerConfig(BaseConfig): + ec2_instance_type: str + iam_role_name: str + image_uri: Optional[str] = None + profile: Optional[str] = None + region: str = "us-east-1" + num_machines: int = 1 + gpu_ids: str = "all" + base_job_name: str = f"accelerate-sagemaker-{num_machines}" + pytorch_version: str = SAGEMAKER_PYTORCH_VERSION + transformers_version: str = SAGEMAKER_TRANSFORMERS_VERSION + py_version: str = SAGEMAKER_PYTHON_VERSION + sagemaker_inputs_file: str = None + sagemaker_metrics_file: str = None + additional_args: dict = None + dynamo_config: dict = None + enable_cpu_affinity: bool = False diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config_utils.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..f62570813a479bf8f695d11a7daa15e54a2e0b70 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/config_utils.py @@ -0,0 +1,111 @@ +#!/usr/bin/env python + +# 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. + +import argparse + +from ...utils.dataclasses import ( + ComputeEnvironment, + DistributedType, + DynamoBackend, + FP8BackendType, + PrecisionType, + SageMakerDistributedType, +) +from ..menu import BulletMenu + + +DYNAMO_BACKENDS = [ + "EAGER", + "AOT_EAGER", + "INDUCTOR", + "AOT_TS_NVFUSER", + "NVPRIMS_NVFUSER", + "CUDAGRAPHS", + "OFI", + "FX2TRT", + "ONNXRT", + "TENSORRT", + "AOT_TORCHXLA_TRACE_ONCE", + "TORHCHXLA_TRACE_ONCE", + "IPEX", + "TVM", +] + + +def _ask_field(input_text, convert_value=None, default=None, error_message=None): + ask_again = True + while ask_again: + result = input(input_text) + try: + if default is not None and len(result) == 0: + return default + return convert_value(result) if convert_value is not None else result + except Exception: + if error_message is not None: + print(error_message) + + +def _ask_options(input_text, options=[], convert_value=None, default=0): + menu = BulletMenu(input_text, options) + result = menu.run(default_choice=default) + return convert_value(result) if convert_value is not None else result + + +def _convert_compute_environment(value): + value = int(value) + return ComputeEnvironment(["LOCAL_MACHINE", "AMAZON_SAGEMAKER"][value]) + + +def _convert_distributed_mode(value): + value = int(value) + return DistributedType( + ["NO", "MULTI_CPU", "MULTI_XPU", "MULTI_GPU", "MULTI_NPU", "MULTI_MLU", "MULTI_MUSA", "XLA"][value] + ) + + +def _convert_dynamo_backend(value): + value = int(value) + return DynamoBackend(DYNAMO_BACKENDS[value]).value + + +def _convert_mixed_precision(value): + value = int(value) + return PrecisionType(["no", "fp16", "bf16", "fp8"][value]) + + +def _convert_sagemaker_distributed_mode(value): + value = int(value) + return SageMakerDistributedType(["NO", "DATA_PARALLEL", "MODEL_PARALLEL"][value]) + + +def _convert_fp8_backend(value): + value = int(value) + return FP8BackendType(["TE", "MSAMP"][value]) + + +def _convert_yes_no_to_bool(value): + return {"yes": True, "no": False}[value.lower()] + + +class SubcommandHelpFormatter(argparse.RawDescriptionHelpFormatter): + """ + A custom formatter that will remove the usage line from the help message for subcommands. + """ + + def _format_usage(self, usage, actions, groups, prefix): + usage = super()._format_usage(usage, actions, groups, prefix) + usage = usage.replace(" [] ", "") + return usage diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/default.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/default.py new file mode 100644 index 0000000000000000000000000000000000000000..dcaa4902e56ab6ca2e698d65d96bc93d6ed761e1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/default.py @@ -0,0 +1,142 @@ +#!/usr/bin/env python + +# 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. + +from pathlib import Path + +import torch + +from ...utils import is_mlu_available, is_musa_available, is_npu_available, is_xpu_available +from .config_args import ClusterConfig, default_json_config_file +from .config_utils import SubcommandHelpFormatter + + +description = "Create a default config file for Accelerate with only a few flags set." + + +def write_basic_config(mixed_precision="no", save_location: str = default_json_config_file, use_xpu: bool = False): + """ + Creates and saves a basic cluster config to be used on a local machine with potentially multiple GPUs. Will also + set CPU if it is a CPU-only machine. + + Args: + mixed_precision (`str`, *optional*, defaults to "no"): + Mixed Precision to use. Should be one of "no", "fp16", or "bf16" + save_location (`str`, *optional*, defaults to `default_json_config_file`): + Optional custom save location. Should be passed to `--config_file` when using `accelerate launch`. Default + location is inside the huggingface cache folder (`~/.cache/huggingface`) but can be overriden by setting + the `HF_HOME` environmental variable, followed by `accelerate/default_config.yaml`. + use_xpu (`bool`, *optional*, defaults to `False`): + Whether to use XPU if available. + """ + path = Path(save_location) + path.parent.mkdir(parents=True, exist_ok=True) + if path.exists(): + print( + f"Configuration already exists at {save_location}, will not override. Run `accelerate config` manually or pass a different `save_location`." + ) + return False + mixed_precision = mixed_precision.lower() + if mixed_precision not in ["no", "fp16", "bf16", "fp8"]: + raise ValueError( + f"`mixed_precision` should be one of 'no', 'fp16', 'bf16', or 'fp8'. Received {mixed_precision}" + ) + config = { + "compute_environment": "LOCAL_MACHINE", + "mixed_precision": mixed_precision, + } + if is_mlu_available(): + num_mlus = torch.mlu.device_count() + config["num_processes"] = num_mlus + config["use_cpu"] = False + if num_mlus > 1: + config["distributed_type"] = "MULTI_MLU" + else: + config["distributed_type"] = "NO" + elif is_musa_available(): + num_musas = torch.musa.device_count() + config["num_processes"] = num_musas + config["use_cpu"] = False + if num_musas > 1: + config["distributed_type"] = "MULTI_MUSA" + else: + config["distributed_type"] = "NO" + elif torch.cuda.is_available(): + num_gpus = torch.cuda.device_count() + config["num_processes"] = num_gpus + config["use_cpu"] = False + if num_gpus > 1: + config["distributed_type"] = "MULTI_GPU" + else: + config["distributed_type"] = "NO" + elif is_xpu_available() and use_xpu: + num_xpus = torch.xpu.device_count() + config["num_processes"] = num_xpus + config["use_cpu"] = False + if num_xpus > 1: + config["distributed_type"] = "MULTI_XPU" + else: + config["distributed_type"] = "NO" + elif is_npu_available(): + num_npus = torch.npu.device_count() + config["num_processes"] = num_npus + config["use_cpu"] = False + if num_npus > 1: + config["distributed_type"] = "MULTI_NPU" + else: + config["distributed_type"] = "NO" + else: + num_xpus = 0 + config["use_cpu"] = True + config["num_processes"] = 1 + config["distributed_type"] = "NO" + config["debug"] = False + config["enable_cpu_affinity"] = False + config = ClusterConfig(**config) + config.to_json_file(path) + return path + + +def default_command_parser(parser, parents): + parser = parser.add_parser("default", parents=parents, help=description, formatter_class=SubcommandHelpFormatter) + parser.add_argument( + "--config_file", + default=default_json_config_file, + help=( + "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " + "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " + "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " + "with 'huggingface'." + ), + dest="save_location", + ) + + parser.add_argument( + "--mixed_precision", + choices=["no", "fp16", "bf16"], + type=str, + help="Whether or not to use mixed precision training. " + "Choose between FP16 and BF16 (bfloat16) training. " + "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.", + default="no", + ) + parser.set_defaults(func=default_config_command) + return parser + + +def default_config_command(args): + config_file = write_basic_config(args.mixed_precision, args.save_location) + if config_file: + print(f"accelerate configuration saved at {config_file}") diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/sagemaker.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/sagemaker.py new file mode 100644 index 0000000000000000000000000000000000000000..1e3491fee0ad28df82683a89d128bbc097053c2f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/sagemaker.py @@ -0,0 +1,267 @@ +#!/usr/bin/env python + +# 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. +import json +import os + +from ...utils.constants import SAGEMAKER_PARALLEL_EC2_INSTANCES, TORCH_DYNAMO_MODES +from ...utils.dataclasses import ComputeEnvironment, SageMakerDistributedType +from ...utils.imports import is_boto3_available +from .config_args import SageMakerConfig +from .config_utils import ( + DYNAMO_BACKENDS, + _ask_field, + _ask_options, + _convert_dynamo_backend, + _convert_mixed_precision, + _convert_sagemaker_distributed_mode, + _convert_yes_no_to_bool, +) + + +if is_boto3_available(): + import boto3 # noqa: F401 + + +def _create_iam_role_for_sagemaker(role_name): + iam_client = boto3.client("iam") + + sagemaker_trust_policy = { + "Version": "2012-10-17", + "Statement": [ + {"Effect": "Allow", "Principal": {"Service": "sagemaker.amazonaws.com"}, "Action": "sts:AssumeRole"} + ], + } + try: + # create the role, associated with the chosen trust policy + iam_client.create_role( + RoleName=role_name, AssumeRolePolicyDocument=json.dumps(sagemaker_trust_policy, indent=2) + ) + policy_document = { + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "sagemaker:*", + "ecr:GetDownloadUrlForLayer", + "ecr:BatchGetImage", + "ecr:BatchCheckLayerAvailability", + "ecr:GetAuthorizationToken", + "cloudwatch:PutMetricData", + "cloudwatch:GetMetricData", + "cloudwatch:GetMetricStatistics", + "cloudwatch:ListMetrics", + "logs:CreateLogGroup", + "logs:CreateLogStream", + "logs:DescribeLogStreams", + "logs:PutLogEvents", + "logs:GetLogEvents", + "s3:CreateBucket", + "s3:ListBucket", + "s3:GetBucketLocation", + "s3:GetObject", + "s3:PutObject", + ], + "Resource": "*", + } + ], + } + # attach policy to role + iam_client.put_role_policy( + RoleName=role_name, + PolicyName=f"{role_name}_policy_permission", + PolicyDocument=json.dumps(policy_document, indent=2), + ) + except iam_client.exceptions.EntityAlreadyExistsException: + print(f"role {role_name} already exists. Using existing one") + + +def _get_iam_role_arn(role_name): + iam_client = boto3.client("iam") + return iam_client.get_role(RoleName=role_name)["Role"]["Arn"] + + +def get_sagemaker_input(): + credentials_configuration = _ask_options( + "How do you want to authorize?", + ["AWS Profile", "Credentials (AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY) "], + int, + ) + aws_profile = None + if credentials_configuration == 0: + aws_profile = _ask_field("Enter your AWS Profile name: [default] ", default="default") + os.environ["AWS_PROFILE"] = aws_profile + else: + print( + "Note you will need to provide AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY when you launch you training script with," + "`accelerate launch --aws_access_key_id XXX --aws_secret_access_key YYY`" + ) + aws_access_key_id = _ask_field("AWS Access Key ID: ") + os.environ["AWS_ACCESS_KEY_ID"] = aws_access_key_id + + aws_secret_access_key = _ask_field("AWS Secret Access Key: ") + os.environ["AWS_SECRET_ACCESS_KEY"] = aws_secret_access_key + + aws_region = _ask_field("Enter your AWS Region: [us-east-1]", default="us-east-1") + os.environ["AWS_DEFAULT_REGION"] = aws_region + + role_management = _ask_options( + "Do you already have an IAM Role for executing Amazon SageMaker Training Jobs?", + ["Provide IAM Role name", "Create new IAM role using credentials"], + int, + ) + if role_management == 0: + iam_role_name = _ask_field("Enter your IAM role name: ") + else: + iam_role_name = "accelerate_sagemaker_execution_role" + print(f'Accelerate will create an iam role "{iam_role_name}" using the provided credentials') + _create_iam_role_for_sagemaker(iam_role_name) + + is_custom_docker_image = _ask_field( + "Do you want to use custom Docker image? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + docker_image = None + if is_custom_docker_image: + docker_image = _ask_field("Enter your Docker image: ", lambda x: str(x).lower()) + + is_sagemaker_inputs_enabled = _ask_field( + "Do you want to provide SageMaker input channels with data locations? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + sagemaker_inputs_file = None + if is_sagemaker_inputs_enabled: + sagemaker_inputs_file = _ask_field( + "Enter the path to the SageMaker inputs TSV file with columns (channel_name, data_location): ", + lambda x: str(x).lower(), + ) + + is_sagemaker_metrics_enabled = _ask_field( + "Do you want to enable SageMaker metrics? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + sagemaker_metrics_file = None + if is_sagemaker_metrics_enabled: + sagemaker_metrics_file = _ask_field( + "Enter the path to the SageMaker metrics TSV file with columns (metric_name, metric_regex): ", + lambda x: str(x).lower(), + ) + + distributed_type = _ask_options( + "What is the distributed mode?", + ["No distributed training", "Data parallelism"], + _convert_sagemaker_distributed_mode, + ) + dynamo_config = {} + use_dynamo = _ask_field( + "Do you wish to optimize your script with torch dynamo?[yes/NO]:", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + if use_dynamo: + prefix = "dynamo_" + dynamo_config[prefix + "backend"] = _ask_options( + "Which dynamo backend would you like to use?", + [x.lower() for x in DYNAMO_BACKENDS], + _convert_dynamo_backend, + default=2, + ) + use_custom_options = _ask_field( + "Do you want to customize the defaults sent to torch.compile? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + if use_custom_options: + dynamo_config[prefix + "mode"] = _ask_options( + "Which mode do you want to use?", + TORCH_DYNAMO_MODES, + lambda x: TORCH_DYNAMO_MODES[int(x)], + default="default", + ) + dynamo_config[prefix + "use_fullgraph"] = _ask_field( + "Do you want the fullgraph mode or it is ok to break model into several subgraphs? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + dynamo_config[prefix + "use_dynamic"] = _ask_field( + "Do you want to enable dynamic shape tracing? [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + ec2_instance_query = "Which EC2 instance type you want to use for your training?" + if distributed_type != SageMakerDistributedType.NO: + ec2_instance_type = _ask_options( + ec2_instance_query, SAGEMAKER_PARALLEL_EC2_INSTANCES, lambda x: SAGEMAKER_PARALLEL_EC2_INSTANCES[int(x)] + ) + else: + ec2_instance_query += "? [ml.p3.2xlarge]:" + ec2_instance_type = _ask_field(ec2_instance_query, lambda x: str(x).lower(), default="ml.p3.2xlarge") + + debug = False + if distributed_type != SageMakerDistributedType.NO: + debug = _ask_field( + "Should distributed operations be checked while running for errors? This can avoid timeout issues but will be slower. [yes/NO]: ", + _convert_yes_no_to_bool, + default=False, + error_message="Please enter yes or no.", + ) + + num_machines = 1 + if distributed_type in (SageMakerDistributedType.DATA_PARALLEL, SageMakerDistributedType.MODEL_PARALLEL): + num_machines = _ask_field( + "How many machines do you want use? [1]: ", + int, + default=1, + ) + + mixed_precision = _ask_options( + "Do you wish to use FP16 or BF16 (mixed precision)?", + ["no", "fp16", "bf16", "fp8"], + _convert_mixed_precision, + ) + + if use_dynamo and mixed_precision == "no": + print( + "Torch dynamo used without mixed precision requires TF32 to be efficient. Accelerate will enable it by default when launching your scripts." + ) + + return SageMakerConfig( + image_uri=docker_image, + compute_environment=ComputeEnvironment.AMAZON_SAGEMAKER, + distributed_type=distributed_type, + use_cpu=False, + dynamo_config=dynamo_config, + ec2_instance_type=ec2_instance_type, + profile=aws_profile, + region=aws_region, + iam_role_name=iam_role_name, + mixed_precision=mixed_precision, + num_machines=num_machines, + sagemaker_inputs_file=sagemaker_inputs_file, + sagemaker_metrics_file=sagemaker_metrics_file, + debug=debug, + ) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/update.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/update.py new file mode 100644 index 0000000000000000000000000000000000000000..5f025594b04ada3e3a78687befc5c1bc1d236adf --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/config/update.py @@ -0,0 +1,63 @@ +#!/usr/bin/env python + +# 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. + +from pathlib import Path + +from .config_args import default_config_file, load_config_from_file +from .config_utils import SubcommandHelpFormatter + + +description = "Update an existing config file with the latest defaults while maintaining the old configuration." + + +def update_config(args): + """ + Update an existing config file with the latest defaults while maintaining the old configuration. + """ + config_file = args.config_file + if config_file is None and Path(default_config_file).exists(): + config_file = default_config_file + elif not Path(config_file).exists(): + raise ValueError(f"The passed config file located at {config_file} doesn't exist.") + config = load_config_from_file(config_file) + + if config_file.endswith(".json"): + config.to_json_file(config_file) + else: + config.to_yaml_file(config_file) + return config_file + + +def update_command_parser(parser, parents): + parser = parser.add_parser("update", parents=parents, help=description, formatter_class=SubcommandHelpFormatter) + parser.add_argument( + "--config_file", + default=None, + help=( + "The path to the config file to update. Will default to a file named default_config.yaml in the cache " + "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " + "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " + "with 'huggingface'." + ), + ) + + parser.set_defaults(func=update_config_command) + return parser + + +def update_config_command(args): + config_file = update_config(args) + print(f"Sucessfully updated the configuration file at {config_file}.") diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/env.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/env.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd5995f6b480562d1c75fcb236a95a9f60d7f6f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/env.py @@ -0,0 +1,113 @@ +#!/usr/bin/env python + +# 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. + +import argparse +import os +import platform +import subprocess + +import numpy as np +import psutil +import torch + +from accelerate import __version__ as version +from accelerate.commands.config import default_config_file, load_config_from_file + +from ..utils import is_mlu_available, is_musa_available, is_npu_available, is_xpu_available + + +def env_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("env") + else: + parser = argparse.ArgumentParser("Accelerate env command") + + parser.add_argument( + "--config_file", default=None, help="The config file to use for the default values in the launching script." + ) + + if subparsers is not None: + parser.set_defaults(func=env_command) + return parser + + +def env_command(args): + pt_version = torch.__version__ + pt_cuda_available = torch.cuda.is_available() + pt_xpu_available = is_xpu_available() + pt_mlu_available = is_mlu_available() + pt_musa_available = is_musa_available() + pt_npu_available = is_npu_available() + + accelerate_config = "Not found" + # Get the default from the config file. + if args.config_file is not None or os.path.isfile(default_config_file): + accelerate_config = load_config_from_file(args.config_file).to_dict() + + # if we can run which, get it + command = None + bash_location = "Not found" + if os.name == "nt": + command = ["where", "accelerate"] + elif os.name == "posix": + command = ["which", "accelerate"] + if command is not None: + bash_location = subprocess.check_output(command, text=True, stderr=subprocess.STDOUT).strip() + info = { + "`Accelerate` version": version, + "Platform": platform.platform(), + "`accelerate` bash location": bash_location, + "Python version": platform.python_version(), + "Numpy version": np.__version__, + "PyTorch version (GPU?)": f"{pt_version} ({pt_cuda_available})", + "PyTorch XPU available": str(pt_xpu_available), + "PyTorch NPU available": str(pt_npu_available), + "PyTorch MLU available": str(pt_mlu_available), + "PyTorch MUSA available": str(pt_musa_available), + "System RAM": f"{psutil.virtual_memory().total / 1024 ** 3:.2f} GB", + } + if pt_cuda_available: + info["GPU type"] = torch.cuda.get_device_name() + if pt_mlu_available: + info["MLU type"] = torch.mlu.get_device_name() + if pt_npu_available: + info["CANN version"] = torch.version.cann + + print("\nCopy-and-paste the text below in your GitHub issue\n") + print("\n".join([f"- {prop}: {val}" for prop, val in info.items()])) + + print("- `Accelerate` default config:" if args.config_file is None else "- `Accelerate` config passed:") + accelerate_config_str = ( + "\n".join([f"\t- {prop}: {val}" for prop, val in accelerate_config.items()]) + if isinstance(accelerate_config, dict) + else f"\t{accelerate_config}" + ) + print(accelerate_config_str) + + info["`Accelerate` configs"] = accelerate_config + + return info + + +def main() -> int: + parser = env_command_parser() + args = parser.parse_args() + env_command(args) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/estimate.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/estimate.py new file mode 100644 index 0000000000000000000000000000000000000000..2cd731b222143e54b5f15e21bf386819ee6cacdd --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/estimate.py @@ -0,0 +1,309 @@ +#!/usr/bin/env python + +# 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. +from huggingface_hub import model_info +from huggingface_hub.utils import GatedRepoError, RepositoryNotFoundError + +from accelerate import init_empty_weights +from accelerate.commands.utils import CustomArgumentParser +from accelerate.utils import ( + calculate_maximum_sizes, + convert_bytes, + is_timm_available, + is_transformers_available, +) + + +if is_transformers_available(): + import transformers + from transformers import AutoConfig, AutoModel + +if is_timm_available(): + import timm + + +def verify_on_hub(repo: str, token: str = None): + "Verifies that the model is on the hub and returns the model info." + try: + return model_info(repo, token=token) + except (OSError, GatedRepoError): + return "gated" + except RepositoryNotFoundError: + return "repo" + + +def check_has_model(error): + """ + Checks what library spawned `error` when a model is not found + """ + if is_timm_available() and isinstance(error, RuntimeError) and "Unknown model" in error.args[0]: + return "timm" + elif ( + is_transformers_available() + and isinstance(error, OSError) + and "does not appear to have a file named" in error.args[0] + ): + return "transformers" + else: + return "unknown" + + +def create_empty_model(model_name: str, library_name: str, trust_remote_code: bool = False, access_token: str = None): + """ + Creates an empty model from its parent library on the `Hub` to calculate the overall memory consumption. + + Args: + model_name (`str`): + The model name on the Hub + library_name (`str`): + The library the model has an integration with, such as `transformers`. Will be used if `model_name` has no + metadata on the Hub to determine the library. + trust_remote_code (`bool`, `optional`, defaults to `False`): + Whether or not to allow for custom models defined on the Hub in their own modeling files. This option + should only be set to `True` for repositories you trust and in which you have read the code, as it will + execute code present on the Hub on your local machine. + access_token (`str`, `optional`, defaults to `None`): + The access token to use to access private or gated models on the Hub. (for use on the Gradio app) + + Returns: + `torch.nn.Module`: The torch model that has been initialized on the `meta` device. + + """ + model_info = verify_on_hub(model_name, access_token) + # Simplified errors + if model_info == "gated": + raise GatedRepoError( + f"Repo for model `{model_name}` is gated. You must be authenticated to access it. Please run `huggingface-cli login`." + ) + elif model_info == "repo": + raise RepositoryNotFoundError( + f"Repo for model `{model_name}` does not exist on the Hub. If you are trying to access a private repo," + " make sure you are authenticated via `huggingface-cli login` and have access." + ) + if library_name is None: + library_name = getattr(model_info, "library_name", False) + if not library_name: + raise ValueError( + f"Model `{model_name}` does not have any library metadata on the Hub, please manually pass in a `--library_name` to use (such as `transformers`)" + ) + if library_name == "transformers": + if not is_transformers_available(): + raise ImportError( + f"To check `{model_name}`, `transformers` must be installed. Please install it via `pip install transformers`" + ) + print(f"Loading pretrained config for `{model_name}` from `transformers`...") + if model_info.config is None: + raise RuntimeError(f"Tried to load `{model_name}` with `transformers` but it does not have any metadata.") + + auto_map = model_info.config.get("auto_map", False) + config = AutoConfig.from_pretrained(model_name, trust_remote_code=trust_remote_code, token=access_token) + with init_empty_weights(): + # remote code could specify a specific `AutoModel` class in the `auto_map` + constructor = AutoModel + if isinstance(auto_map, dict): + value = None + for key in auto_map.keys(): + if key.startswith("AutoModelFor"): + value = key + break + if value is not None: + constructor = getattr(transformers, value) + model = constructor.from_config(config, trust_remote_code=trust_remote_code) + elif library_name == "timm": + if not is_timm_available(): + raise ImportError( + f"To check `{model_name}`, `timm` must be installed. Please install it via `pip install timm`" + ) + print(f"Loading pretrained config for `{model_name}` from `timm`...") + with init_empty_weights(): + model = timm.create_model(model_name, pretrained=False) + else: + raise ValueError( + f"Library `{library_name}` is not supported yet, please open an issue on GitHub for us to add support." + ) + return model + + +def create_ascii_table(headers: list, rows: list, title: str): + "Creates a pretty table from a list of rows, minimal version of `tabulate`." + sep_char, in_between = "│", "─" + column_widths = [] + for i in range(len(headers)): + column_values = [row[i] for row in rows] + [headers[i]] + max_column_width = max(len(value) for value in column_values) + column_widths.append(max_column_width) + + formats = [f"%{column_widths[i]}s" for i in range(len(rows[0]))] + + pattern = f"{sep_char}{sep_char.join(formats)}{sep_char}" + diff = 0 + + def make_row(left_char, middle_char, right_char): + return f"{left_char}{middle_char.join([in_between * n for n in column_widths])}{in_between * diff}{right_char}" + + separator = make_row("├", "┼", "┤") + if len(title) > sum(column_widths): + diff = abs(len(title) - len(separator)) + column_widths[-1] += diff + + # Update with diff + separator = make_row("├", "┼", "┤") + initial_rows = [ + make_row("┌", in_between, "┐"), + f"{sep_char}{title.center(len(separator) - 2)}{sep_char}", + make_row("├", "┬", "┤"), + ] + table = "\n".join(initial_rows) + "\n" + column_widths[-1] += diff + centered_line = [text.center(column_widths[i]) for i, text in enumerate(headers)] + table += f"{pattern % tuple(centered_line)}\n{separator}\n" + for i, line in enumerate(rows): + centered_line = [t.center(column_widths[i]) for i, t in enumerate(line)] + table += f"{pattern % tuple(centered_line)}\n" + table += f'└{"┴".join([in_between * n for n in column_widths])}┘' + + return table + + +def estimate_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("estimate-memory") + else: + parser = CustomArgumentParser(description="Model size estimator for fitting a model onto CUDA memory.") + + parser.add_argument("model_name", type=str, help="The model name on the Hugging Face Hub.") + parser.add_argument( + "--library_name", + type=str, + help="The library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub.", + choices=["timm", "transformers"], + ) + parser.add_argument( + "--dtypes", + type=str, + nargs="+", + default=["float32", "float16", "int8", "int4"], + help="The dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4`", + choices=["float32", "float16", "int8", "int4"], + ) + parser.add_argument( + "--trust_remote_code", + action="store_true", + help="""Whether or not to allow for custom models defined on the Hub in their own modeling files. This flag + should only be used for repositories you trust and in which you have read the code, as it will execute + code present on the Hub on your local machine.""", + default=False, + ) + + if subparsers is not None: + parser.set_defaults(func=estimate_command) + return parser + + +def estimate_training_usage(bytes: int, mixed_precision: str, msamp_config: str = None) -> dict: + """ + Given an amount of `bytes` and `mixed_precision`, calculates how much training memory is needed for a batch size of + 1. + + Args: + bytes (`int`): + The size of the model being trained. + mixed_precision (`str`): + The mixed precision that would be ran. + msamp_config (`str`): + The msamp config to estimate the training memory for if `mixed_precision` is set to `"fp8"`. + """ + memory_sizes = {"model": -1, "optimizer": -1, "gradients": -1, "step": -1} + fp32_size = bytes + fp16_size = bytes // 2 + + if mixed_precision == "float32": + memory_sizes["model"] = fp32_size + memory_sizes["gradients"] = fp32_size + memory_sizes["optimizer"] = fp32_size * 2 + memory_sizes["step"] = fp32_size * 4 + elif mixed_precision in ("float16", "bfloat16") or (mixed_precision == "fp8" and msamp_config is None): + # With native `TransformersEngine`, there is no memory savings with FP8 + # With mixed precision training, the model has weights stored + # in FP16 and FP32 + memory_sizes["model"] = fp32_size + # 1.5 from weight gradient + computation (GEMM) + memory_sizes["gradients"] = fp32_size + fp16_size + # 2x from optimizer states + memory_sizes["optimizer"] = fp32_size * 2 # Optimizer states + memory_sizes["step"] = memory_sizes["optimizer"] + return memory_sizes + + +def gather_data(args): + "Creates an empty model and gathers the data for the sizes" + try: + model = create_empty_model( + args.model_name, library_name=args.library_name, trust_remote_code=args.trust_remote_code + ) + except (RuntimeError, OSError) as e: + library = check_has_model(e) + if library != "unknown": + raise RuntimeError( + f"Tried to load `{args.model_name}` with `{library}` but a possible model to load was not found inside the repo." + ) + raise e + + total_size, largest_layer = calculate_maximum_sizes(model) + + data = [] + + for dtype in args.dtypes: + dtype_total_size = total_size + dtype_largest_layer = largest_layer[0] + dtype_training_size = estimate_training_usage(dtype_total_size, dtype) + if dtype == "float16": + dtype_total_size /= 2 + dtype_largest_layer /= 2 + elif dtype == "int8": + dtype_total_size /= 4 + dtype_largest_layer /= 4 + elif dtype == "int4": + dtype_total_size /= 8 + dtype_largest_layer /= 8 + data.append([dtype, dtype_largest_layer, dtype_total_size, dtype_training_size]) + return data + + +def estimate_command(args): + data = gather_data(args) + for row in data: + for i, item in enumerate(row): + if isinstance(item, (int, float)): + row[i] = convert_bytes(item) + elif isinstance(item, dict): + training_usage = max(item.values()) + row[i] = convert_bytes(training_usage) if training_usage != -1 else "N/A" + + headers = ["dtype", "Largest Layer", "Total Size", "Training using Adam"] + + title = f"Memory Usage for loading `{args.model_name}`" + table = create_ascii_table(headers, data, title) + print(table) + + +def main(): + parser = estimate_command_parser() + args = parser.parse_args() + estimate_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/launch.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..b4f606f493a083d5c7f67ddc5dfb17b64198e9ea --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/launch.py @@ -0,0 +1,1184 @@ +#!/usr/bin/env python + +# 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. + +import argparse +import importlib +import logging +import os +import subprocess +import sys +from pathlib import Path + +import psutil +import torch + +from accelerate.commands.config import default_config_file, load_config_from_file +from accelerate.commands.config.config_args import SageMakerConfig +from accelerate.commands.config.config_utils import DYNAMO_BACKENDS +from accelerate.commands.utils import CustomArgumentParser +from accelerate.state import get_int_from_env +from accelerate.utils import ( + ComputeEnvironment, + DistributedType, + PrepareForLaunch, + _filter_args, + check_cuda_p2p_ib_support, + convert_dict_to_env_variables, + is_bf16_available, + is_deepspeed_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_rich_available, + is_sagemaker_available, + is_torch_version, + is_torch_xla_available, + is_xpu_available, + patch_environment, + prepare_deepspeed_cmd_env, + prepare_multi_gpu_env, + prepare_sagemager_args_inputs, + prepare_simple_launcher_cmd_env, + prepare_tpu, + str_to_bool, +) +from accelerate.utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS, TORCH_DYNAMO_MODES + + +if is_rich_available(): + from rich import get_console + from rich.logging import RichHandler + + FORMAT = "%(message)s" + logging.basicConfig(format=FORMAT, datefmt="[%X]", handlers=[RichHandler()]) + + +logger = logging.getLogger(__name__) + + +options_to_group = { + "multi_gpu": "Distributed GPUs", + "tpu": "TPU", + "use_deepspeed": "DeepSpeed Arguments", + "use_fsdp": "FSDP Arguments", + "use_megatron_lm": "Megatron-LM Arguments", + "fp8_backend": "FP8 Arguments", +} + + +def clean_option(option): + "Finds all cases of - after the first two characters and changes them to _" + if "fp8_backend" in option: + option = "--fp8_backend" + if option.startswith("--"): + return option[2:].replace("-", "_") + + +class CustomHelpFormatter(argparse.HelpFormatter): + """ + This is a custom help formatter that will hide all arguments that are not used in the command line when the help is + called. This is useful for the case where the user is using a specific platform and only wants to see the arguments + for that platform. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.titles = [ + "Hardware Selection Arguments", + "Resource Selection Arguments", + "Training Paradigm Arguments", + "positional arguments", + "optional arguments", + ] + + def add_argument(self, action: argparse.Action): + if "accelerate" in sys.argv[0] and "launch" in sys.argv[1:]: + args = sys.argv[2:] + else: + args = sys.argv[1:] + + if len(args) > 1: + args = list(map(clean_option, args)) + used_platforms = [arg for arg in args if arg in options_to_group.keys()] + used_titles = [options_to_group[o] for o in used_platforms] + if action.container.title not in self.titles + used_titles: + action.help = argparse.SUPPRESS + elif action.container.title == "Hardware Selection Arguments": + if set(action.option_strings).isdisjoint(set(args)): + action.help = argparse.SUPPRESS + else: + action.help = action.help + " (currently selected)" + elif action.container.title == "Training Paradigm Arguments": + if set(action.option_strings).isdisjoint(set(args)): + action.help = argparse.SUPPRESS + else: + action.help = action.help + " (currently selected)" + + action.option_strings = [s for s in action.option_strings if "-" not in s[2:]] + super().add_argument(action) + + def end_section(self): + if len(self._current_section.items) < 2: + self._current_section.items = [] + self._current_section.heading = "" + super().end_section() + + +def launch_command_parser(subparsers=None): + description = "Launch a python script in a distributed scenario. Arguments can be passed in with either hyphens (`--num-processes=2`) or underscores (`--num_processes=2`)" + if subparsers is not None: + parser = subparsers.add_parser( + "launch", description=description, add_help=False, allow_abbrev=False, formatter_class=CustomHelpFormatter + ) + else: + parser = CustomArgumentParser( + "Accelerate launch command", + description=description, + add_help=False, + allow_abbrev=False, + formatter_class=CustomHelpFormatter, + ) + + parser.add_argument("-h", "--help", action="help", help="Show this help message and exit.") + + parser.add_argument( + "--config_file", + default=None, + help="The config file to use for the default values in the launching script.", + ) + parser.add_argument( + "--quiet", + "-q", + action="store_true", + help="Silence subprocess errors from the launch stack trace and only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations)", + ) + # Hardware selection arguments + hardware_args = parser.add_argument_group( + "Hardware Selection Arguments", "Arguments for selecting the hardware to be used." + ) + hardware_args.add_argument( + "--cpu", default=False, action="store_true", help="Whether or not to force the training on the CPU." + ) + hardware_args.add_argument( + "--multi_gpu", + default=False, + action="store_true", + help="Whether or not this should launch a distributed GPU training.", + ) + hardware_args.add_argument( + "--tpu", default=False, action="store_true", help="Whether or not this should launch a TPU training." + ) + hardware_args.add_argument( + "--ipex", + default=False, + action="store_true", + help="Whether or not this should launch a Intel PyTorch Extension (IPEX) training.", + ) + + # Resource selection arguments + resource_args = parser.add_argument_group( + "Resource Selection Arguments", "Arguments for fine-tuning how available hardware should be used." + ) + resource_args.add_argument( + "--mixed_precision", + type=str, + choices=["no", "fp16", "bf16", "fp8"], + help="Whether or not to use mixed precision training. " + "Choose between FP16 and BF16 (bfloat16) training. " + "BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later.", + ) + resource_args.add_argument( + "--num_processes", type=int, default=None, help="The total number of processes to be launched in parallel." + ) + resource_args.add_argument( + "--num_machines", type=int, default=None, help="The total number of machines used in this training." + ) + resource_args.add_argument( + "--num_cpu_threads_per_process", + type=int, + default=None, + help="The number of CPU threads per process. Can be tuned for optimal performance.", + ) + resource_args.add_argument( + "--enable_cpu_affinity", + default=False, + action="store_true", + help="Whether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware.", + ) + # Dynamo arguments + resource_args.add_argument( + "--dynamo_backend", + type=str, + choices=["no"] + [b.lower() for b in DYNAMO_BACKENDS], + help="Choose a backend to optimize your training with dynamo, see more at " + "https://github.com/pytorch/torchdynamo.", + ) + resource_args.add_argument( + "--dynamo_mode", + type=str, + default="default", + choices=TORCH_DYNAMO_MODES, + help="Choose a mode to optimize your training with dynamo.", + ) + resource_args.add_argument( + "--dynamo_use_fullgraph", + default=False, + action="store_true", + help="Whether to use full graph mode for dynamo or it is ok to break model into several subgraphs", + ) + resource_args.add_argument( + "--dynamo_use_dynamic", + default=False, + action="store_true", + help="Whether to enable dynamic shape tracing.", + ) + + # Training Paradigm arguments + paradigm_args = parser.add_argument_group( + "Training Paradigm Arguments", "Arguments for selecting which training paradigm to be used." + ) + paradigm_args.add_argument( + "--use_deepspeed", + default=False, + action="store_true", + help="Whether to use deepspeed.", + ) + paradigm_args.add_argument( + "--use_fsdp", + default=False, + action="store_true", + help="Whether to use fsdp.", + ) + paradigm_args.add_argument( + "--use_megatron_lm", + default=False, + action="store_true", + help="Whether to use Megatron-LM.", + ) + paradigm_args.add_argument( + "--use_xpu", + default=False, + action="store_true", + help="Whether to use IPEX plugin to speed up training on XPU specifically.", + ) + + # distributed GPU training arguments + distributed_args = parser.add_argument_group("Distributed GPUs", "Arguments related to distributed GPU training.") + distributed_args.add_argument( + "--gpu_ids", + default=None, + help="What GPUs (by id) should be used for training on this machine as a comma-seperated list", + ) + distributed_args.add_argument( + "--same_network", + default=False, + action="store_true", + help="Whether all machines used for multinode training exist on the same local network.", + ) + distributed_args.add_argument( + "--machine_rank", type=int, default=None, help="The rank of the machine on which this script is launched." + ) + distributed_args.add_argument( + "--main_process_ip", type=str, default=None, help="The IP address of the machine of rank 0." + ) + distributed_args.add_argument( + "--main_process_port", + type=int, + default=None, + help="The port to use to communicate with the machine of rank 0.", + ) + distributed_args.add_argument( + "-t", + "--tee", + default="0", + type=str, + help="Tee std streams into a log file and also to console.", + ) + distributed_args.add_argument( + "--log_dir", + type=str, + default=None, + help=( + "Base directory to use for log files when using torchrun/torch.distributed.run as launcher. " + "Use with --tee to redirect std streams info log files." + ), + ) + distributed_args.add_argument( + "--role", + type=str, + default="default", + help="User-defined role for the workers.", + ) + # Rendezvous related arguments + distributed_args.add_argument( + "--rdzv_backend", + type=str, + default="static", + help="The rendezvous method to use, such as 'static' (the default) or 'c10d'", + ) + distributed_args.add_argument( + "--rdzv_conf", + type=str, + default="", + help="Additional rendezvous configuration (=,=,...).", + ) + distributed_args.add_argument( + "--max_restarts", + type=int, + default=0, + help="Maximum number of worker group restarts before failing.", + ) + distributed_args.add_argument( + "--monitor_interval", + type=float, + default=0.1, + help="Interval, in seconds, to monitor the state of workers.", + ) + parser.add_argument( + "-m", + "--module", + action="store_true", + help="Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'.", + ) + parser.add_argument( + "--no_python", + action="store_true", + help="Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script.", + ) + + # TPU arguments + tpu_args = parser.add_argument_group("TPU", "Arguments related to TPU.") + tpu_args.add_argument( + "--tpu_cluster", + action="store_true", + dest="tpu_use_cluster", + help="Whether to use a GCP TPU pod for training.", + ) + tpu_args.add_argument( + "--no_tpu_cluster", + action="store_false", + dest="tpu_use_cluster", + help="Should not be passed explicitly, this is for internal use only.", + ) + tpu_args.add_argument( + "--tpu_use_sudo", + action="store_true", + help="Whether to use `sudo` when running the TPU training script in each pod.", + ) + tpu_args.add_argument( + "--vm", + type=str, + action="append", + help=( + "List of single Compute VM instance names. " + "If not provided we assume usage of instance groups. For TPU pods." + ), + ) + tpu_args.add_argument( + "--env", + type=str, + action="append", + help="List of environment variables to set on the Compute VM instances. For TPU pods.", + ) + tpu_args.add_argument( + "--main_training_function", + type=str, + default=None, + help="The name of the main function to be executed in your script (only for TPU training).", + ) + tpu_args.add_argument( + "--downcast_bf16", + action="store_true", + help="Whether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32.", + ) + + # DeepSpeed arguments + deepspeed_args = parser.add_argument_group("DeepSpeed Arguments", "Arguments related to DeepSpeed.") + deepspeed_args.add_argument( + "--deepspeed_config_file", + default=None, + type=str, + help="DeepSpeed config file.", + ) + deepspeed_args.add_argument( + "--zero_stage", + default=None, + type=int, + help="DeepSpeed's ZeRO optimization stage (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to `2`.", + ) + deepspeed_args.add_argument( + "--offload_optimizer_device", + default=None, + type=str, + help="Decides where (none|cpu|nvme) to offload optimizer states (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to 'none'.", + ) + deepspeed_args.add_argument( + "--offload_param_device", + default=None, + type=str, + help="Decides where (none|cpu|nvme) to offload parameters (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to 'none'.", + ) + deepspeed_args.add_argument( + "--offload_optimizer_nvme_path", + default=None, + type=str, + help="Decides Nvme Path to offload optimizer states (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to 'none'.", + ) + deepspeed_args.add_argument( + "--offload_param_nvme_path", + default=None, + type=str, + help="Decides Nvme Path to offload parameters (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to 'none'.", + ) + deepspeed_args.add_argument( + "--gradient_accumulation_steps", + default=None, + type=int, + help="No of gradient_accumulation_steps used in your training script (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to `1`.", + ) + deepspeed_args.add_argument( + "--gradient_clipping", + default=None, + type=float, + help="gradient clipping value used in your training script (useful only when `use_deepspeed` flag is passed). " + "If unspecified, will default to `1.0`.", + ) + deepspeed_args.add_argument( + "--zero3_init_flag", + default=None, + type=str, + help="Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. " + "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `true`.", + ) + deepspeed_args.add_argument( + "--zero3_save_16bit_model", + default=None, + type=str, + help="Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. " + "Only applicable with DeepSpeed ZeRO Stage-3. If unspecified, will default to `false`.", + ) + deepspeed_args.add_argument( + "--deepspeed_hostfile", + default=None, + type=str, + help="DeepSpeed hostfile for configuring multi-node compute resources.", + ) + deepspeed_args.add_argument( + "--deepspeed_exclusion_filter", + default=None, + type=str, + help="DeepSpeed exclusion filter string when using mutli-node setup.", + ) + deepspeed_args.add_argument( + "--deepspeed_inclusion_filter", + default=None, + type=str, + help="DeepSpeed inclusion filter string when using mutli-node setup.", + ) + deepspeed_args.add_argument( + "--deepspeed_multinode_launcher", + default=None, + type=str, + help="DeepSpeed multi-node launcher to use. If unspecified, will default to `pdsh`.", + ) + deepspeed_args.add_argument( + "--deepspeed_moe_layer_cls_names", + default=None, + type=str, + help="comma-separated list of transformer MoE layer class names (case-sensitive) to wrap ,e.g, `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..." + " (useful only when `use_deepspeed` flag is passed).", + ) + + # fsdp arguments + fsdp_args = parser.add_argument_group("FSDP Arguments", "Arguments related to Fully Shared Data Parallelism.") + fsdp_args.add_argument( + "--fsdp_offload_params", + default="false", + type=str, + help="Decides Whether (true|false) to offload parameters and gradients to CPU. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_min_num_params", + type=int, + default=1e8, + help="FSDP's minimum number of parameters for Default Auto Wrapping. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_sharding_strategy", + type=str, + default="FULL_SHARD", + help="FSDP's Sharding Strategy. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_auto_wrap_policy", + type=str, + default=None, + help="FSDP's auto wrap policy. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_transformer_layer_cls_to_wrap", + default=None, + type=str, + help="Transformer layer class name (case-sensitive) to wrap ,e.g, `BertLayer`, `GPTJBlock`, `T5Block` .... " + "(useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_backward_prefetch_policy", + default=None, + type=str, + help="This argument is deprecated and will be removed in version 0.27.0 of 🤗 Accelerate. Use `fsdp_backward_prefetch` instead.", + ) + fsdp_args.add_argument( + "--fsdp_backward_prefetch", + default=None, + type=str, + help="FSDP's backward prefetch policy. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_state_dict_type", + default=None, + type=str, + help="FSDP's state dict type. (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_forward_prefetch", + default="false", + type=str, + help="If True, then FSDP explicitly prefetches the next upcoming " + "all-gather while executing in the forward pass (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_use_orig_params", + default="true", + type=str, + help="If True, allows non-uniform `requires_grad` during init, which means support for interspersed frozen and trainable paramteres." + " (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_cpu_ram_efficient_loading", + default="true", + type=str, + help="If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. " + "Only applicable for 🤗 Transformers. When using this, `--fsdp_sync_module_states` needs to True. " + "(useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_sync_module_states", + default="true", + type=str, + help="If True, each individually wrapped FSDP unit will broadcast module parameters from rank 0." + " (useful only when `use_fsdp` flag is passed).", + ) + fsdp_args.add_argument( + "--fsdp_activation_checkpointing", + default="false", + type=str, + help="Decides Whether (true|false) intermediate activations are freed during the forward pass, and a checkpoint is left as a placeholder. (useful only when `use_fsdp` flag is passed).", + ) + + # megatron_lm args + megatron_lm_args = parser.add_argument_group("Megatron-LM Arguments", "Arguments related to Megatron-LM.") + megatron_lm_args.add_argument( + "--megatron_lm_tp_degree", + type=int, + default=1, + help="Megatron-LM's Tensor Parallelism (TP) degree. (useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_pp_degree", + type=int, + default=1, + help="Megatron-LM's Pipeline Parallelism (PP) degree. (useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_num_micro_batches", + type=int, + default=None, + help="Megatron-LM's number of micro batches when PP degree > 1. (useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_sequence_parallelism", + default=None, + type=str, + help="Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. " + "(useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_recompute_activations", + default=None, + type=str, + help="Decides Whether (true|false) to enable Selective Activation Recomputation. " + "(useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_use_distributed_optimizer", + default=None, + type=str, + help="Decides Whether (true|false) to use distributed optimizer " + "which shards optimizer state and gradients across Data Pralellel (DP) ranks. " + "(useful only when `use_megatron_lm` flag is passed).", + ) + megatron_lm_args.add_argument( + "--megatron_lm_gradient_clipping", + default=1.0, + type=float, + help="Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). " + "(useful only when `use_megatron_lm` flag is passed).", + ) + + # FP8 arguments + fp8_args = parser.add_argument_group( + "FP8 Arguments", "Arguments related to FP8 training (requires `--mixed_precision=fp8`)" + ) + fp8_args.add_argument( + "--fp8_backend", + type=str, + choices=["te", "msamp"], + help="Choose a backend to train with FP8 (te: TransformerEngine, msamp: MS-AMP)", + ) + fp8_args.add_argument( + "--fp8_use_autocast_during_eval", + default=False, + action="store_true", + help="Whether to use FP8 autocast during eval mode (useful only when `--fp8_backend=te` is passed). Generally better metrics are found when this is not passed.", + ) + fp8_args.add_argument( + "--fp8_margin", + type=int, + default=0, + help="The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_interval", + type=int, + default=1, + help="The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_format", + type=str, + default="E4M3", + choices=["E4M3", "HYBRID"], + help="The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_amax_history_len", + type=int, + default=1024, + help="The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_amax_compute_algo", + type=str, + default="most_recent", + choices=["max", "most_recent"], + help="The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_override_linear_precision", + type=lambda x: tuple(map(str_to_bool, x.split(","))), + default=(False, False, False), + help="Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. Should be passed in a comma-seperated string of booleans (useful only when `--fp8_backend=te` is passed).", + ) + fp8_args.add_argument( + "--fp8_opt_level", + type=str, + default="O2", + choices=["O1", "O2"], + help="What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed).", + ) + + # AWS arguments + aws_args = parser.add_argument_group("AWS Arguments", "Arguments related to AWS.") + aws_args.add_argument( + "--aws_access_key_id", + type=str, + default=None, + help="The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job", + ) + aws_args.add_argument( + "--aws_secret_access_key", + type=str, + default=None, + help="The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job.", + ) + parser.add_argument( + "--debug", + action="store_true", + help="Whether to print out the torch.distributed stack trace when something fails.", + ) + parser.add_argument( + "training_script", + type=str, + help=( + "The full path to the script to be launched in parallel, followed by all the arguments for the training " + "script." + ), + ) + + # MPI arguments + mpirun_args = parser.add_argument_group("MPI Arguments", "Arguments related to mpirun for Multi-CPU") + mpirun_args.add_argument( + "--mpirun_hostfile", + type=str, + default=None, + help="Location for a hostfile for using Accelerate to launch a multi-CPU training job with mpirun. This will " + "get passed to the MPI --hostfile or -f parameter, depending on which MPI program is installed.", + ) + mpirun_args.add_argument( + "--mpirun_ccl", + type=int, + default=1, + help="The number of oneCCL worker threads when using Accelerate to launch multi-CPU training with mpirun.", + ) + + # Other arguments of the training scripts + parser.add_argument("training_script_args", nargs=argparse.REMAINDER, help="Arguments of the training script.") + + if subparsers is not None: + parser.set_defaults(func=launch_command) + return parser + + +def simple_launcher(args): + cmd, current_env = prepare_simple_launcher_cmd_env(args) + + process = subprocess.Popen(cmd, env=current_env) + process.wait() + if process.returncode != 0: + if not args.quiet: + raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd) + else: + sys.exit(1) + + +def multi_gpu_launcher(args): + import torch.distributed.run as distrib_run + + current_env = prepare_multi_gpu_env(args) + if not check_cuda_p2p_ib_support(): + message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled." + warn = False + if "NCCL_P2P_DISABLE" not in current_env: + current_env["NCCL_P2P_DISABLE"] = "1" + warn = True + if "NCCL_IB_DISABLE" not in current_env: + current_env["NCCL_IB_DISABLE"] = "1" + warn = True + if warn: + logger.warning(message) + + debug = getattr(args, "debug", False) + args = _filter_args( + args, + distrib_run.get_args_parser(), + ["--training_script", args.training_script, "--training_script_args", args.training_script_args], + ) + + with patch_environment(**current_env): + try: + distrib_run.run(args) + except Exception: + if is_rich_available() and debug: + console = get_console() + console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]") + console.print_exception(suppress=[__file__], show_locals=False) + else: + raise + + +def deepspeed_launcher(args): + import torch.distributed.run as distrib_run + + if not is_deepspeed_available(): + raise ImportError("DeepSpeed is not installed => run `pip3 install deepspeed` or build it from source.") + else: + from deepspeed.launcher.runner import DEEPSPEED_ENVIRONMENT_NAME + + cmd, current_env = prepare_deepspeed_cmd_env(args) + if not check_cuda_p2p_ib_support(): + message = "Using RTX 4000 series which doesn't support faster communication speedups. Ensuring P2P and IB communications are disabled." + warn = False + if "NCCL_P2P_DISABLE" not in current_env: + current_env["NCCL_P2P_DISABLE"] = "1" + warn = True + if "NCCL_IB_DISABLE" not in current_env: + current_env["NCCL_IB_DISABLE"] = "1" + warn = True + if warn: + logger.warning(message) + + if args.num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]: + with open(DEEPSPEED_ENVIRONMENT_NAME, "a") as f: + valid_env_items = convert_dict_to_env_variables(current_env) + if len(valid_env_items) > 1: + f.writelines(valid_env_items) + + process = subprocess.Popen(cmd, env=current_env) + process.wait() + if process.returncode != 0: + if not args.quiet: + raise subprocess.CalledProcessError(returncode=process.returncode, cmd=cmd) + else: + sys.exit(1) + else: + debug = getattr(args, "debug", False) + args = _filter_args( + args, + distrib_run.get_args_parser(), + ["--training_script", args.training_script, "--training_script_args", args.training_script_args], + ) + with patch_environment(**current_env): + try: + distrib_run.run(args) + except Exception: + if is_rich_available() and debug: + console = get_console() + console.print("\n[bold red]Using --debug, `torch.distributed` Stack Trace:[/bold red]") + console.print_exception(suppress=[__file__], show_locals=False) + else: + raise + + +def tpu_launcher(args): + import torch_xla.distributed.xla_multiprocessing as xmp + + if args.no_python: + raise ValueError("--no_python cannot be used with TPU launcher") + + args, current_env = prepare_tpu(args, {}) + + if args.module: + mod_name = args.training_script + else: + # Import training_script as a module + script_path = Path(args.training_script) + sys.path.append(str(script_path.parent.resolve())) + mod_name = script_path.stem + + mod = importlib.import_module(mod_name) + if not hasattr(mod, args.main_training_function): + raise ValueError( + f"Your training script should have a function named {args.main_training_function}, or you should pass a " + "different value to `--main_training_function`." + ) + + # Patch sys.argv + sys.argv = [mod.__file__] + args.training_script_args + + main_function = getattr(mod, args.main_training_function) + with patch_environment(**current_env): + xmp.spawn(PrepareForLaunch(main_function), args=(), nprocs=args.num_processes) + + +def tpu_pod_launcher(args): + from torch_xla.distributed import xla_dist + + current_env = {} + args, current_env = prepare_tpu(args, current_env, True) + debug = getattr(args, "debug", False) + + training_script = args.training_script + training_script_args = args.training_script_args + new_args = _filter_args( + args, xla_dist.get_args_parser(), ["--tpu", args.tpu_name, "--positional", "", "--restart-tpuvm-pod-server"] + ) + + if args.tpu_use_sudo: + new_cmd = ["sudo"] + else: + new_cmd = [] + + new_cmd += [ + "accelerate-launch", + "--tpu", + "--no_tpu_cluster", + "--num_machines", + "1", + "--mixed_precision", + "no", + "--dynamo_backend", + "no", + "--num_processes", + str(args.num_processes), + "--main_training_function", + str(args.main_training_function), + training_script, + ] + training_script_args + + new_args.positional = new_cmd + bad_flags = "" + for arg in vars(new_args): + if arg.startswith("docker_"): + value = getattr(new_args, arg) + if value != "" and value is not None: + bad_flags += f'{arg}="{value}"\n' + if bad_flags != "": + raise ValueError( + f"Docker containers are not supported for TPU pod launcher currently, please remove the following flags:\n{bad_flags}" + ) + new_args.env = [f"{k}={v}" for k, v in current_env.items()] + new_args.env.append("ACCELERATE_IN_TPU_POD=1") + try: + xla_dist.resolve_and_execute(new_args) + except Exception: + if is_rich_available() and debug: + console = get_console() + console.print("\n[bold red]Using --debug, `torch_xla.xla_dist` Stack Trace:[/bold red]") + console.print_exception(suppress=[__file__], show_locals=False) + else: + raise + + +def sagemaker_launcher(sagemaker_config: SageMakerConfig, args): + if not is_sagemaker_available(): + raise ImportError( + "Please install sagemaker to be able to launch training on Amazon SageMaker with `pip install accelerate[sagemaker]`" + ) + if args.module or args.no_python: + raise ValueError( + "SageMaker requires a python training script file and cannot be used with --module or --no_python" + ) + + from sagemaker.huggingface import HuggingFace + + args, sagemaker_inputs = prepare_sagemager_args_inputs(sagemaker_config, args) + + huggingface_estimator = HuggingFace(**args) + + huggingface_estimator.fit(inputs=sagemaker_inputs) + print(f"You can find your model data at: {huggingface_estimator.model_data}") + + +def _validate_launch_command(args): + # Sanity checks + if sum([args.multi_gpu, args.cpu, args.tpu, args.use_deepspeed, args.use_fsdp]) > 1: + raise ValueError( + "You can only use one of `--cpu`, `--multi_gpu`, `--tpu`, `--use_deepspeed`, `--use_fsdp` at a time." + ) + if args.multi_gpu and (args.num_processes is not None) and (args.num_processes < 2): + raise ValueError("You need to use at least 2 processes to use `--multi_gpu`.") + + defaults = None + warned = [] + mp_from_config_flag = False + # Get the default from the config file. + if args.config_file is not None or os.path.isfile(default_config_file) and not args.cpu: + defaults = load_config_from_file(args.config_file) + if ( + not args.multi_gpu + and not args.tpu + and not args.tpu_use_cluster + and not args.use_deepspeed + and not args.use_fsdp + and not args.use_megatron_lm + ): + args.use_deepspeed = defaults.distributed_type == DistributedType.DEEPSPEED + args.multi_gpu = ( + True + if defaults.distributed_type + in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_XPU, + ) + else False + ) + args.tpu = defaults.distributed_type == DistributedType.XLA + args.use_fsdp = defaults.distributed_type == DistributedType.FSDP + args.use_megatron_lm = defaults.distributed_type == DistributedType.MEGATRON_LM + args.tpu_use_cluster = defaults.tpu_use_cluster if args.tpu else False + if args.gpu_ids is None: + if defaults.gpu_ids is not None: + args.gpu_ids = defaults.gpu_ids + else: + args.gpu_ids = "all" + + if args.multi_gpu and args.num_machines is None: + args.num_machines = defaults.num_machines + + if len(args.gpu_ids.split(",")) < 2 and (args.gpu_ids != "all") and args.multi_gpu and args.num_machines <= 1: + raise ValueError( + "Less than two GPU ids were configured and tried to run on on multiple GPUs. " + "Please ensure at least two are specified for `--gpu_ids`, or use `--gpu_ids='all'`." + ) + if defaults.compute_environment == ComputeEnvironment.LOCAL_MACHINE: + # Update args with the defaults + for name, attr in defaults.__dict__.items(): + if isinstance(attr, dict): + for k in defaults.deepspeed_config: + setattr(args, k, defaults.deepspeed_config[k]) + for k in defaults.fsdp_config: + arg_to_set = k + if "fsdp" not in arg_to_set: + arg_to_set = "fsdp_" + arg_to_set + setattr(args, arg_to_set, defaults.fsdp_config[k]) + for k in defaults.megatron_lm_config: + setattr(args, k, defaults.megatron_lm_config[k]) + for k in defaults.dynamo_config: + setattr(args, k, defaults.dynamo_config[k]) + for k in defaults.ipex_config: + setattr(args, k, defaults.ipex_config[k]) + for k in defaults.mpirun_config: + setattr(args, k, defaults.mpirun_config[k]) + continue + + # Those args are handled separately + if ( + name not in ["compute_environment", "mixed_precision", "distributed_type"] + and getattr(args, name, None) is None + ): + setattr(args, name, attr) + if not args.debug: + args.debug = defaults.debug + + if not args.mixed_precision: + if defaults.mixed_precision is None: + args.mixed_precision = "no" + else: + args.mixed_precision = defaults.mixed_precision + mp_from_config_flag = True + else: + if args.use_cpu or (args.use_xpu and torch.xpu.is_available()): + native_amp = is_torch_version(">=", "1.10") + else: + native_amp = is_bf16_available(True) + if ( + args.mixed_precision == "bf16" + and not native_amp + and not (args.tpu and is_torch_xla_available(check_is_tpu=True)) + ): + raise ValueError("bf16 mixed precision requires PyTorch >= 1.10 and a supported device.") + + # Silently set the default here + if args.dynamo_backend is None: + args.dynamo_backend = "no" + if args.num_processes == -1: + raise ValueError("You need to manually pass in `--num_processes` using this config yaml.") + else: + if args.num_processes is None: + if args.use_xpu and is_xpu_available(): + args.num_processes = torch.xpu.device_count() + elif is_mlu_available(): + args.num_processes = torch.mlu.device_count() + elif is_musa_available(): + args.num_processes = torch.musa.device_count() + elif is_npu_available(): + args.num_processes = torch.npu.device_count() + else: + args.num_processes = torch.cuda.device_count() + warned.append(f"\t`--num_processes` was set to a value of `{args.num_processes}`") + if args.debug is None: + args.debug = False + if ( + not args.multi_gpu + and args.num_processes > 1 + and ( + (args.use_xpu and is_xpu_available() and torch.xpu.device_count() > 1) + or (is_mlu_available() and torch.mlu.device_count() > 1) + or (is_musa_available() and torch.musa.device_count() > 1) + or (is_npu_available() and torch.npu.device_count() > 1) + or (torch.cuda.device_count() > 1) + ) + ): + warned.append( + "\t\tMore than one GPU was found, enabling multi-GPU training.\n" + "\t\tIf this was unintended please pass in `--num_processes=1`." + ) + args.multi_gpu = True + if args.num_machines is None: + warned.append("\t`--num_machines` was set to a value of `1`") + args.num_machines = 1 + if args.mixed_precision is None: + warned.append("\t`--mixed_precision` was set to a value of `'no'`") + args.mixed_precision = "no" + if not hasattr(args, "use_cpu"): + args.use_cpu = args.cpu + if args.dynamo_backend is None: + warned.append("\t`--dynamo_backend` was set to a value of `'no'`") + args.dynamo_backend = "no" + if args.debug: + logger.debug("Running script in debug mode, expect distributed operations to be slightly slower.") + + is_aws_env_disabled = defaults is None or ( + defaults is not None and defaults.compute_environment != ComputeEnvironment.AMAZON_SAGEMAKER + ) + if is_aws_env_disabled and args.num_cpu_threads_per_process is None: + args.num_cpu_threads_per_process = get_int_from_env(["OMP_NUM_THREADS"], 1) + if args.use_cpu and args.num_processes >= 1 and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0: + local_size = get_int_from_env( + ["MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"], + max(int(args.num_processes / args.num_machines), 1), + ) + threads_per_process = int(psutil.cpu_count(logical=False) / local_size) + if threads_per_process > 1: + args.num_cpu_threads_per_process = threads_per_process + warned.append( + f"\t`--num_cpu_threads_per_process` was set to `{args.num_cpu_threads_per_process}` to improve out-of-box performance when training on CPUs" + ) + + if any(warned): + message = "The following values were not passed to `accelerate launch` and had defaults used instead:\n" + message += "\n".join(warned) + message += ( + "\nTo avoid this warning pass in values for each of the problematic parameters or run `accelerate config`." + ) + logger.warning(message) + return args, defaults, mp_from_config_flag + + +def launch_command(args): + args, defaults, mp_from_config_flag = _validate_launch_command(args) + # Use the proper launcher + if args.use_deepspeed and not args.cpu: + args.deepspeed_fields_from_accelerate_config = list(defaults.deepspeed_config.keys()) if defaults else [] + if mp_from_config_flag: + args.deepspeed_fields_from_accelerate_config.append("mixed_precision") + args.deepspeed_fields_from_accelerate_config = ",".join(args.deepspeed_fields_from_accelerate_config) + deepspeed_launcher(args) + elif args.use_fsdp and not args.cpu: + multi_gpu_launcher(args) + elif args.use_megatron_lm and not args.cpu: + multi_gpu_launcher(args) + elif args.multi_gpu and not args.cpu: + multi_gpu_launcher(args) + elif args.tpu and not args.cpu: + if args.tpu_use_cluster: + tpu_pod_launcher(args) + else: + tpu_launcher(args) + elif defaults is not None and defaults.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER: + sagemaker_launcher(defaults, args) + else: + simple_launcher(args) + + +def main(): + parser = launch_command_parser() + args = parser.parse_args() + launch_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/__init__.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c2c851cc0b192ab8207d3fa68d7409868c84354c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/__init__.py @@ -0,0 +1,14 @@ +# 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. +from .selection_menu import BulletMenu diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/cursor.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/cursor.py new file mode 100644 index 0000000000000000000000000000000000000000..c1f0bb7b68025ae4fe0c2c76c095eb36b4e64f2c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/cursor.py @@ -0,0 +1,65 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. 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. + +""" +A utility for showing and hiding the terminal cursor on Windows and Linux, based on https://github.com/bchao1/bullet +""" + +import os +import sys +from contextlib import contextmanager + + +# Windows only +if os.name == "nt": + import ctypes + import msvcrt # noqa + + class CursorInfo(ctypes.Structure): + # _fields is a specific attr expected by ctypes + _fields_ = [("size", ctypes.c_int), ("visible", ctypes.c_byte)] + + +def hide_cursor(): + if os.name == "nt": + ci = CursorInfo() + handle = ctypes.windll.kernel32.GetStdHandle(-11) + ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci)) + ci.visible = False + ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci)) + elif os.name == "posix": + sys.stdout.write("\033[?25l") + sys.stdout.flush() + + +def show_cursor(): + if os.name == "nt": + ci = CursorInfo() + handle = ctypes.windll.kernel32.GetStdHandle(-11) + ctypes.windll.kernel32.GetConsoleCursorInfo(handle, ctypes.byref(ci)) + ci.visible = True + ctypes.windll.kernel32.SetConsoleCursorInfo(handle, ctypes.byref(ci)) + elif os.name == "posix": + sys.stdout.write("\033[?25h") + sys.stdout.flush() + + +@contextmanager +def hide(): + "Context manager to hide the terminal cursor" + try: + hide_cursor() + yield + finally: + show_cursor() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/helpers.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..de46f37ddcf4591167e3e01791391e4b1729034f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/helpers.py @@ -0,0 +1,59 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. 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. + +""" +A variety of helper functions and constants when dealing with terminal menu choices, based on +https://github.com/bchao1/bullet +""" + +import enum +import shutil +import sys + + +TERMINAL_WIDTH, _ = shutil.get_terminal_size() + +CURSOR_TO_CHAR = {"UP": "A", "DOWN": "B", "RIGHT": "C", "LEFT": "D"} + + +class Direction(enum.Enum): + UP = 0 + DOWN = 1 + + +def forceWrite(content, end=""): + sys.stdout.write(str(content) + end) + sys.stdout.flush() + + +def writeColor(content, color, end=""): + forceWrite(f"\u001b[{color}m{content}\u001b[0m", end) + + +def reset_cursor(): + forceWrite("\r") + + +def move_cursor(num_lines: int, direction: str): + forceWrite(f"\033[{num_lines}{CURSOR_TO_CHAR[direction.upper()]}") + + +def clear_line(): + forceWrite(" " * TERMINAL_WIDTH) + reset_cursor() + + +def linebreak(): + reset_cursor() + forceWrite("-" * TERMINAL_WIDTH) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/input.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/input.py new file mode 100644 index 0000000000000000000000000000000000000000..2690f86aa61f7ac648f4a9c2040a34ee35147201 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/input.py @@ -0,0 +1,86 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. 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 file contains utilities for handling input from the user and registering specific keys to specific functions, +based on https://github.com/bchao1/bullet +""" + +from typing import List + +from .keymap import KEYMAP, get_character + + +def mark(key: str): + """ + Mark the function with the key code so it can be handled in the register + """ + + def decorator(func): + handle = getattr(func, "handle_key", []) + handle += [key] + func.handle_key = handle + return func + + return decorator + + +def mark_multiple(*keys: List[str]): + """ + Mark the function with the key codes so it can be handled in the register + """ + + def decorator(func): + handle = getattr(func, "handle_key", []) + handle += keys + func.handle_key = handle + return func + + return decorator + + +class KeyHandler(type): + """ + Metaclass that adds the key handlers to the class + """ + + def __new__(cls, name, bases, attrs): + new_cls = super().__new__(cls, name, bases, attrs) + if not hasattr(new_cls, "key_handler"): + new_cls.key_handler = {} + new_cls.handle_input = KeyHandler.handle_input + + for value in attrs.values(): + handled_keys = getattr(value, "handle_key", []) + for key in handled_keys: + new_cls.key_handler[key] = value + return new_cls + + @staticmethod + def handle_input(cls): + "Finds and returns the selected character if it exists in the handler" + char = get_character() + if char != KEYMAP["undefined"]: + char = ord(char) + handler = cls.key_handler.get(char) + if handler: + cls.current_selection = char + return handler(cls) + else: + return None + + +def register(cls): + """Adds KeyHandler metaclass to the class""" + return KeyHandler(cls.__name__, cls.__bases__, cls.__dict__.copy()) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/keymap.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/keymap.py new file mode 100644 index 0000000000000000000000000000000000000000..787db12860fe21c6786dda69c34fcccab114f2f8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/keymap.py @@ -0,0 +1,133 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. 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. + +""" +Utilities relating to parsing raw characters from the keyboard, based on https://github.com/bchao1/bullet +""" + +import os +import string +import sys + + +ARROW_KEY_FLAG = 1 << 8 + +KEYMAP = { + "tab": ord("\t"), + "newline": ord("\r"), + "esc": 27, + "up": 65 + ARROW_KEY_FLAG, + "down": 66 + ARROW_KEY_FLAG, + "right": 67 + ARROW_KEY_FLAG, + "left": 68 + ARROW_KEY_FLAG, + "mod_int": 91, + "undefined": sys.maxsize, + "interrupt": 3, + "insert": 50, + "delete": 51, + "pg_up": 53, + "pg_down": 54, +} + +KEYMAP["arrow_begin"] = KEYMAP["up"] +KEYMAP["arrow_end"] = KEYMAP["left"] + +if sys.platform == "win32": + WIN_CH_BUFFER = [] + WIN_KEYMAP = { + b"\xe0H": KEYMAP["up"] - ARROW_KEY_FLAG, + b"\x00H": KEYMAP["up"] - ARROW_KEY_FLAG, + b"\xe0P": KEYMAP["down"] - ARROW_KEY_FLAG, + b"\x00P": KEYMAP["down"] - ARROW_KEY_FLAG, + b"\xe0M": KEYMAP["right"] - ARROW_KEY_FLAG, + b"\x00M": KEYMAP["right"] - ARROW_KEY_FLAG, + b"\xe0K": KEYMAP["left"] - ARROW_KEY_FLAG, + b"\x00K": KEYMAP["left"] - ARROW_KEY_FLAG, + } + +for i in range(10): + KEYMAP[str(i)] = ord(str(i)) + + +def get_raw_chars(): + "Gets raw characters from inputs" + if os.name == "nt": + import msvcrt + + encoding = "mbcs" + # Flush the keyboard buffer + while msvcrt.kbhit(): + msvcrt.getch() + if len(WIN_CH_BUFFER) == 0: + # Read the keystroke + ch = msvcrt.getch() + + # If it is a prefix char, get second part + if ch in (b"\x00", b"\xe0"): + ch2 = ch + msvcrt.getch() + # Translate actual Win chars to bullet char types + try: + chx = chr(WIN_KEYMAP[ch2]) + WIN_CH_BUFFER.append(chr(KEYMAP["mod_int"])) + WIN_CH_BUFFER.append(chx) + if ord(chx) in ( + KEYMAP["insert"] - 1 << 9, + KEYMAP["delete"] - 1 << 9, + KEYMAP["pg_up"] - 1 << 9, + KEYMAP["pg_down"] - 1 << 9, + ): + WIN_CH_BUFFER.append(chr(126)) + ch = chr(KEYMAP["esc"]) + except KeyError: + ch = ch2[1] + else: + ch = ch.decode(encoding) + else: + ch = WIN_CH_BUFFER.pop(0) + elif os.name == "posix": + import termios + import tty + + fd = sys.stdin.fileno() + old_settings = termios.tcgetattr(fd) + try: + tty.setraw(fd) + ch = sys.stdin.read(1) + finally: + termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) + return ch + + +def get_character(): + "Gets a character from the keyboard and returns the key code" + char = get_raw_chars() + if ord(char) in [KEYMAP["interrupt"], KEYMAP["newline"]]: + return char + + elif ord(char) == KEYMAP["esc"]: + combo = get_raw_chars() + if ord(combo) == KEYMAP["mod_int"]: + key = get_raw_chars() + if ord(key) >= KEYMAP["arrow_begin"] - ARROW_KEY_FLAG and ord(key) <= KEYMAP["arrow_end"] - ARROW_KEY_FLAG: + return chr(ord(key) + ARROW_KEY_FLAG) + else: + return KEYMAP["undefined"] + else: + return get_raw_chars() + + else: + if char in string.printable: + return char + else: + return KEYMAP["undefined"] diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/selection_menu.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/selection_menu.py new file mode 100644 index 0000000000000000000000000000000000000000..ee9a771a54ef666ee46b67ae6c75fb957d49efdd --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/menu/selection_menu.py @@ -0,0 +1,144 @@ +# Copyright 2022 The HuggingFace Team and Brian Chao. 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. + +""" +Main driver for the selection menu, based on https://github.com/bchao1/bullet +""" + +import builtins +import sys + +from ...utils.imports import _is_package_available +from . import cursor, input +from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor +from .keymap import KEYMAP + + +in_colab = False +try: + in_colab = _is_package_available("google.colab") +except ModuleNotFoundError: + pass + + +@input.register +class BulletMenu: + """ + A CLI menu to select a choice from a list of choices using the keyboard. + """ + + def __init__(self, prompt: str = None, choices: list = []): + self.position = 0 + self.choices = choices + self.prompt = prompt + if sys.platform == "win32": + self.arrow_char = "*" + else: + self.arrow_char = "➔ " + + def write_choice(self, index, end: str = ""): + if sys.platform != "win32": + writeColor(self.choices[index], 32, end) + else: + forceWrite(self.choices[index], end) + + def print_choice(self, index: int): + "Prints the choice at the given index" + if index == self.position: + forceWrite(f" {self.arrow_char} ") + self.write_choice(index) + else: + forceWrite(f" {self.choices[index]}") + reset_cursor() + + def move_direction(self, direction: Direction, num_spaces: int = 1): + "Should not be directly called, used to move a direction of either up or down" + old_position = self.position + if direction == Direction.DOWN: + if self.position + 1 >= len(self.choices): + return + self.position += num_spaces + else: + if self.position - 1 < 0: + return + self.position -= num_spaces + clear_line() + self.print_choice(old_position) + move_cursor(num_spaces, direction.name) + self.print_choice(self.position) + + @input.mark(KEYMAP["up"]) + def move_up(self): + self.move_direction(Direction.UP) + + @input.mark(KEYMAP["down"]) + def move_down(self): + self.move_direction(Direction.DOWN) + + @input.mark(KEYMAP["newline"]) + def select(self): + move_cursor(len(self.choices) - self.position, "DOWN") + return self.position + + @input.mark(KEYMAP["interrupt"]) + def interrupt(self): + move_cursor(len(self.choices) - self.position, "DOWN") + raise KeyboardInterrupt + + @input.mark_multiple(*[KEYMAP[str(number)] for number in range(10)]) + def select_row(self): + index = int(chr(self.current_selection)) + movement = index - self.position + if index == self.position: + return + if index < len(self.choices): + if self.position > index: + self.move_direction(Direction.UP, -movement) + elif self.position < index: + self.move_direction(Direction.DOWN, movement) + else: + return + else: + return + + def run(self, default_choice: int = 0): + "Start the menu and return the selected choice" + if self.prompt: + linebreak() + forceWrite(self.prompt, "\n") + if in_colab: + forceWrite("Please input a choice index (starting from 0), and press enter", "\n") + else: + forceWrite("Please select a choice using the arrow or number keys, and selecting with enter", "\n") + self.position = default_choice + for i in range(len(self.choices)): + self.print_choice(i) + forceWrite("\n") + move_cursor(len(self.choices) - self.position, "UP") + with cursor.hide(): + while True: + if in_colab: + try: + choice = int(builtins.input()) + except ValueError: + choice = default_choice + else: + choice = self.handle_input() + if choice is not None: + reset_cursor() + for _ in range(len(self.choices) + 1): + move_cursor(1, "UP") + clear_line() + self.write_choice(choice, "\n") + return choice diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/merge.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/merge.py new file mode 100644 index 0000000000000000000000000000000000000000..b5c538165e9adc22f7d71b4752f3d390729639b7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/merge.py @@ -0,0 +1,69 @@ +#!/usr/bin/env python + +# 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. +from accelerate.commands.utils import CustomArgumentParser +from accelerate.utils import merge_fsdp_weights + + +description = """Utility to merge the weights from multiple FSDP checkpoints into a single combined checkpoint. Should be used if +`SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}`. + +This is a CPU-bound process and requires enough RAM to load the entire model state dict.""" + + +def merge_command(args): + merge_fsdp_weights( + args.checkpoint_directory, args.output_path, not args.unsafe_serialization, args.remove_checkpoint_dir + ) + + +def merge_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("merge-weights", description=description) + else: + parser = CustomArgumentParser(description=description) + + parser.add_argument("checkpoint_directory", type=str, help="A directory containing sharded weights saved by FSDP.") + parser.add_argument( + "output_path", + type=str, + help="The path to save the merged weights. Defaults to the current directory. ", + ) + parser.add_argument( + "--unsafe_serialization", + action="store_false", + default=False, + help="Whether to save the merged weights as `.bin` rather than `.safetensors` (not recommended).", + ) + parser.add_argument( + "--remove_checkpoint_dir", + action="store_true", + help="Whether to remove the checkpoint directory after merging.", + default=False, + ) + + if subparsers is not None: + parser.set_defaults(func=merge_command) + return parser + + +def main(): + parser = merge_command_parser() + args = parser.parse_args() + merge_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/test.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/test.py new file mode 100644 index 0000000000000000000000000000000000000000..a0d2f7bcf14727aa13e3438f4cd6e6f140f5bb2f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/test.py @@ -0,0 +1,65 @@ +#!/usr/bin/env python + +# 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. + +import argparse + +from accelerate.test_utils import execute_subprocess_async, path_in_accelerate_package + + +def test_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("test") + else: + parser = argparse.ArgumentParser("Accelerate test command") + + parser.add_argument( + "--config_file", + default=None, + help=( + "The path to use to store the config file. Will default to a file named default_config.yaml in the cache " + "location, which is the content of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have " + "such an environment variable, your cache directory ('~/.cache' or the content of `XDG_CACHE_HOME`) suffixed " + "with 'huggingface'." + ), + ) + + if subparsers is not None: + parser.set_defaults(func=test_command) + return parser + + +def test_command(args): + script_name = path_in_accelerate_package("test_utils", "scripts", "test_script.py") + + if args.config_file is None: + test_args = [script_name] + else: + test_args = f"--config_file={args.config_file} {script_name}".split() + + cmd = ["accelerate-launch"] + test_args + result = execute_subprocess_async(cmd) + if result.returncode == 0: + print("Test is a success! You are ready for your distributed training!") + + +def main(): + parser = test_command_parser() + args = parser.parse_args() + test_command(args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/tpu.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/tpu.py new file mode 100644 index 0000000000000000000000000000000000000000..fc0f07bf8697bfdb6484d3bf817f2e18b1313b00 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/tpu.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python + +# 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. + +import argparse +import os +import subprocess + +from packaging.version import Version, parse + +from accelerate.commands.config.config_args import default_config_file, load_config_from_file + + +_description = "Run commands across TPU VMs for initial setup before running `accelerate launch`." + + +def tpu_command_parser(subparsers=None): + if subparsers is not None: + parser = subparsers.add_parser("tpu-config", description=_description) + else: + parser = argparse.ArgumentParser("Accelerate tpu-config command", description=_description) + # Core arguments + config_args = parser.add_argument_group( + "Config Arguments", "Arguments that can be configured through `accelerate config`." + ) + config_args.add_argument( + "--config_file", + type=str, + default=None, + help="Path to the config file to use for accelerate.", + ) + config_args.add_argument( + "--tpu_name", + default=None, + help="The name of the TPU to use. If not specified, will use the TPU specified in the config file.", + ) + config_args.add_argument( + "--tpu_zone", + default=None, + help="The zone of the TPU to use. If not specified, will use the zone specified in the config file.", + ) + pod_args = parser.add_argument_group("TPU Arguments", "Arguments for options ran inside the TPU.") + pod_args.add_argument( + "--use_alpha", + action="store_true", + help="Whether to use `gcloud alpha` when running the TPU training script instead of `gcloud`.", + ) + pod_args.add_argument( + "--command_file", + default=None, + help="The path to the file containing the commands to run on the pod on startup.", + ) + pod_args.add_argument( + "--command", + action="append", + nargs="+", + help="A command to run on the pod. Can be passed multiple times.", + ) + pod_args.add_argument( + "--install_accelerate", + action="store_true", + help="Whether to install accelerate on the pod. Defaults to False.", + ) + pod_args.add_argument( + "--accelerate_version", + default="latest", + help="The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub.", + ) + pod_args.add_argument( + "--debug", action="store_true", help="If set, will print the command that would be run instead of running it." + ) + + if subparsers is not None: + parser.set_defaults(func=tpu_command_launcher) + return parser + + +def tpu_command_launcher(args): + defaults = None + + # Get the default from the config file if it exists. + if args.config_file is not None or os.path.isfile(default_config_file): + defaults = load_config_from_file(args.config_file) + if not args.command_file and defaults.command_file is not None and not args.command: + args.command_file = defaults.command_file + if not args.command and defaults.commands is not None: + args.command = defaults.commands + if not args.tpu_name: + args.tpu_name = defaults.tpu_name + if not args.tpu_zone: + args.tpu_zone = defaults.tpu_zone + if args.accelerate_version == "dev": + args.accelerate_version = "git+https://github.com/huggingface/accelerate.git" + elif args.accelerate_version == "latest": + args.accelerate_version = "accelerate -U" + elif isinstance(parse(args.accelerate_version), Version): + args.accelerate_version = f"accelerate=={args.accelerate_version}" + + if not args.command_file and not args.command: + raise ValueError("You must specify either a command file or a command to run on the pod.") + + if args.command_file: + with open(args.command_file) as f: + args.command = [f.read().splitlines()] + + # To turn list of lists into list of strings + if isinstance(args.command[0], list): + args.command = [line for cmd in args.command for line in cmd] + # Default to the shared folder and install accelerate + new_cmd = ["cd /usr/share"] + if args.install_accelerate: + new_cmd += [f"pip install {args.accelerate_version}"] + new_cmd += args.command + args.command = "; ".join(new_cmd) + + # Then send it to gcloud + # Eventually try to use google-api-core to do this instead of subprocess + cmd = ["gcloud"] + if args.use_alpha: + cmd += ["alpha"] + cmd += [ + "compute", + "tpus", + "tpu-vm", + "ssh", + args.tpu_name, + "--zone", + args.tpu_zone, + "--command", + args.command, + "--worker", + "all", + ] + if args.debug: + print(f"Running {' '.join(cmd)}") + return + subprocess.run(cmd) + print("Successfully setup pod.") + + +def main(): + parser = tpu_command_parser() + args = parser.parse_args() + + tpu_command_launcher(args) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/utils.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b65215fac7666b475af98b17e264ef6701239bc1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/commands/utils.py @@ -0,0 +1,120 @@ +# 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. + +import argparse + + +class _StoreAction(argparse.Action): + """ + Custom action that allows for `-` or `_` to be passed in for an argument. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + new_option_strings = [] + for option_string in self.option_strings: + new_option_strings.append(option_string) + if "_" in option_string[2:]: + # Add `-` version to the option string + new_option_strings.append(option_string.replace("_", "-")) + self.option_strings = new_option_strings + + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, self.dest, values) + + +class _StoreConstAction(_StoreAction): + """ + Same as `argparse._StoreConstAction` but uses the custom `_StoreAction`. + """ + + def __init__(self, option_strings, dest, const, default=None, required=False, help=None): + super().__init__( + option_strings=option_strings, + dest=dest, + nargs=0, + const=const, + default=default, + required=required, + help=help, + ) + + def __call__(self, parser, namespace, values, option_string=None): + setattr(namespace, self.dest, self.const) + + +class _StoreTrueAction(_StoreConstAction): + """ + Same as `argparse._StoreTrueAction` but uses the custom `_StoreConstAction`. + """ + + def __init__( + self, + option_strings, + dest, + default=None, + required=False, + help=None, + ): + super().__init__( + option_strings=option_strings, dest=dest, const=True, default=default, required=required, help=help + ) + + +class CustomArgumentGroup(argparse._ArgumentGroup): + """ + Custom argument group that allows for the use of `-` or `_` in arguments passed and overrides the help for each + when applicable. + """ + + def _add_action(self, action): + args = vars(action) + if isinstance(action, argparse._StoreTrueAction): + action = _StoreTrueAction( + args["option_strings"], args["dest"], args["default"], args["required"], args["help"] + ) + elif isinstance(action, argparse._StoreConstAction): + action = _StoreConstAction( + args["option_strings"], + args["dest"], + args["const"], + args["default"], + args["required"], + args["help"], + ) + elif isinstance(action, argparse._StoreAction): + action = _StoreAction(**args) + action = super()._add_action(action) + return action + + +class CustomArgumentParser(argparse.ArgumentParser): + """ + Custom argument parser that allows for the use of `-` or `_` in arguments passed and overrides the help for each + when applicable. + """ + + def add_argument(self, *args, **kwargs): + if "action" in kwargs: + # Translate action -> class + if kwargs["action"] == "store_true": + kwargs["action"] = _StoreTrueAction + else: + kwargs["action"] = _StoreAction + super().add_argument(*args, **kwargs) + + def add_argument_group(self, *args, **kwargs): + group = CustomArgumentGroup(self, *args, **kwargs) + self._action_groups.append(group) + return group diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/data_loader.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/data_loader.py new file mode 100644 index 0000000000000000000000000000000000000000..d9b2e0e8980b72bb9323ed0d81f07294a5f273bd --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/data_loader.py @@ -0,0 +1,1291 @@ +# 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. + +import math +from contextlib import suppress +from typing import Callable, List, Optional, Union + +import torch +from torch.utils.data import BatchSampler, DataLoader, IterableDataset, RandomSampler + +from .logging import get_logger +from .state import DistributedType, GradientState, PartialState, is_torch_xla_available +from .utils import ( + RNGType, + broadcast, + broadcast_object_list, + concatenate, + find_batch_size, + get_data_structure, + initialize_tensors, + is_torch_version, + is_torchdata_stateful_dataloader_available, + send_to_device, + slice_tensors, + synchronize_rng_states, +) + + +logger = get_logger(__name__) + +# kwargs of the DataLoader in min version 1.4.0. +_PYTORCH_DATALOADER_KWARGS = { + "batch_size": 1, + "shuffle": False, + "sampler": None, + "batch_sampler": None, + "num_workers": 0, + "collate_fn": None, + "pin_memory": False, + "drop_last": False, + "timeout": 0, + "worker_init_fn": None, + "multiprocessing_context": None, + "generator": None, + "prefetch_factor": 2, + "persistent_workers": False, +} + +# kwargs added after by version +_PYTORCH_DATALOADER_ADDITIONAL_KWARGS = {} + +for v, additional_kwargs in _PYTORCH_DATALOADER_ADDITIONAL_KWARGS.items(): + if is_torch_version(">=", v): + _PYTORCH_DATALOADER_KWARGS.update(additional_kwargs) + + +class SeedableRandomSampler(RandomSampler): + """ + Same as a random sampler, except that in `__iter__` a seed can be used. + + Needed specifically in distributed cases, when the random generator for each GPU needs to start from the same seed + and be fully reproducable on multiple iterations. + + If a custom `generator` is passed, it will rely on its initial seed as well as the current iteration it is on + (stored in `self.epoch`). + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.epoch = 0 + self.initial_seed = torch.random.initial_seed() + + def __iter__(self): + if self.generator is None: + self.generator = torch.Generator() + self.generator.manual_seed(self.initial_seed) + + # Allow `self.epoch` to modify the seed of the generator + seed = self.epoch + self.initial_seed + # print("Setting seed at epoch", self.epoch, seed) + self.generator.manual_seed(seed) + yield from super().__iter__() + self.set_epoch(self.epoch + 1) + + def set_epoch(self, epoch: int): + "Sets the current iteration of the sampler." + self.epoch = epoch + + +class BatchSamplerShard(BatchSampler): + """ + Wraps a PyTorch `BatchSampler` to generate batches for one of the processes only. Instances of this class will + always yield a number of batches that is a round multiple of `num_processes` and that all have the same size. + Depending on the value of the `drop_last` attribute of the batch sampler passed, it will either stop the iteration + at the first batch that would be too small / not present on all processes or loop with indices from the beginning. + + Args: + batch_sampler (`torch.utils.data.sampler.BatchSampler`): + The batch sampler to split in several shards. + num_processes (`int`, *optional*, defaults to 1): + The number of processes running concurrently. + process_index (`int`, *optional*, defaults to 0): + The index of the current process. + split_batches (`bool`, *optional*, defaults to `False`): + Whether the shards should be created by splitting a batch to give a piece of it on each process, or by + yielding different full batches on each process. + + On two processes with a sampler of `[[0, 1, 2, 3], [4, 5, 6, 7]]`, this will result in: + + - the sampler on process 0 to yield `[0, 1, 2, 3]` and the sampler on process 1 to yield `[4, 5, 6, 7]` if + this argument is set to `False`. + - the sampler on process 0 to yield `[0, 1]` then `[4, 5]` and the sampler on process 1 to yield `[2, 3]` + then `[6, 7]` if this argument is set to `True`. + even_batches (`bool`, *optional*, defaults to `True`): + Whether or not to loop back at the beginning of the sampler when the number of samples is not a round + multiple of (original batch size / number of processes). + + + + `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches` + equal to `False` + + """ + + def __init__( + self, + batch_sampler: BatchSampler, + num_processes: int = 1, + process_index: int = 0, + split_batches: bool = False, + even_batches: bool = True, + ): + if split_batches and batch_sampler.batch_size % num_processes != 0: + raise ValueError( + f"To use `BatchSamplerShard` in `split_batches` mode, the batch size ({batch_sampler.batch_size}) " + f"needs to be a round multiple of the number of processes ({num_processes})." + ) + self.batch_sampler = batch_sampler + self.num_processes = num_processes + self.process_index = process_index + self.split_batches = split_batches + self.even_batches = even_batches + self.batch_size = getattr(batch_sampler, "batch_size", None) + self.drop_last = getattr(batch_sampler, "drop_last", False) + if self.batch_size is None and self.even_batches: + raise ValueError( + "You need to use `even_batches=False` when the batch sampler has no batch size. If you " + "are not calling this method directly, set `accelerator.even_batches=False` instead." + ) + + @property + def total_length(self): + return len(self.batch_sampler) + + def __len__(self): + if self.split_batches: + # Split batches does not change the length of the batch sampler + return len(self.batch_sampler) + if len(self.batch_sampler) % self.num_processes == 0: + # If the length is a round multiple of the number of processes, it's easy. + return len(self.batch_sampler) // self.num_processes + length = len(self.batch_sampler) // self.num_processes + if self.drop_last: + # Same if we drop the remainder. + return length + elif self.even_batches: + # When we even batches we always get +1 + return length + 1 + else: + # Otherwise it depends on the process index. + return length + 1 if self.process_index < len(self.batch_sampler) % self.num_processes else length + + def __iter__(self): + return self._iter_with_split() if self.split_batches else self._iter_with_no_split() + + def _iter_with_split(self): + initial_data = [] + batch_length = self.batch_sampler.batch_size // self.num_processes + for idx, batch in enumerate(self.batch_sampler): + if idx == 0: + initial_data = batch + if len(batch) == self.batch_size: + # If the batch is full, we yield the part of it this process is responsible of. + yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)] + + # If drop_last is True of the last batch was full, iteration is over, otherwise... + if not self.drop_last and len(initial_data) > 0 and len(batch) < self.batch_size: + if not self.even_batches: + if len(batch) > batch_length * self.process_index: + yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)] + else: + # For degenerate cases where the dataset has less than num_process * batch_size samples + while len(initial_data) < self.batch_size: + initial_data += initial_data + batch = batch + initial_data + yield batch[batch_length * self.process_index : batch_length * (self.process_index + 1)] + + def _iter_with_no_split(self): + initial_data = [] + batch_to_yield = [] + for idx, batch in enumerate(self.batch_sampler): + # We gather the initial indices in case we need to circle back at the end. + if not self.drop_last and idx < self.num_processes: + initial_data += batch + # We identify the batch to yield but wait until we ar sure every process gets a full batch before actually + # yielding it. + if idx % self.num_processes == self.process_index: + batch_to_yield = batch + if idx % self.num_processes == self.num_processes - 1 and ( + self.batch_size is None or len(batch) == self.batch_size + ): + yield batch_to_yield + batch_to_yield = [] + + # If drop_last is True, iteration is over, otherwise... + if not self.drop_last and len(initial_data) > 0: + if not self.even_batches: + if len(batch_to_yield) > 0: + yield batch_to_yield + else: + # ... we yield the complete batch we had saved before if it has the proper length + if len(batch_to_yield) == self.batch_size: + yield batch_to_yield + + # For degenerate cases where the dataset has less than num_process * batch_size samples + while len(initial_data) < self.num_processes * self.batch_size: + initial_data += initial_data + + # If the last batch seen was of the proper size, it has been yielded by its process so we move to the next + if len(batch) == self.batch_size: + batch = [] + idx += 1 + + # Make sure we yield a multiple of self.num_processes batches + cycle_index = 0 + while idx % self.num_processes != 0 or len(batch) > 0: + end_index = cycle_index + self.batch_size - len(batch) + batch += initial_data[cycle_index:end_index] + if idx % self.num_processes == self.process_index: + yield batch + cycle_index = end_index + batch = [] + idx += 1 + + +class IterableDatasetShard(IterableDataset): + """ + Wraps a PyTorch `IterableDataset` to generate samples for one of the processes only. Instances of this class will + always yield a number of samples that is a round multiple of the actual batch size (depending of the value of + `split_batches`, this is either `batch_size` or `batch_size x num_processes`). Depending on the value of the + `drop_last` attribute of the batch sampler passed, it will either stop the iteration at the first batch that would + be too small or loop with indices from the beginning. + + Args: + dataset (`torch.utils.data.dataset.IterableDataset`): + The batch sampler to split in several shards. + batch_size (`int`, *optional*, defaults to 1): + The size of the batches per shard (if `split_batches=False`) or the size of the batches (if + `split_batches=True`). + drop_last (`bool`, *optional*, defaults to `False`): + Whether or not to drop the last incomplete batch or complete the last batches by using the samples from the + beginning. + num_processes (`int`, *optional*, defaults to 1): + The number of processes running concurrently. + process_index (`int`, *optional*, defaults to 0): + The index of the current process. + split_batches (`bool`, *optional*, defaults to `False`): + Whether the shards should be created by splitting a batch to give a piece of it on each process, or by + yielding different full batches on each process. + + On two processes with an iterable dataset yielding of `[0, 1, 2, 3, 4, 5, 6, 7]`, this will result in: + + - the shard on process 0 to yield `[0, 1, 2, 3]` and the shard on process 1 to yield `[4, 5, 6, 7]` if this + argument is set to `False`. + - the shard on process 0 to yield `[0, 1, 4, 5]` and the sampler on process 1 to yield `[2, 3, 6, 7]` if + this argument is set to `True`. + """ + + def __init__( + self, + dataset: IterableDataset, + batch_size: int = 1, + drop_last: bool = False, + num_processes: int = 1, + process_index: int = 0, + split_batches: bool = False, + ): + if split_batches and batch_size > 1 and batch_size % num_processes != 0: + raise ValueError( + f"To use `IterableDatasetShard` in `split_batches` mode, the batch size ({batch_size}) " + f"needs to be a round multiple of the number of processes ({num_processes})." + ) + self.dataset = dataset + self.batch_size = batch_size + self.drop_last = drop_last + self.num_processes = num_processes + self.process_index = process_index + self.split_batches = split_batches + + def set_epoch(self, epoch): + self.epoch = epoch + if hasattr(self.dataset, "set_epoch"): + self.dataset.set_epoch(epoch) + + def __len__(self): + # We will just raise the downstream error if the underlying dataset is not sized + if self.drop_last: + return (len(self.dataset) // (self.batch_size * self.num_processes)) * self.batch_size + else: + return math.ceil(len(self.dataset) / (self.batch_size * self.num_processes)) * self.batch_size + + def __iter__(self): + if ( + not hasattr(self.dataset, "set_epoch") + and hasattr(self.dataset, "generator") + and isinstance(self.dataset.generator, torch.Generator) + ): + self.dataset.generator.manual_seed(self.epoch) + real_batch_size = self.batch_size if self.split_batches else (self.batch_size * self.num_processes) + process_batch_size = (self.batch_size // self.num_processes) if self.split_batches else self.batch_size + process_slice = range(self.process_index * process_batch_size, (self.process_index + 1) * process_batch_size) + + first_batch = None + current_batch = [] + for element in self.dataset: + current_batch.append(element) + # Wait to have a full batch before yielding elements. + if len(current_batch) == real_batch_size: + for i in process_slice: + yield current_batch[i] + if first_batch is None: + first_batch = current_batch.copy() + current_batch = [] + + # Finished if drop_last is True, otherwise complete the last batch with elements from the beginning. + if not self.drop_last and len(current_batch) > 0: + if first_batch is None: + first_batch = current_batch.copy() + while len(current_batch) < real_batch_size: + current_batch += first_batch + for i in process_slice: + yield current_batch[i] + + +class DataLoaderStateMixin: + """ + Mixin class that adds a state to a `DataLoader` to keep track of the status inside the dataloader such as at the + end of the iteration, the number of items in the dataset in the last batch relative to the batch size, and other + useful information that might be needed. + + **Available attributes:** + + - **end_of_dataloader** (`bool`) -- Whether at the last iteration or batch + - **remainder** (`int`) -- The number of items that are remaining in the last batch, relative to the total + batch size + + + + Inheriters of this class should ensure that the class creates a `GradientState()` instance, stored in + `self.gradient_state`. + + + + """ + + def __init_subclass__(cls, **kwargs): + cls.end_of_dataloader = False + cls.remainder = -1 + + def reset(self): + self.end_of_dataloader = False + self.remainder = -1 + + def begin(self): + "Prepares the gradient state for the current dataloader" + self.reset() + with suppress(Exception): + if not self._drop_last: + length = getattr(self.dataset, "total_dataset_length", len(self.dataset)) + self.remainder = length % self.total_batch_size + self.gradient_state._add_dataloader(self) + + def end(self): + "Cleans up the gradient state after exiting the dataloader" + self.gradient_state._remove_dataloader(self) + + +class DataLoaderAdapter: + """ + A class which wraps around a PyTorch `DataLoader` (or variants of it) to be used with the `Accelerator`. For + compatability reasons, this class inherits from the class it wraps around, so it can be used as a drop-in. + """ + + def __init__(self, dataset, use_stateful_dataloader=False, batch_sampler=None, **kwargs): + self.use_stateful_dataloader = use_stateful_dataloader + if is_torchdata_stateful_dataloader_available(): + from torchdata.stateful_dataloader import StatefulDataLoader + + if use_stateful_dataloader and not is_torchdata_stateful_dataloader_available(): + raise ImportError( + "StatefulDataLoader is not available. Please install torchdata version 0.8.0 or higher to use it." + ) + if use_stateful_dataloader: + self.base_dataloader = StatefulDataLoader(dataset, batch_sampler=batch_sampler, **kwargs) + else: + self.base_dataloader = DataLoader(dataset, batch_sampler=batch_sampler, **kwargs) + + # Dynamically mixin the parent class. See https://stackoverflow.com/a/31075641 + # In C++ terms, this is analogous to creating `DataLoaderAdapter : T`, where T is a DataLoader or + # StatefulDataLoader + # + # The same functionality could be achieved by directly creating the required subclasses for both {DataLoader, + # StatefulDataLoader}, however that could lead to much messier code, with duplicated classes and conditional + # dispatching scattered throughout various functions and files. + # + # This code is incredibly awkward but it's the only way to make `isinstance(obj, StatefulDataLoader)` work + # transparently. + # + # A more robust solution is for DataLoaderAdapter to not inherit from DataLoader (compose rather than inherit), + # but this would not be backwards compatible with existing code which assumes + # DataLoaderShard/DataLoaderDispatcher are DataLoaders. + base_cls = self.__class__ + base_cls_name = self.__class__.__name__ + parent_cls_name = self.base_dataloader.__class__ + self.__class__ = type(base_cls_name, (base_cls, parent_cls_name), {}) + + if hasattr(self.base_dataloader, "state_dict"): + self.dl_state_dict = self.base_dataloader.state_dict() + + def __getattr__(self, name): + # Avoid infinite recursion if we try to access a nonexistent base_dataloader attribute. + if name == "base_dataloader": + raise AttributeError() + # Delegate attribute access to the internal dataloader + return getattr(self.base_dataloader, name) + + def state_dict(self): + return self.dl_state_dict + + def load_state_dict(self, state_dict): + self.base_dataloader.load_state_dict(state_dict) + + def adjust_state_dict_for_prefetch(self): + """ + Adjusts the state dict for prefetching. Natively, this will adjust all of the iters yielded keys in + `self.dl_state_dict` by a factor of `num_processes - 1`, however if a custom correction is needed, this can be + overridden. + + This should modify `self.dl_state_dict` directly + """ + # The state dict will be off by a factor of `n-1` batch too many during DDP, + # so we need to adjust it here + if PartialState().distributed_type != DistributedType.NO: + factor = PartialState().num_processes - 1 + if self.dl_state_dict["_sampler_iter_yielded"] > 0: + self.dl_state_dict["_sampler_iter_yielded"] -= factor + if self.dl_state_dict["_num_yielded"] > 0: + self.dl_state_dict["_num_yielded"] -= factor + if self.dl_state_dict["_index_sampler_state"] is not None: + if ( + "samples_yielded" in self.dl_state_dict["_index_sampler_state"] + and self.dl_state_dict["_index_sampler_state"]["samples_yielded"] > 0 + ): + self.dl_state_dict["_index_sampler_state"]["samples_yielded"] -= self.batch_size * factor + + def _update_state_dict(self): + # The state_dict of the underlying base_dataloader may be ahead of what is currently being yielded. + # E.g. the implementation of DataLoaderShard involves having an underlying iterator 1 element ahead of + # what it wants to yield. + # + # _update_state_dict is called to snapshot the state_dict that would properly recover the DataLoaderAdapter. + if hasattr(self.base_dataloader, "state_dict"): + self.dl_state_dict = self.base_dataloader.state_dict() + # Potentially modify the state_dict to adjust for prefetching + self.adjust_state_dict_for_prefetch() + # Then tag if we are at the end of the dataloader + self.dl_state_dict["_iterator_finished"] = self.end_of_dataloader + + +class DataLoaderShard(DataLoaderAdapter, DataLoaderStateMixin): + """ + Subclass of `DataLoaderAdapter` that will deal with device placement and current distributed setup. + + Args: + dataset (`torch.utils.data.dataset.Dataset`): + The dataset to use to build this datalaoder. + device (`torch.device`, *optional*): + If passed, the device to put all batches on. + rng_types (list of `str` or [`~utils.RNGType`]): + The list of random number generators to synchronize at the beginning of each iteration. Should be one or + several of: + + - `"torch"`: the base torch random number generator + - `"cuda"`: the CUDA random number generator (GPU only) + - `"xla"`: the XLA random number generator (TPU only) + - `"generator"`: an optional `torch.Generator` + synchronized_generator (`torch.Generator`, *optional*): + A random number generator to keep synchronized across processes. + skip_batches (`int`, *optional*, defaults to 0): + The number of batches to skip at the beginning. + use_stateful_dataloader (`bool`, *optional*, defaults to `False`): + Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`. + **kwargs (additional keyword arguments, *optional*): + All other keyword arguments to pass to the regular `DataLoader` initialization. + + **Available attributes:** + + - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes. + Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total + number of processes + + - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes. + """ + + def __init__( + self, + dataset, + device=None, + rng_types=None, + synchronized_generator=None, + skip_batches=0, + use_stateful_dataloader=False, + _drop_last: bool = False, + _non_blocking: bool = False, + **kwargs, + ): + super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs) + self.device = device + self.rng_types = rng_types + self.synchronized_generator = synchronized_generator + self.skip_batches = skip_batches + self.gradient_state = GradientState() + self._drop_last = _drop_last + self._non_blocking = _non_blocking + self.iteration = 0 + + def __iter__(self): + if self.rng_types is not None: + synchronize_rng_states(self.rng_types, self.synchronized_generator) + self.begin() + + self.set_epoch(self.iteration) + dataloader_iter = self.base_dataloader.__iter__() + # We iterate one batch ahead to check when we are at the end + try: + current_batch = next(dataloader_iter) + except StopIteration: + yield + + batch_index = 0 + while True: + try: + # But we still move it to the device so it is done before `StopIteration` is reached + if self.device is not None: + current_batch = send_to_device(current_batch, self.device, non_blocking=self._non_blocking) + self._update_state_dict() + next_batch = next(dataloader_iter) + if batch_index >= self.skip_batches: + yield current_batch + batch_index += 1 + current_batch = next_batch + except StopIteration: + self.end_of_dataloader = True + self._update_state_dict() + if batch_index >= self.skip_batches: + yield current_batch + break + + self.iteration += 1 + self.end() + + def set_epoch(self, epoch: int): + # In case it is manually passed in, the user can set it to what they like + if self.iteration != epoch: + self.iteration = epoch + if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"): + self.batch_sampler.sampler.set_epoch(epoch) + # We support if a custom `Dataset` implementation has `set_epoch` + # or in general HF datasets `Datasets` + elif hasattr(self.dataset, "set_epoch"): + self.dataset.set_epoch(epoch) + + @property + def total_batch_size(self): + batch_sampler = self.sampler if isinstance(self.sampler, BatchSampler) else self.batch_sampler + return ( + batch_sampler.batch_size + if getattr(batch_sampler, "split_batches", False) + else (batch_sampler.batch_size * getattr(batch_sampler, "num_processes", 1)) + ) + + @property + def total_dataset_length(self): + if hasattr(self.dataset, "total_length"): + return self.dataset.total_length + else: + return len(self.dataset) + + def get_sampler(self): + return get_sampler(self) + + def set_sampler(self, sampler): + sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler) + if sampler_is_batch_sampler: + self.sampler.sampler = sampler + else: + self.batch_sampler.sampler = sampler + if hasattr(self.batch_sampler, "batch_sampler"): + self.batch_sampler.batch_sampler.sampler = sampler + + +if is_torch_xla_available(): + import torch_xla.distributed.parallel_loader as xpl + + class MpDeviceLoaderWrapper(xpl.MpDeviceLoader): + """ + Wrapper for the xpl.MpDeviceLoader class that knows the total batch size. + + XLA preloading threads will all call DataLoaderShard's __iter__(). Remove rng_types from DataLoaderShard to + prevent it from using the XLA device in the preloading threads, and synchronize the RNG once from the main + thread only. + + **Available attributes:** + + - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes. + Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total + number of processes + + - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes. + """ + + def __init__(self, dataloader: DataLoaderShard, device: torch.device): + super().__init__(dataloader, device) + self._rng_types = self._loader.rng_types + self._loader.rng_types = None + self.device = device + + def __iter__(self): + if self._rng_types is not None: + synchronize_rng_states(self._rng_types, self._loader.synchronized_generator) + + return super().__iter__() + + def set_epoch(self, epoch: int): + if hasattr(self.dataloader, "set_epoch"): + self.dataloader.set_epoch(epoch) + + @property + def total_batch_size(self): + return self._loader.total_batch_size + + @property + def total_dataset_length(self): + return self._loader.total_dataset_length + + @property + def batch_sampler(self): + return self._loader.batch_sampler + + @property + def dataloader(self): + return self._loader + + +class DataLoaderDispatcher(DataLoaderAdapter, DataLoaderStateMixin): + """ + Subclass of `DataLoaderAdapter` that will iterate and preprocess on process 0 only, then dispatch on each process + their part of the batch. + + Args: + split_batches (`bool`, *optional*, defaults to `False`): + Whether the resulting `DataLoader` should split the batches of the original data loader across devices or + yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of + `num_processes` batches at each iteration). Another way to see this is that the observed batch size will be + the same as the initial `dataloader` if this option is set to `True`, the batch size of the initial + `dataloader` multiplied by `num_processes` otherwise. Setting this option to `True` requires that the batch + size of the `dataloader` is a round multiple of `batch_size`. + skip_batches (`int`, *optional*, defaults to 0): + The number of batches to skip at the beginning of an iteration. + use_stateful_dataloader (`bool`, *optional*, defaults to `False`): + Whether to have this class adapt `StatefulDataLoader` from `torchdata` instead of the regular `DataLoader`. + + **Available attributes:** + + - **total_batch_size** (`int`) -- Total batch size of the dataloader across all processes. + Equal to the original batch size when `split_batches=True`; otherwise the original batch size * the total + number of processes + + - **total_dataset_length** (`int`) -- Total length of the inner dataset across all processes. + """ + + def __init__( + self, + dataset, + split_batches: bool = False, + skip_batches=0, + use_stateful_dataloader=False, + _drop_last: bool = False, + _non_blocking: bool = False, + slice_fn=None, + **kwargs, + ): + shuffle = False + if is_torch_version(">=", "1.11.0"): + from torch.utils.data.datapipes.iter.combinatorics import ShufflerIterDataPipe + + # We need to save the shuffling state of the DataPipe + if isinstance(dataset, ShufflerIterDataPipe): + shuffle = dataset._shuffle_enabled + super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs) + self.split_batches = split_batches + if shuffle: + torch.utils.data.graph_settings.apply_shuffle_settings(dataset, shuffle=shuffle) + + self.gradient_state = GradientState() + self.state = PartialState() + self._drop_last = _drop_last + self._non_blocking = _non_blocking + self.skip_batches = skip_batches + + self.slice_fn = slice_tensors if slice_fn is None else slice_fn + self.iteration = 0 + + def _fetch_batches(self, iterator): + batches, batch = None, None + # On process 0, we gather the batch to dispatch. + if self.state.process_index == 0: + try: + if self.split_batches: + # One batch of the main iterator is dispatched and split. + self._update_state_dict() + batch = next(iterator) + else: + # num_processes batches of the main iterator are concatenated then dispatched and split. + # We add the batches one by one so we have the remainder available when drop_last=False. + batches = [] + for _ in range(self.state.num_processes): + self._update_state_dict() + batches.append(next(iterator)) + try: + batch = concatenate(batches, dim=0) + except RuntimeError as e: + raise RuntimeError( + "You can't use batches of different size with `dispatch_batches=True` or when using an `IterableDataset`." + "either pass `dispatch_batches=False` and have each process fetch its own batch " + " or pass `split_batches=True`. By doing so, the main process will fetch a full batch and " + "slice it into `num_processes` batches for each process." + ) from e + # In both cases, we need to get the structure of the batch that we will broadcast on other + # processes to initialize the tensors with the right shape. + # data_structure, stop_iteration + batch_info = [get_data_structure(batch), False] + except StopIteration: + batch_info = [None, True] + else: + batch_info = [None, self._stop_iteration] + # This is inplace, so after this instruction, every process has the same `batch_info` as process 0. + broadcast_object_list(batch_info) + self._stop_iteration = batch_info[1] + if self._stop_iteration: + # If drop_last is False and split_batches is False, we may have a remainder to take care of. + if not self.split_batches and not self._drop_last: + if self.state.process_index == 0 and len(batches) > 0: + batch = concatenate(batches, dim=0) + batch_info = [get_data_structure(batch), False] + else: + batch_info = [None, True] + broadcast_object_list(batch_info) + return batch, batch_info + + def __iter__(self): + self.begin() + self.set_epoch(self.iteration) + main_iterator = None + if is_torch_version(">=", "2.0.1"): + # NOTE PyTorch DataLoader adds forward compatibilities for DataPipes, which broadcasts + # shared seed to all dist processes. Thus, we need to create iterator for all dist processes. + # But, we only iterate through the DataLoader on process 0. + main_iterator = self.base_dataloader.__iter__() + elif self.state.process_index == 0: + main_iterator = self.base_dataloader.__iter__() + stop_iteration = False + self._stop_iteration = False + first_batch = None + next_batch, next_batch_info = self._fetch_batches(main_iterator) + batch_index = 0 + while not stop_iteration: + batch, batch_info = next_batch, next_batch_info + + if self.state.process_index != 0: + # Initialize tensors on other processes than process 0. + batch = initialize_tensors(batch_info[0]) + batch = send_to_device(batch, self.state.device, non_blocking=self._non_blocking) + # Broadcast the batch before splitting it. + batch = broadcast(batch, from_process=0) + + if not self._drop_last and first_batch is None: + # We keep at least num processes elements of the first batch to be able to complete the last batch + first_batch = self.slice_fn( + batch, + slice(0, self.state.num_processes), + process_index=self.state.process_index, + num_processes=self.state.num_processes, + ) + + if batch is None: + raise ValueError( + f"Batch does not contain any data (`{batch}`). At the end of all iterable data available before expected stop iteration." + ) + + observed_batch_size = find_batch_size(batch) + batch_size = observed_batch_size // self.state.num_processes + + stop_iteration = self._stop_iteration + if not stop_iteration: + # We may still be at the end of the dataloader without knowing it yet: if there is nothing left in + # the dataloader since the number of batches is a round multiple of the number of processes. + next_batch, next_batch_info = self._fetch_batches(main_iterator) + # next_batch_info[0] is None when there are no more batches, otherwise we still need to process them. + if self._stop_iteration and next_batch_info[0] is None: + stop_iteration = True + + if not self._drop_last and stop_iteration and observed_batch_size % self.state.num_processes != 0: + # If the last batch is not complete, let's add the first batch to it. + batch = concatenate([batch, first_batch], dim=0) + # Batch size computation above is wrong, it's off by 1 so we fix it. + batch_size += 1 + + data_slice = slice(self.state.process_index * batch_size, (self.state.process_index + 1) * batch_size) + batch = self.slice_fn( + batch, + data_slice, + process_index=self.state.process_index, + num_processes=self.state.num_processes, + ) + + if stop_iteration: + self.end_of_dataloader = True + self._update_state_dict() + self.remainder = observed_batch_size + if batch_index >= self.skip_batches: + yield batch + batch_index += 1 + self.iteration += 1 + self.end() + + def set_epoch(self, epoch: int): + # In case it is manually passed in, the user can set it to what they like + if self.iteration != epoch: + self.iteration = epoch + if hasattr(self.batch_sampler, "sampler") and hasattr(self.batch_sampler.sampler, "set_epoch"): + self.batch_sampler.sampler.set_epoch(epoch) + elif hasattr(self.dataset, "set_epoch"): + self.dataset.set_epoch(epoch) + + def __len__(self): + whole_length = super().__len__() + if self.split_batches: + return whole_length + elif self._drop_last: + return whole_length // self.state.num_processes + else: + return math.ceil(whole_length / self.state.num_processes) + + @property + def total_batch_size(self): + return ( + self.dataset.batch_size if self.split_batches else (self.dataset.batch_size * self.dataset.num_processes) + ) + + @property + def total_dataset_length(self): + return len(self.dataset) + + def get_sampler(self): + return get_sampler(self) + + def set_sampler(self, sampler): + sampler_is_batch_sampler = isinstance(self.sampler, BatchSampler) + if sampler_is_batch_sampler: + self.sampler.sampler = sampler + else: + self.batch_sampler.sampler = sampler + if hasattr(self.batch_sampler, "batch_sampler"): + self.batch_sampler.batch_sampler.sampler = sampler + + +def get_sampler(dataloader): + """ + Get the sampler associated to the dataloader + + Args: + dataloader (`torch.utils.data.dataloader.DataLoader`): + The data loader to split across several devices. + Returns: + `torch.utils.data.Sampler`: The sampler associated to the dataloader + """ + sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler) + if sampler_is_batch_sampler: + sampler = getattr(dataloader.sampler, "sampler", None) + else: + sampler = getattr(dataloader.batch_sampler, "sampler", None) + return sampler + + +def prepare_data_loader( + dataloader: DataLoader, + device: Optional[torch.device] = None, + num_processes: Optional[int] = None, + process_index: Optional[int] = None, + split_batches: bool = False, + put_on_device: bool = False, + rng_types: Optional[List[Union[str, RNGType]]] = None, + dispatch_batches: Optional[bool] = None, + even_batches: bool = True, + slice_fn_for_dispatch: Optional[Callable] = None, + use_seedable_sampler: bool = False, + non_blocking: bool = False, + use_stateful_dataloader: bool = False, +) -> DataLoader: + """ + Wraps a PyTorch `DataLoader` to generate batches for one of the processes only. + + Depending on the value of the `drop_last` attribute of the `dataloader` passed, it will either stop the iteration + at the first batch that would be too small / not present on all processes or loop with indices from the beginning. + + Args: + dataloader (`torch.utils.data.dataloader.DataLoader`): + The data loader to split across several devices. + device (`torch.device`): + The target device for the returned `DataLoader`. + num_processes (`int`, *optional*): + The number of processes running concurrently. Will default to the value given by [`~state.PartialState`]. + process_index (`int`, *optional*): + The index of the current process. Will default to the value given by [`~state.PartialState`]. + split_batches (`bool`, *optional*, defaults to `False`): + Whether the resulting `DataLoader` should split the batches of the original data loader across devices or + yield full batches (in which case it will yield batches starting at the `process_index`-th and advancing of + `num_processes` batches at each iteration). + + Another way to see this is that the observed batch size will be the same as the initial `dataloader` if + this option is set to `True`, the batch size of the initial `dataloader` multiplied by `num_processes` + otherwise. + + Setting this option to `True` requires that the batch size of the `dataloader` is a round multiple of + `batch_size`. + put_on_device (`bool`, *optional*, defaults to `False`): + Whether or not to put the batches on `device` (only works if the batches are nested list, tuples or + dictionaries of tensors). + rng_types (list of `str` or [`~utils.RNGType`]): + The list of random number generators to synchronize at the beginning of each iteration. Should be one or + several of: + + - `"torch"`: the base torch random number generator + - `"cuda"`: the CUDA random number generator (GPU only) + - `"xla"`: the XLA random number generator (TPU only) + - `"generator"`: the `torch.Generator` of the sampler (or batch sampler if there is no sampler in your + dataloader) or of the iterable dataset (if it exists) if the underlying dataset is of that type. + + dispatch_batches (`bool`, *optional*): + If set to `True`, the datalaoder prepared is only iterated through on the main process and then the batches + are split and broadcast to each process. Will default to `True` when the underlying dataset is an + `IterableDataset`, `False` otherwise. + even_batches (`bool`, *optional*, defaults to `True`): + If set to `True`, in cases where the total batch size across all processes does not exactly divide the + dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among + all workers. + slice_fn_for_dispatch (`Callable`, *optional*`): + If passed, this function will be used to slice tensors across `num_processes`. Will default to + [`~utils.slice_tensors`]. This argument is used only when `dispatch_batches` is set to `True` and will be + ignored otherwise. + use_seedable_sampler (`bool`, *optional*, defaults to `False`): + Whether to use the [`~data_loader.SeedableRandomSampler`] instead of a `RandomSampler` for better + reproducability. Comes at a cost of potentially different performances due to different shuffling + algorithms but ensures results will be the *exact* same. Should be paired with `set_seed()` at every + `self.set_epoch` + non_blocking (`bool`, *optional*, defaults to `False`): + If set to `True`, dataloader will utilize non-blocking host-to-device transfers. If the dataloader has + `pin_memory` set to `True`, this will help to increase overlap between data transfer and computations. + use_stateful_dataloader (`bool`, *optional*, defaults to `False`): + "If set to true, the dataloader prepared by the Accelerator will be backed by " + "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). + This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed." + + + Returns: + `torch.utils.data.dataloader.DataLoader`: A new data loader that will yield the portion of the batches + + + + `BatchSampler`s with varying batch sizes are not enabled by default. To enable this behaviour, set `even_batches` + equal to `False` + + + """ + if dispatch_batches is None: + if not put_on_device: + dispatch_batches = False + else: + dispatch_batches = isinstance(dataloader.dataset, IterableDataset) + + if dispatch_batches and not put_on_device: + raise ValueError("Using `dispatch_batches=True` requires `put_on_device=True`.") + # Grab defaults from PartialState + state = PartialState() + if num_processes is None: + num_processes = state.num_processes + if process_index is None: + process_index = state.process_index + + # Sanity check + if split_batches: + if dataloader.batch_size is not None: + batch_size_for_check = dataloader.batch_size + else: + # For custom batch_sampler + if hasattr(dataloader.batch_sampler, "batch_size"): + batch_size_for_check = dataloader.batch_sampler.batch_size + else: + raise ValueError( + "In order to use `split_batches==True` you must have a `batch_size` attribute either in the passed " + "`dataloader` or `dataloader.batch_sampler` objects, and it has to return a natural number. " + "Your `dataloader.batch_size` is None and `dataloader.batch_sampler` " + f"(`{type(dataloader.batch_sampler)}`) does not have the `batch_size` attribute set." + ) + + if batch_size_for_check > 1 and batch_size_for_check % num_processes != 0: + raise ValueError( + f"To use a `DataLoader` in `split_batches` mode, the batch size ({dataloader.batch_size}) " + f"needs to be a round multiple of the number of processes ({num_processes})." + ) + + new_dataset = dataloader.dataset + # Iterable dataset doesn't like batch_sampler, but data_loader creates a default one for it + new_batch_sampler = dataloader.batch_sampler if not isinstance(new_dataset, IterableDataset) else None + sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler) + synchronized_generator = None + + sampler = get_sampler(dataloader) + if isinstance(sampler, RandomSampler) and use_seedable_sampler: + # When iterating through the dataloader during distributed processes + # we want to ensure that on each process we are iterating through the same + # samples in the same order if a seed is set. This requires a tweak + # to the `torch.utils.data.RandomSampler` class (if used). + sampler = SeedableRandomSampler( + data_source=sampler.data_source, + replacement=sampler.replacement, + num_samples=sampler._num_samples, + generator=getattr(sampler, "generator", torch.Generator()), + ) + + if isinstance(dataloader.sampler, RandomSampler) and state.distributed_type == DistributedType.XLA: + # isinstance(dataloader.sampler, RandomSampler) indicates the original dataloader has `shuffle` enabled. + generator = torch.Generator().manual_seed(42) + dataloader.generator = generator + dataloader.sampler.generator = generator + # No change if no multiprocess + if (num_processes != 1 or state.distributed_type == DistributedType.MEGATRON_LM) and not dispatch_batches: + if isinstance(new_dataset, IterableDataset): + if getattr(dataloader.dataset, "generator", None) is not None: + synchronized_generator = dataloader.dataset.generator + new_dataset = IterableDatasetShard( + new_dataset, + batch_size=dataloader.batch_size, + drop_last=dataloader.drop_last, + num_processes=num_processes, + process_index=process_index, + split_batches=split_batches, + ) + else: + if not use_seedable_sampler and hasattr(sampler, "generator"): + if sampler.generator is None: + sampler.generator = torch.Generator() + synchronized_generator = sampler.generator + batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler + new_batch_sampler = BatchSamplerShard( + batch_sampler, + num_processes=num_processes, + process_index=process_index, + split_batches=split_batches, + even_batches=even_batches, + ) + + # We ignore all of those since they are all dealt with by our new_batch_sampler + ignore_kwargs = [ + "batch_size", + "shuffle", + "sampler", + "batch_sampler", + "drop_last", + ] + + if rng_types is not None and synchronized_generator is None and "generator" in rng_types: + rng_types.remove("generator") + + kwargs = { + k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k]) + for k in _PYTORCH_DATALOADER_KWARGS + if k not in ignore_kwargs + } + + # Need to provide batch_size as batch_sampler is None for Iterable dataset + if new_batch_sampler is None: + kwargs["drop_last"] = dataloader.drop_last + kwargs["batch_size"] = ( + dataloader.batch_size // num_processes if split_batches and not dispatch_batches else dataloader.batch_size + ) + if dispatch_batches: + kwargs.pop("generator") + dataloader = DataLoaderDispatcher( + new_dataset, + split_batches=split_batches, + batch_sampler=new_batch_sampler, + _drop_last=dataloader.drop_last, + _non_blocking=non_blocking, + slice_fn=slice_fn_for_dispatch, + use_stateful_dataloader=use_stateful_dataloader, + **kwargs, + ) + elif sampler_is_batch_sampler: + dataloader = DataLoaderShard( + new_dataset, + device=device if put_on_device and state.distributed_type != DistributedType.XLA else None, + sampler=new_batch_sampler, + batch_size=dataloader.batch_size, + rng_types=rng_types, + _drop_last=dataloader.drop_last, + _non_blocking=non_blocking, + synchronized_generator=synchronized_generator, + use_stateful_dataloader=use_stateful_dataloader, + **kwargs, + ) + else: + dataloader = DataLoaderShard( + new_dataset, + device=device if put_on_device and state.distributed_type != DistributedType.XLA else None, + batch_sampler=new_batch_sampler, + rng_types=rng_types, + synchronized_generator=synchronized_generator, + _drop_last=dataloader.drop_last, + _non_blocking=non_blocking, + use_stateful_dataloader=use_stateful_dataloader, + **kwargs, + ) + + if isinstance(sampler, SeedableRandomSampler) and use_seedable_sampler: + dataloader.set_sampler(sampler) + if state.distributed_type == DistributedType.XLA: + return MpDeviceLoaderWrapper(dataloader, device) + return dataloader + + +class SkipBatchSampler(BatchSampler): + """ + A `torch.utils.data.BatchSampler` that skips the first `n` batches of another `torch.utils.data.BatchSampler`. + Should not be used if the original dataloader is a `StatefulDataLoader`. + """ + + def __init__(self, batch_sampler, skip_batches=0): + self.batch_sampler = batch_sampler + self.skip_batches = skip_batches + + def __iter__(self): + for index, samples in enumerate(self.batch_sampler): + if index >= self.skip_batches: + yield samples + + @property + def total_length(self): + return len(self.batch_sampler) + + def __len__(self): + return len(self.batch_sampler) - self.skip_batches + + +class SkipDataLoader(DataLoaderAdapter, DataLoaderStateMixin): + """ + Subclass of a PyTorch `DataLoader` that will skip the first batches. Generally it's preferable to use + `skip_first_batches`/`torchdata.StatefulDataLoader` instead of this class. + + Args: + dataset (`torch.utils.data.dataset.Dataset`): + The dataset to use to build this datalaoder. + skip_batches (`int`, *optional*, defaults to 0): + The number of batches to skip at the beginning. + kwargs: + All other keyword arguments to pass to the regular `DataLoader` initialization. + """ + + def __init__(self, dataset, skip_batches=0, use_stateful_dataloader=False, **kwargs): + super().__init__(dataset, use_stateful_dataloader=use_stateful_dataloader, **kwargs) + self.skip_batches = skip_batches + self.gradient_state = GradientState() + + def __iter__(self): + self.begin() + for index, batch in enumerate(self.base_dataloader.__iter__()): + if index >= self.skip_batches: + self._update_state_dict() + yield batch + self.end() + + +def skip_first_batches(dataloader, num_batches=0): + """ + Creates a `torch.utils.data.DataLoader` that will efficiently skip the first `num_batches`. Should not be used if + the original dataloader is a `StatefulDataLoader`. + """ + state = PartialState() + if state.distributed_type == DistributedType.XLA: + device = dataloader.device + dataloader = dataloader.dataloader + + dataset = dataloader.dataset + sampler_is_batch_sampler = False + if isinstance(dataset, IterableDataset): + new_batch_sampler = None + else: + sampler_is_batch_sampler = isinstance(dataloader.sampler, BatchSampler) + batch_sampler = dataloader.sampler if sampler_is_batch_sampler else dataloader.batch_sampler + new_batch_sampler = SkipBatchSampler(batch_sampler, skip_batches=num_batches) + + # We ignore all of those since they are all dealt with by our new_batch_sampler + ignore_kwargs = [ + "batch_size", + "shuffle", + "sampler", + "batch_sampler", + "drop_last", + ] + + kwargs = { + k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k]) + for k in _PYTORCH_DATALOADER_KWARGS + if k not in ignore_kwargs + } + + # Need to provide batch_size as batch_sampler is None for Iterable dataset + if new_batch_sampler is None: + kwargs["drop_last"] = dataloader.drop_last + kwargs["batch_size"] = dataloader.batch_size + + if isinstance(dataloader, DataLoaderDispatcher): + if new_batch_sampler is None: + # Need to manually skip batches in the dataloader + kwargs["skip_batches"] = num_batches + dataloader = DataLoaderDispatcher( + dataset, + split_batches=dataloader.split_batches, + batch_sampler=new_batch_sampler, + _drop_last=dataloader._drop_last, + **kwargs, + ) + elif isinstance(dataloader, DataLoaderShard): + if new_batch_sampler is None: + # Need to manually skip batches in the dataloader + kwargs["skip_batches"] = num_batches + elif sampler_is_batch_sampler: + kwargs["sampler"] = new_batch_sampler + kwargs["batch_size"] = dataloader.batch_size + else: + kwargs["batch_sampler"] = new_batch_sampler + dataloader = DataLoaderShard( + dataset, + device=dataloader.device, + rng_types=dataloader.rng_types, + synchronized_generator=dataloader.synchronized_generator, + **kwargs, + ) + else: + if new_batch_sampler is None: + # Need to manually skip batches in the dataloader + dataloader = SkipDataLoader(dataset, skip_batches=num_batches, **kwargs) + else: + dataloader = DataLoader(dataset, batch_sampler=new_batch_sampler, **kwargs) + + if state.distributed_type == DistributedType.XLA: + dataloader = MpDeviceLoaderWrapper(dataloader, device) + + return dataloader diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/hooks.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/hooks.py new file mode 100644 index 0000000000000000000000000000000000000000..caadd8729eed2985f52d332e5bce62b523c60eb5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/hooks.py @@ -0,0 +1,718 @@ +# 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. + +import functools +from typing import Dict, List, Mapping, Optional, Union + +import torch +import torch.nn as nn + +from .state import PartialState +from .utils import ( + PrefixedDataset, + find_device, + named_module_tensors, + send_to_device, + set_module_tensor_to_device, +) +from .utils.memory import clear_device_cache +from .utils.modeling import get_non_persistent_buffers +from .utils.other import recursive_getattr + + +_accelerate_added_attributes = ["to", "cuda", "npu", "xpu", "mlu", "musa"] + + +class ModelHook: + """ + A hook that contains callbacks to be executed just before and after the forward method of a model. The difference + with PyTorch existing hooks is that they get passed along the kwargs. + + Class attribute: + - **no_grad** (`bool`, *optional*, defaults to `False`) -- Whether or not to execute the actual forward pass under + the `torch.no_grad()` context manager. + """ + + no_grad = False + + def init_hook(self, module): + """ + To be executed when the hook is attached to the module. + + Args: + module (`torch.nn.Module`): The module attached to this hook. + """ + return module + + def pre_forward(self, module, *args, **kwargs): + """ + To be executed just before the forward method of the model. + + Args: + module (`torch.nn.Module`): The module whose forward pass will be executed just after this event. + args (`Tuple[Any]`): The positional arguments passed to the module. + kwargs (`Dict[Str, Any]`): The keyword arguments passed to the module. + + Returns: + `Tuple[Tuple[Any], Dict[Str, Any]]`: A tuple with the treated `args` and `kwargs`. + """ + return args, kwargs + + def post_forward(self, module, output): + """ + To be executed just after the forward method of the model. + + Args: + module (`torch.nn.Module`): The module whose forward pass been executed just before this event. + output (`Any`): The output of the module. + + Returns: + `Any`: The processed `output`. + """ + return output + + def detach_hook(self, module): + """ + To be executed when the hook is detached from a module. + + Args: + module (`torch.nn.Module`): The module detached from this hook. + """ + return module + + +class SequentialHook(ModelHook): + """ + A hook that can contain several hooks and iterates through them at each event. + """ + + def __init__(self, *hooks): + self.hooks = hooks + + def init_hook(self, module): + for hook in self.hooks: + module = hook.init_hook(module) + return module + + def pre_forward(self, module, *args, **kwargs): + for hook in self.hooks: + args, kwargs = hook.pre_forward(module, *args, **kwargs) + return args, kwargs + + def post_forward(self, module, output): + for hook in self.hooks: + output = hook.post_forward(module, output) + return output + + def detach_hook(self, module): + for hook in self.hooks: + module = hook.detach_hook(module) + return module + + +def add_hook_to_module(module: nn.Module, hook: ModelHook, append: bool = False): + """ + Adds a hook to a given module. This will rewrite the `forward` method of the module to include the hook, to remove + this behavior and restore the original `forward` method, use `remove_hook_from_module`. + + + + If the module already contains a hook, this will replace it with the new hook passed by default. To chain two hooks + together, pass `append=True`, so it chains the current and new hook into an instance of the `SequentialHook` class. + + + + Args: + module (`torch.nn.Module`): + The module to attach a hook to. + hook (`ModelHook`): + The hook to attach. + append (`bool`, *optional*, defaults to `False`): + Whether the hook should be chained with an existing one (if module already contains a hook) or not. + + Returns: + `torch.nn.Module`: The same module, with the hook attached (the module is modified in place, so the result can + be discarded). + """ + + if append and (getattr(module, "_hf_hook", None) is not None): + old_hook = module._hf_hook + remove_hook_from_module(module) + hook = SequentialHook(old_hook, hook) + + if hasattr(module, "_hf_hook") and hasattr(module, "_old_forward"): + # If we already put some hook on this module, we replace it with the new one. + old_forward = module._old_forward + else: + old_forward = module.forward + module._old_forward = old_forward + + module = hook.init_hook(module) + module._hf_hook = hook + + def new_forward(module, *args, **kwargs): + args, kwargs = module._hf_hook.pre_forward(module, *args, **kwargs) + if module._hf_hook.no_grad: + with torch.no_grad(): + output = module._old_forward(*args, **kwargs) + else: + output = module._old_forward(*args, **kwargs) + return module._hf_hook.post_forward(module, output) + + # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail. + # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409 + if "GraphModuleImpl" in str(type(module)): + module.__class__.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward) + else: + module.forward = functools.update_wrapper(functools.partial(new_forward, module), old_forward) + + return module + + +def remove_hook_from_module(module: nn.Module, recurse=False): + """ + Removes any hook attached to a module via `add_hook_to_module`. + + Args: + module (`torch.nn.Module`): The module to attach a hook to. + recurse (`bool`, **optional**): Whether to remove the hooks recursively + + Returns: + `torch.nn.Module`: The same module, with the hook detached (the module is modified in place, so the result can + be discarded). + """ + + if hasattr(module, "_hf_hook"): + module._hf_hook.detach_hook(module) + delattr(module, "_hf_hook") + + if hasattr(module, "_old_forward"): + # Overriding a GraphModuleImpl forward freezes the forward call and later modifications on the graph will fail. + # Reference: https://pytorch.slack.com/archives/C3PDTEV8E/p1705929610405409 + if "GraphModuleImpl" in str(type(module)): + module.__class__.forward = module._old_forward + else: + module.forward = module._old_forward + delattr(module, "_old_forward") + + # Remove accelerate added warning hooks from dispatch_model + for attr in _accelerate_added_attributes: + module.__dict__.pop(attr, None) + + if recurse: + for child in module.children(): + remove_hook_from_module(child, recurse) + + return module + + +class AlignDevicesHook(ModelHook): + """ + A generic `ModelHook` that ensures inputs and model weights are on the same device for the forward pass of the + associated module, potentially offloading the weights after the forward pass. + + Args: + execution_device (`torch.device`, *optional*): + The device on which inputs and model weights should be placed before the forward pass. + offload (`bool`, *optional*, defaults to `False`): + Whether or not the weights should be offloaded after the forward pass. + io_same_device (`bool`, *optional*, defaults to `False`): + Whether or not the output should be placed on the same device as the input was. + weights_map (`Mapping[str, torch.Tensor]`, *optional*): + When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to include the associated module's buffers when offloading. + place_submodules (`bool`, *optional*, defaults to `False`): + Whether to place the submodules on `execution_device` during the `init_hook` event. + """ + + def __init__( + self, + execution_device: Optional[Union[int, str, torch.device]] = None, + offload: bool = False, + io_same_device: bool = False, + weights_map: Optional[Mapping] = None, + offload_buffers: bool = False, + place_submodules: bool = False, + skip_keys: Optional[Union[str, List[str]]] = None, + tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None, + ): + self.execution_device = execution_device + self.offload = offload + self.io_same_device = io_same_device + self.weights_map = weights_map + self.offload_buffers = offload_buffers + self.place_submodules = place_submodules + self.skip_keys = skip_keys + + # Will contain the input device when `io_same_device=True`. + self.input_device = None + self.param_original_devices = {} + self.buffer_original_devices = {} + self.tied_params_names = set() + + # The hook pre_forward/post_forward need to have knowledge of this dictionary, as with offloading we want to avoid duplicating memory + # for tied weights already loaded on the target execution device. + self.tied_params_map = tied_params_map + + def __repr__(self): + return ( + f"AlignDevicesHook(execution_device={self.execution_device}, offload={self.offload}, " + f"io_same_device={self.io_same_device}, offload_buffers={self.offload_buffers}, " + f"place_submodules={self.place_submodules}, skip_keys={repr(self.skip_keys)})" + ) + + def init_hook(self, module): + # In case the AlignDevicesHook is on meta device, ignore tied weights as data_ptr() is then always zero. + if self.execution_device == "meta" or self.execution_device == torch.device("meta"): + self.tied_params_map = None + + if not self.offload and self.execution_device is not None: + for name, _ in named_module_tensors(module, recurse=self.place_submodules): + set_module_tensor_to_device(module, name, self.execution_device, tied_params_map=self.tied_params_map) + elif self.offload: + self.original_devices = { + name: param.device for name, param in named_module_tensors(module, recurse=self.place_submodules) + } + if self.weights_map is None: + self.weights_map = { + name: param.to("cpu") + for name, param in named_module_tensors( + module, include_buffers=self.offload_buffers, recurse=self.place_submodules + ) + } + for name, _ in named_module_tensors( + module, include_buffers=self.offload_buffers, recurse=self.place_submodules, remove_non_persistent=True + ): + # When using disk offloading, we can not rely on `weights_map[name].data_ptr()` as the reference pointer, + # as we have no guarantee that safetensors' `file.get_tensor()` will always give the same pointer. + # As we have no reliable way to track the shared data pointer of tied weights in this case, we use tied_params_names: List[str] + # to add on the fly pointers to `tied_params_map` in the pre_forward call. + if ( + self.tied_params_map is not None + and recursive_getattr(module, name).data_ptr() in self.tied_params_map + ): + self.tied_params_names.add(name) + + set_module_tensor_to_device(module, name, "meta") + + if not self.offload_buffers and self.execution_device is not None: + for name, _ in module.named_buffers(recurse=self.place_submodules): + set_module_tensor_to_device( + module, name, self.execution_device, tied_params_map=self.tied_params_map + ) + elif self.offload_buffers and self.execution_device is not None: + for name in get_non_persistent_buffers(module, recurse=self.place_submodules): + set_module_tensor_to_device( + module, name, self.execution_device, tied_params_map=self.tied_params_map + ) + + return module + + def pre_forward(self, module, *args, **kwargs): + if self.io_same_device: + self.input_device = find_device([args, kwargs]) + if self.offload: + self.tied_pointers_to_remove = set() + + for name, _ in named_module_tensors( + module, + include_buffers=self.offload_buffers, + recurse=self.place_submodules, + remove_non_persistent=True, + ): + fp16_statistics = None + value = self.weights_map[name] + if "weight" in name and name.replace("weight", "SCB") in self.weights_map.keys(): + if value.dtype == torch.int8: + fp16_statistics = self.weights_map[name.replace("weight", "SCB")] + + # In case we are using offloading with tied weights, we need to keep track of the offloaded weights + # that are loaded on device at this point, as we will need to remove them as well from the dictionary + # self.tied_params_map in order to allow to free memory. + if name in self.tied_params_names and value.data_ptr() not in self.tied_params_map: + self.tied_params_map[value.data_ptr()] = {} + + if ( + value is not None + and self.tied_params_map is not None + and value.data_ptr() in self.tied_params_map + and self.execution_device not in self.tied_params_map[value.data_ptr()] + ): + self.tied_pointers_to_remove.add((value.data_ptr(), self.execution_device)) + + set_module_tensor_to_device( + module, + name, + self.execution_device, + value=value, + fp16_statistics=fp16_statistics, + tied_params_map=self.tied_params_map, + ) + + return send_to_device(args, self.execution_device), send_to_device( + kwargs, self.execution_device, skip_keys=self.skip_keys + ) + + def post_forward(self, module, output): + if self.offload: + for name, _ in named_module_tensors( + module, + include_buffers=self.offload_buffers, + recurse=self.place_submodules, + remove_non_persistent=True, + ): + set_module_tensor_to_device(module, name, "meta") + if type(module).__name__ == "Linear8bitLt": + module.state.SCB = None + module.state.CxB = None + + # We may have loaded tied weights into self.tied_params_map (avoiding to load them several times in e.g. submodules): remove them from + # this dictionary to allow the garbage collector to do its job. + for value_pointer, device in self.tied_pointers_to_remove: + del self.tied_params_map[value_pointer][device] + self.tied_pointers_to_remove = set() + + if self.io_same_device and self.input_device is not None: + output = send_to_device(output, self.input_device, skip_keys=self.skip_keys) + + return output + + def detach_hook(self, module): + if self.offload: + for name, device in self.original_devices.items(): + if device != torch.device("meta"): + set_module_tensor_to_device(module, name, device, value=self.weights_map.get(name, None)) + return module + + +def attach_execution_device_hook( + module: torch.nn.Module, + execution_device: Union[int, str, torch.device], + skip_keys: Optional[Union[str, List[str]]] = None, + preload_module_classes: Optional[List[str]] = None, + tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None, +): + """ + Recursively attaches `AlignDevicesHook` to all submodules of a given model to make sure they have the right + execution device + + Args: + module (`torch.nn.Module`): + The module where we want to attach the hooks. + execution_device (`int`, `str` or `torch.device`): + The device on which inputs and model weights should be placed before the forward pass. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`): + A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution + device, this parameter is useful to reuse the first available pointer of a shared weight for all others, + instead of duplicating memory. + """ + if not hasattr(module, "_hf_hook") and len(module.state_dict()) > 0: + add_hook_to_module( + module, + AlignDevicesHook(execution_device, skip_keys=skip_keys, tied_params_map=tied_params_map), + ) + + # Break the recursion if we get to a preload module. + if preload_module_classes is not None and module.__class__.__name__ in preload_module_classes: + return + + for child in module.children(): + attach_execution_device_hook(child, execution_device, tied_params_map=tied_params_map) + + +def attach_align_device_hook( + module: torch.nn.Module, + execution_device: Optional[torch.device] = None, + offload: bool = False, + weights_map: Optional[Mapping] = None, + offload_buffers: bool = False, + module_name: str = "", + skip_keys: Optional[Union[str, List[str]]] = None, + preload_module_classes: Optional[List[str]] = None, + tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None, +): + """ + Recursively attaches `AlignDevicesHook` to all submodules of a given model that have direct parameters and/or + buffers. + + Args: + module (`torch.nn.Module`): + The module where we want to attach the hooks. + execution_device (`torch.device`, *optional*): + The device on which inputs and model weights should be placed before the forward pass. + offload (`bool`, *optional*, defaults to `False`): + Whether or not the weights should be offloaded after the forward pass. + weights_map (`Mapping[str, torch.Tensor]`, *optional*): + When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to include the associated module's buffers when offloading. + module_name (`str`, *optional*, defaults to `""`): + The name of the module. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`): + A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution + device, this parameter is useful to reuse the first available pointer of a shared weight for all others, + instead of duplicating memory. + """ + # Attach the hook on this module if it has any direct tensor. + directs = named_module_tensors(module) + full_offload = ( + offload and preload_module_classes is not None and module.__class__.__name__ in preload_module_classes + ) + + if len(list(directs)) > 0 or full_offload: + if weights_map is not None: + prefix = f"{module_name}." if len(module_name) > 0 else "" + prefixed_weights_map = PrefixedDataset(weights_map, prefix) + else: + prefixed_weights_map = None + hook = AlignDevicesHook( + execution_device=execution_device, + offload=offload, + weights_map=prefixed_weights_map, + offload_buffers=offload_buffers, + place_submodules=full_offload, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook, append=True) + + # We stop the recursion in case we hit the full offload. + if full_offload: + return + + # Recurse on all children of the module. + for child_name, child in module.named_children(): + child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name + attach_align_device_hook( + child, + execution_device=execution_device, + offload=offload, + weights_map=weights_map, + offload_buffers=offload_buffers, + module_name=child_name, + preload_module_classes=preload_module_classes, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + + +def remove_hook_from_submodules(module: nn.Module): + """ + Recursively removes all hooks attached on the submodules of a given model. + + Args: + module (`torch.nn.Module`): The module on which to remove all hooks. + """ + remove_hook_from_module(module) + for child in module.children(): + remove_hook_from_submodules(child) + + +def attach_align_device_hook_on_blocks( + module: nn.Module, + execution_device: Optional[Union[torch.device, Dict[str, torch.device]]] = None, + offload: Union[bool, Dict[str, bool]] = False, + weights_map: Mapping = None, + offload_buffers: bool = False, + module_name: str = "", + skip_keys: Optional[Union[str, List[str]]] = None, + preload_module_classes: Optional[List[str]] = None, + tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None, +): + """ + Attaches `AlignDevicesHook` to all blocks of a given model as needed. + + Args: + module (`torch.nn.Module`): + The module where we want to attach the hooks. + execution_device (`torch.device` or `Dict[str, torch.device]`, *optional*): + The device on which inputs and model weights should be placed before the forward pass. It can be one device + for the whole module, or a dictionary mapping module name to device. + offload (`bool`, *optional*, defaults to `False`): + Whether or not the weights should be offloaded after the forward pass. It can be one boolean for the whole + module, or a dictionary mapping module name to boolean. + weights_map (`Mapping[str, torch.Tensor]`, *optional*): + When the model weights are offloaded, a (potentially lazy) map from param names to the tensor values. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to include the associated module's buffers when offloading. + module_name (`str`, *optional*, defaults to `""`): + The name of the module. + skip_keys (`str` or `List[str]`, *optional*): + A list of keys to ignore when moving inputs or outputs between devices. + preload_module_classes (`List[str]`, *optional*): + A list of classes whose instances should load all their weights (even in the submodules) at the beginning + of the forward. This should only be used for classes that have submodules which are registered but not + called directly during the forward, for instance if a `dense` linear layer is registered, but at forward, + `dense.weight` and `dense.bias` are used in some operations instead of calling `dense` directly. + tied_params_map (Optional[Dict[int, Dict[torch.device, torch.Tensor]]], *optional*, defaults to `None`): + A map of data pointers to dictionaries of devices to already dispatched tied weights. For a given execution + device, this parameter is useful to reuse the first available pointer of a shared weight for all others, + instead of duplicating memory. + """ + # If one device and one offload, we've got one hook. + if not isinstance(execution_device, Mapping) and not isinstance(offload, dict): + if not offload: + hook = AlignDevicesHook( + execution_device=execution_device, + io_same_device=True, + skip_keys=skip_keys, + place_submodules=True, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook) + else: + attach_align_device_hook( + module, + execution_device=execution_device, + offload=True, + weights_map=weights_map, + offload_buffers=offload_buffers, + module_name=module_name, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + return + + if not isinstance(execution_device, Mapping): + execution_device = {key: execution_device for key in offload.keys()} + if not isinstance(offload, Mapping): + offload = {key: offload for key in execution_device.keys()} + + if module_name in execution_device and module_name in offload and not offload[module_name]: + hook = AlignDevicesHook( + execution_device=execution_device[module_name], + offload_buffers=offload_buffers, + io_same_device=(module_name == ""), + place_submodules=True, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook) + attach_execution_device_hook(module, execution_device[module_name], tied_params_map=tied_params_map) + elif module_name in execution_device and module_name in offload: + attach_align_device_hook( + module, + execution_device=execution_device[module_name], + offload=True, + weights_map=weights_map, + offload_buffers=offload_buffers, + module_name=module_name, + skip_keys=skip_keys, + preload_module_classes=preload_module_classes, + tied_params_map=tied_params_map, + ) + if not hasattr(module, "_hf_hook"): + hook = AlignDevicesHook( + execution_device=execution_device[module_name], + io_same_device=(module_name == ""), + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook) + attach_execution_device_hook( + module, + execution_device[module_name], + preload_module_classes=preload_module_classes, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + elif module_name == "": + hook = AlignDevicesHook( + execution_device=execution_device.get(""), + io_same_device=True, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + add_hook_to_module(module, hook) + + for child_name, child in module.named_children(): + child_name = f"{module_name}.{child_name}" if len(module_name) > 0 else child_name + attach_align_device_hook_on_blocks( + child, + execution_device=execution_device, + offload=offload, + weights_map=weights_map, + offload_buffers=offload_buffers, + module_name=child_name, + preload_module_classes=preload_module_classes, + skip_keys=skip_keys, + tied_params_map=tied_params_map, + ) + + +class CpuOffload(ModelHook): + """ + Offloads a model on the CPU until its forward pass is called. The model will not be offloaded back to the CPU after + the forward, the user needs to call the `init_hook` method again for this. + + Args: + execution_device(`str`, `int` or `torch.device`, *optional*): + The device on which the model should be executed. Will default to the MPS device if it's available, then + GPU 0 if there is a GPU, and finally to the CPU. + prev_module_hook (`UserCpuOffloadHook`, *optional*): + The hook sent back by [`cpu_offload_with_hook`] for a previous model in the pipeline you are running. If + passed, its offload method will be called just before the forward of the model to which this hook is + attached. + """ + + def __init__( + self, + execution_device: Optional[Union[str, int, torch.device]] = None, + prev_module_hook: Optional["UserCpuOffloadHook"] = None, + ): + self.prev_module_hook = prev_module_hook + + self.execution_device = execution_device if execution_device is not None else PartialState().default_device + + def init_hook(self, module): + return module.to("cpu") + + def pre_forward(self, module, *args, **kwargs): + if self.prev_module_hook is not None: + self.prev_module_hook.offload() + clear_device_cache() + module.to(self.execution_device) + return send_to_device(args, self.execution_device), send_to_device(kwargs, self.execution_device) + + +class UserCpuOffloadHook: + """ + A simple hook grouping a model and a `ModelHook`, which provides easy APIs for to call the init method of the hook + or remove it entirely. + """ + + def __init__(self, model, hook): + self.model = model + self.hook = hook + + def offload(self): + self.hook.init_hook(self.model) + + def remove(self): + remove_hook_from_module(self.model) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/inference.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/inference.py new file mode 100644 index 0000000000000000000000000000000000000000..7ee0bdd6f6359011b5a5081e3403ab31c40cafb2 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/inference.py @@ -0,0 +1,184 @@ +# 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. +import math +from types import MethodType +from typing import Any, Dict, List, Optional, Tuple, Union + +from .state import PartialState +from .utils import ( + calculate_maximum_sizes, + convert_bytes, + copy_tensor_to_devices, + ignorant_find_batch_size, + infer_auto_device_map, + is_pippy_available, + pad_input_tensors, + send_to_device, +) + + +def generate_device_map(model, num_processes: int = 1, no_split_module_classes=None, max_memory: dict = None): + """ + Calculates the device map for `model` with an offset for PiPPy + """ + if num_processes == 1: + return infer_auto_device_map(model, no_split_module_classes=no_split_module_classes, clean_result=False) + if max_memory is None: + model_size, shared = calculate_maximum_sizes(model) + + # Split into `n` chunks for each GPU + memory = (model_size + shared[0]) / num_processes + memory = convert_bytes(memory) + value, ending = memory.split(" ") + + # Add a chunk to deal with potential extra shared memory instances + memory = math.ceil(float(value)) * 1.1 + memory = f"{memory} {ending}" + max_memory = {i: memory for i in range(num_processes)} + device_map = infer_auto_device_map( + model, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + clean_result=False, + ) + return device_map + + +def find_pippy_batch_size(args, kwargs): + found_batch_size = None + if args is not None: + for arg in args: + found_batch_size = ignorant_find_batch_size(arg) + if found_batch_size is not None: + break + if kwargs is not None and found_batch_size is None: + for kwarg in kwargs.values(): + found_batch_size = ignorant_find_batch_size(kwarg) + if found_batch_size is not None: + break + return found_batch_size + + +def build_pipeline(model, split_points, args, kwargs, num_chunks): + """ + Attaches the split points to the model based on `self.device_map` and generates a `PipelineStage`. Requires passing + in needed `args` and `kwargs` as the model needs on the CPU. + + Users can pass in custom `num_chunks` as an optional hyper-parameter. By default will use + `AcceleratorState.num_processes` + """ + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + from torch.distributed.pipelining import ScheduleGPipe, SplitPoint, pipeline + + # We need to annotate the split points in the model for PiPPy + state = PartialState() + split_spec = {split_point: SplitPoint.BEGINNING for split_point in split_points} + pipe = pipeline( + model, + mb_args=args, + mb_kwargs=kwargs, + split_spec=split_spec, + ) + stage = pipe.build_stage(state.local_process_index, device=state.device) + schedule = ScheduleGPipe(stage, num_chunks) + + return schedule + + +def pippy_forward(forward, num_chunks, gather_output, *args, **kwargs): + state = PartialState() + output = None + + if state.num_processes == 1: + output = forward(*args, **kwargs) + elif state.is_local_main_process: + found_batch_size = find_pippy_batch_size(args, kwargs) + if found_batch_size is None: + raise ValueError("Could not find batch size from args or kwargs") + else: + if found_batch_size != num_chunks: + args = pad_input_tensors(args, found_batch_size, num_chunks) + kwargs = pad_input_tensors(kwargs, found_batch_size, num_chunks) + forward(*args, **kwargs) + elif state.is_last_process: + output = forward() + else: + forward() + if gather_output: + # Each node will get a copy of the full output which is only on the last GPU + output = copy_tensor_to_devices(output) + return output + + +def prepare_pippy( + model, + split_points: Optional[Union[str, List[str]]] = "auto", + no_split_module_classes: Optional[List[str]] = None, + example_args: Optional[Tuple[Any]] = (), + example_kwargs: Optional[Dict[str, Any]] = None, + num_chunks: Optional[int] = None, + gather_output: Optional[bool] = False, +): + """ + Wraps `model` for pipeline parallel inference. + + Args: + model (`torch.nn.Module`): + A model we want to split for pipeline-parallel inference + split_points (`str` or `List[str]`, defaults to 'auto'): + How to generate the split points and chunk the model across each GPU. 'auto' will find the best balanced + split given any model. Should be a list of layer names in the model to split by otherwise. + no_split_module_classes (`List[str]`): + A list of class names for layers we don't want to be split. + example_args (tuple of model inputs): + The expected inputs for the model that uses order-based inputs for a *single process*. Recommended to use + this method if possible. + example_kwargs (dict of model inputs) + The expected inputs for the model that uses dictionary-based inputs for a *single process*. This is a + *highly* limiting structure that requires the same keys be present at *all* inference calls. Not + recommended unless the prior condition is true for all cases. + num_chunks (`int`, defaults to the number of available GPUs): + The number of different stages the Pipeline will have. By default it will assign one chunk per GPU, but + this can be tuned and played with. In general one should have num_chunks >= num_gpus. + gather_output (`bool`, defaults to `False`): + If `True`, the output from the last GPU (which holds the true outputs) is sent across to all GPUs. + """ + if not is_pippy_available(): + raise ImportError("Using `torch.distributed.pipelining` requires PyTorch 2.4.0 or later.") + state = PartialState() + example_args = send_to_device(example_args, "cpu") + example_kwargs = send_to_device(example_kwargs, "cpu") + if num_chunks is None: + num_chunks = state.num_processes + if split_points == "auto": + device_map = generate_device_map(model, num_chunks, no_split_module_classes=no_split_module_classes) + split_points = [] + for i in range(1, num_chunks): + split_points.append(next(k for k, v in device_map.items() if v == i)) + model.hf_split_points = split_points + stage = build_pipeline(model, split_points, example_args, example_kwargs, num_chunks) + model._original_forward = model.forward + model._original_call = model.__call__ + model.pippy_stage = stage + model.hf_split_points = split_points + + def forward(*args, **kwargs): + return pippy_forward(stage.step, num_chunks, gather_output, *args, **kwargs) + + # To act like a decorator so that it can be popped when doing `extract_model_from_parallel` + # Note: creates an infinite recursion loop with `generate` + model_forward = MethodType(forward, model) + forward.__wrapped__ = model_forward + model.forward = forward + return model diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/launchers.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/launchers.py new file mode 100644 index 0000000000000000000000000000000000000000..3aa0ca22b28c166f291f6ae7d65180188256231a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/launchers.py @@ -0,0 +1,302 @@ +# 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. + +import os +import sys +import tempfile + +import torch + +from .state import AcceleratorState, PartialState +from .utils import ( + PrecisionType, + PrepareForLaunch, + are_libraries_initialized, + check_cuda_p2p_ib_support, + get_gpu_info, + is_mps_available, + is_torch_version, + patch_environment, +) +from .utils.constants import ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION + + +def test_launch(): + "Verify a `PartialState` can be initialized." + _ = PartialState() + + +def notebook_launcher( + function, + args=(), + num_processes=None, + mixed_precision="no", + use_port="29500", + master_addr="127.0.0.1", + node_rank=0, + num_nodes=1, + rdzv_backend="static", + rdzv_endpoint="", + rdzv_conf=None, + rdzv_id="none", + max_restarts=0, + monitor_interval=0.1, + log_line_prefix_template=None, +): + """ + Launches a training function, using several processes or multiple nodes if it's possible in the current environment + (TPU with multiple cores for instance). + + + + To use this function absolutely zero calls to a CUDA device must be made in the notebook session before calling. If + any have been made, you will need to restart the notebook and make sure no cells use any CUDA capability. + + Setting `ACCELERATE_DEBUG_MODE="1"` in your environment will run a test before truly launching to ensure that none + of those calls have been made. + + + + Args: + function (`Callable`): + The training function to execute. If it accepts arguments, the first argument should be the index of the + process run. + args (`Tuple`): + Tuple of arguments to pass to the function (it will receive `*args`). + num_processes (`int`, *optional*): + The number of processes to use for training. Will default to 8 in Colab/Kaggle if a TPU is available, to + the number of GPUs available otherwise. + mixed_precision (`str`, *optional*, defaults to `"no"`): + If `fp16` or `bf16`, will use mixed precision training on multi-GPU. + use_port (`str`, *optional*, defaults to `"29500"`): + The port to use to communicate between processes when launching a multi-GPU training. + master_addr (`str`, *optional*, defaults to `"127.0.0.1"`): + The address to use for communication between processes. + node_rank (`int`, *optional*, defaults to 0): + The rank of the current node. + num_nodes (`int`, *optional*, defaults to 1): + The number of nodes to use for training. + rdzv_backend (`str`, *optional*, defaults to `"static"`): + The rendezvous method to use, such as 'static' (the default) or 'c10d' + rdzv_endpoint (`str`, *optional*, defaults to `""`): + The endpoint of the rdzv sync. storage. + rdzv_conf (`Dict`, *optional*, defaults to `None`): + Additional rendezvous configuration. + rdzv_id (`str`, *optional*, defaults to `"none"`): + The unique run id of the job. + max_restarts (`int`, *optional*, defaults to 0): + The maximum amount of restarts that elastic agent will conduct on workers before failure. + monitor_interval (`float`, *optional*, defaults to 0.1): + The interval in seconds that is used by the elastic_agent as a period of monitoring workers. + log_line_prefix_template (`str`, *optional*, defaults to `None`): + The prefix template for elastic launch logging. Available from PyTorch 2.2.0. + + Example: + + ```python + # Assume this is defined in a Jupyter Notebook on an instance with two GPUs + from accelerate import notebook_launcher + + + def train(*args): + # Your training function here + ... + + + notebook_launcher(train, args=(arg1, arg2), num_processes=2, mixed_precision="fp16") + ``` + """ + # Are we in a google colab or a Kaggle Kernel? + in_colab = False + in_kaggle = False + if any(key.startswith("KAGGLE") for key in os.environ.keys()): + in_kaggle = True + elif "IPython" in sys.modules: + in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython()) + + try: + mixed_precision = PrecisionType(mixed_precision.lower()) + except ValueError: + raise ValueError( + f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." + ) + + if (in_colab or in_kaggle) and (os.environ.get("TPU_NAME", None) is not None): + # TPU launch + import torch_xla.distributed.xla_multiprocessing as xmp + + if len(AcceleratorState._shared_state) > 0: + raise ValueError( + "To train on TPU in Colab or Kaggle Kernel, the `Accelerator` should only be initialized inside " + "your training function. Restart your notebook and make sure no cells initializes an " + "`Accelerator`." + ) + if num_processes is None: + num_processes = 8 + + launcher = PrepareForLaunch(function, distributed_type="TPU") + print(f"Launching a training on {num_processes} TPU cores.") + xmp.spawn(launcher, args=args, nprocs=num_processes, start_method="fork") + elif in_colab and get_gpu_info()[1] < 2: + # No need for a distributed launch otherwise as it's either CPU or one GPU. + if torch.cuda.is_available(): + print("Launching training on one GPU.") + else: + print("Launching training on one CPU.") + function(*args) + else: + if num_processes is None: + raise ValueError( + "You have to specify the number of GPUs you would like to use, add `num_processes=...` to your call." + ) + if node_rank >= num_nodes: + raise ValueError("The node_rank must be less than the number of nodes.") + if num_processes > 1: + # Multi-GPU launch + from torch.distributed.launcher.api import LaunchConfig, elastic_launch + from torch.multiprocessing import start_processes + from torch.multiprocessing.spawn import ProcessRaisedException + + if len(AcceleratorState._shared_state) > 0: + raise ValueError( + "To launch a multi-GPU training from your notebook, the `Accelerator` should only be initialized " + "inside your training function. Restart your notebook and make sure no cells initializes an " + "`Accelerator`." + ) + # Check for specific libraries known to initialize CUDA that users constantly use + problematic_imports = are_libraries_initialized("bitsandbytes") + if len(problematic_imports) > 0: + err = ( + "Could not start distributed process. Libraries known to initialize CUDA upon import have been " + "imported already. Please keep these imports inside your training function to try and help with this:" + ) + for lib_name in problematic_imports: + err += f"\n\t* `{lib_name}`" + raise RuntimeError(err) + + patched_env = dict( + nproc=num_processes, + node_rank=node_rank, + world_size=num_nodes * num_processes, + master_addr=master_addr, + master_port=use_port, + mixed_precision=mixed_precision, + ) + + # Check for CUDA P2P and IB issues + if not check_cuda_p2p_ib_support(): + patched_env["nccl_p2p_disable"] = "1" + patched_env["nccl_ib_disable"] = "1" + + # torch.distributed will expect a few environment variable to be here. We set the ones common to each + # process here (the other ones will be set be the launcher). + with patch_environment(**patched_env): + # First dummy launch + if os.environ.get("ACCELERATE_DEBUG_MODE", "false").lower() == "true": + launcher = PrepareForLaunch(test_launch, distributed_type="MULTI_GPU") + try: + start_processes(launcher, args=(), nprocs=num_processes, start_method="fork") + except ProcessRaisedException as e: + err = "An issue was found when verifying a stable environment for the notebook launcher." + if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: + raise RuntimeError( + f"{err}" + "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. " + "Please review your imports and test them when running the `notebook_launcher()` to identify " + "which one is problematic and causing CUDA to be initialized." + ) from e + else: + raise RuntimeError(f"{err} The following error was raised: {e}") from e + # Now the actual launch + launcher = PrepareForLaunch(function, distributed_type="MULTI_GPU") + print(f"Launching training on {num_processes} GPUs.") + try: + if rdzv_conf is None: + rdzv_conf = {} + if rdzv_backend == "static": + rdzv_conf["rank"] = node_rank + if not rdzv_endpoint: + rdzv_endpoint = f"{master_addr}:{use_port}" + launch_config_kwargs = dict( + min_nodes=num_nodes, + max_nodes=num_nodes, + nproc_per_node=num_processes, + run_id=rdzv_id, + rdzv_endpoint=rdzv_endpoint, + rdzv_backend=rdzv_backend, + rdzv_configs=rdzv_conf, + max_restarts=max_restarts, + monitor_interval=monitor_interval, + start_method="fork", + ) + if is_torch_version(">=", ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION): + launch_config_kwargs["log_line_prefix_template"] = log_line_prefix_template + elastic_launch(config=LaunchConfig(**launch_config_kwargs), entrypoint=function)(*args) + except ProcessRaisedException as e: + if "Cannot re-initialize CUDA in forked subprocess" in e.args[0]: + raise RuntimeError( + "CUDA has been initialized before the `notebook_launcher` could create a forked subprocess. " + "This likely stems from an outside import causing issues once the `notebook_launcher()` is called. " + "Please review your imports and test them when running the `notebook_launcher()` to identify " + "which one is problematic and causing CUDA to be initialized." + ) from e + else: + raise RuntimeError(f"An issue was found when launching the training: {e}") from e + + else: + # No need for a distributed launch otherwise as it's either CPU, GPU or MPS. + if is_mps_available(): + os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + print("Launching training on MPS.") + elif torch.cuda.is_available(): + print("Launching training on one GPU.") + else: + print("Launching training on CPU.") + function(*args) + + +def debug_launcher(function, args=(), num_processes=2): + """ + Launches a training function using several processes on CPU for debugging purposes. + + + + This function is provided for internal testing and debugging, but it's not intended for real trainings. It will + only use the CPU. + + + + Args: + function (`Callable`): + The training function to execute. + args (`Tuple`): + Tuple of arguments to pass to the function (it will receive `*args`). + num_processes (`int`, *optional*, defaults to 2): + The number of processes to use for training. + """ + from torch.multiprocessing import start_processes + + with tempfile.NamedTemporaryFile() as tmp_file: + # torch.distributed will expect a few environment variable to be here. We set the ones common to each + # process here (the other ones will be set be the launcher). + with patch_environment( + world_size=num_processes, + master_addr="127.0.0.1", + master_port="29500", + accelerate_mixed_precision="no", + accelerate_debug_rdv_file=tmp_file.name, + accelerate_use_cpu="yes", + ): + launcher = PrepareForLaunch(function, debug=True) + start_processes(launcher, args=args, nprocs=num_processes, start_method="fork") diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/local_sgd.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/local_sgd.py new file mode 100644 index 0000000000000000000000000000000000000000..382c34bc91c42c423db5caf37a6579260e29d090 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/local_sgd.py @@ -0,0 +1,103 @@ +# 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. +import torch + +from accelerate import Accelerator, DistributedType + + +class LocalSGD: + """ + A helper class to support local SGD on top of Accelerator. It simply runs a given number of updates independently + on each device, and averages model weights every K synchronization step. + + It should be used only in the multi-GPU (or multi-CPU) setup without extensions such as DeepSpeed. In particular, + this is a simple implementation that cannot support scenarios such as model parallelism. + + + Although we are not aware of the true origins of this simple approach, the idea of local SGD is quite old and goes + back to at least: + + Zhang, J., De Sa, C., Mitliagkas, I., & Ré, C. (2016). [Parallel SGD: When does averaging help?. arXiv preprint + arXiv:1606.07365.](https://arxiv.org/abs/1606.07365) + + We credit the term Local SGD to the following paper (but there might be earlier references we are not aware of). + + Stich, Sebastian Urban. ["Local SGD Converges Fast and Communicates Little." ICLR 2019-International Conference on + Learning Representations. No. CONF. 2019.](https://arxiv.org/abs/1805.09767) + + """ + + def __enter__(self): + if self.enabled: + self.model_sync_obj = self.model.no_sync() + self.model_sync_obj.__enter__() + + return self + + def __exit__(self, type, value, tb): + if self.enabled: + # Average all models on exit + self._sync_and_avg_model_params() + self.model_sync_obj.__exit__(type, value, tb) + + def __init__(self, accelerator: Accelerator, model: torch.nn.Module, local_sgd_steps: int, enabled: bool = True): + """ + Constructor. + + Args: + model (`torch.nn.Module): + The model whose parameters we need to average. + accelerator (`Accelerator`): + Accelerator object. + local_sgd_steps (`int`): + A number of local SGD steps (before model parameters are synchronized). + enabled (`bool): + Local SGD is disabled if this parameter set to `False`. + """ + if accelerator.distributed_type not in [ + DistributedType.NO, + DistributedType.MULTI_CPU, + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + ]: + raise NotImplementedError("LocalSGD is supported only for CPUs and GPUs (no DeepSpeed or MegatronLM)") + self.enabled = enabled and accelerator.distributed_type != DistributedType.NO + self.num_steps = 0 + if self.enabled: + self.accelerator = accelerator + self.model = model + self.local_sgd_steps = local_sgd_steps + + def step(self): + """ + This function makes a "step" and synchronizes model parameters if necessary. + """ + self.num_steps += 1 + if not self.enabled: + return + + if self.num_steps % self.local_sgd_steps == 0: + self._sync_and_avg_model_params() + + def _sync_and_avg_model_params(self): + """ + Synchronize + Average model parameters across all GPUs + """ + + self.accelerator.wait_for_everyone() + with self.accelerator.autocast(): + for param in self.model.parameters(): + param.data = self.accelerator.reduce(param.data, reduction="mean") diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/logging.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/logging.py new file mode 100644 index 0000000000000000000000000000000000000000..1615bc313b74d4f01166384435b6c499ff616f49 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/logging.py @@ -0,0 +1,125 @@ +# 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. + +import functools +import logging +import os + +from .state import PartialState + + +class MultiProcessAdapter(logging.LoggerAdapter): + """ + An adapter to assist with logging in multiprocess. + + `log` takes in an additional `main_process_only` kwarg, which dictates whether it should be called on all processes + or only the main executed one. Default is `main_process_only=True`. + + Does not require an `Accelerator` object to be created first. + """ + + @staticmethod + def _should_log(main_process_only): + "Check if log should be performed" + state = PartialState() + return not main_process_only or (main_process_only and state.is_main_process) + + def log(self, level, msg, *args, **kwargs): + """ + Delegates logger call after checking if we should log. + + Accepts a new kwarg of `main_process_only`, which will dictate whether it will be logged across all processes + or only the main executed one. Default is `True` if not passed + + Also accepts "in_order", which if `True` makes the processes log one by one, in order. This is much easier to + read, but comes at the cost of sometimes needing to wait for the other processes. Default is `False` to not + break with the previous behavior. + + `in_order` is ignored if `main_process_only` is passed. + """ + if PartialState._shared_state == {}: + raise RuntimeError( + "You must initialize the accelerate state by calling either `PartialState()` or `Accelerator()` before using the logging utility." + ) + main_process_only = kwargs.pop("main_process_only", True) + in_order = kwargs.pop("in_order", False) + # set `stacklevel` to exclude ourself in `Logger.findCaller()` while respecting user's choice + kwargs.setdefault("stacklevel", 2) + + if self.isEnabledFor(level): + if self._should_log(main_process_only): + msg, kwargs = self.process(msg, kwargs) + self.logger.log(level, msg, *args, **kwargs) + + elif in_order: + state = PartialState() + for i in range(state.num_processes): + if i == state.process_index: + msg, kwargs = self.process(msg, kwargs) + self.logger.log(level, msg, *args, **kwargs) + state.wait_for_everyone() + + @functools.lru_cache(None) + def warning_once(self, *args, **kwargs): + """ + This method is identical to `logger.warning()`, but will emit the warning with the same message only once + + Note: The cache is for the function arguments, so 2 different callers using the same arguments will hit the + cache. The assumption here is that all warning messages are unique across the code. If they aren't then need to + switch to another type of cache that includes the caller frame information in the hashing function. + """ + self.warning(*args, **kwargs) + + +def get_logger(name: str, log_level: str = None): + """ + Returns a `logging.Logger` for `name` that can handle multiprocessing. + + If a log should be called on all processes, pass `main_process_only=False` If a log should be called on all + processes and in order, also pass `in_order=True` + + Args: + name (`str`): + The name for the logger, such as `__file__` + log_level (`str`, *optional*): + The log level to use. If not passed, will default to the `LOG_LEVEL` environment variable, or `INFO` if not + + Example: + + ```python + >>> from accelerate.logging import get_logger + >>> from accelerate import Accelerator + + >>> logger = get_logger(__name__) + + >>> accelerator = Accelerator() + >>> logger.info("My log", main_process_only=False) + >>> logger.debug("My log", main_process_only=True) + + >>> logger = get_logger(__name__, log_level="DEBUG") + >>> logger.info("My log") + >>> logger.debug("My second log") + + >>> array = ["a", "b", "c", "d"] + >>> letter_at_rank = array[accelerator.process_index] + >>> logger.info(letter_at_rank, in_order=True) + ``` + """ + if log_level is None: + log_level = os.environ.get("ACCELERATE_LOG_LEVEL", None) + logger = logging.getLogger(name) + if log_level is not None: + logger.setLevel(log_level.upper()) + logger.root.setLevel(log_level.upper()) + return MultiProcessAdapter(logger, {}) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/memory_utils.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/memory_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..fa2e2c8b9d7d0064c3e5e282737a7ad6919bde29 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/memory_utils.py @@ -0,0 +1,22 @@ +# 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. + +import warnings + + +warnings.warn( + "memory_utils has been reorganized to utils.memory. Import `find_executable_batchsize` from the main `__init__`: " + "`from accelerate import find_executable_batch_size` to avoid this warning.", + FutureWarning, +) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/optimizer.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/optimizer.py new file mode 100644 index 0000000000000000000000000000000000000000..1c0a777dcba0a63c1cd4950c700fc87c4e5a88cc --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/optimizer.py @@ -0,0 +1,216 @@ +# 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. + +import inspect +import warnings + +import torch + +from .state import AcceleratorState, GradientState +from .utils import DistributedType, honor_type, is_lomo_available, is_torch_xla_available + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + +def move_to_device(state, device): + if isinstance(state, (list, tuple)): + return honor_type(state, (move_to_device(t, device) for t in state)) + elif isinstance(state, dict): + return type(state)({k: move_to_device(v, device) for k, v in state.items()}) + elif isinstance(state, torch.Tensor): + return state.to(device) + return state + + +class AcceleratedOptimizer(torch.optim.Optimizer): + """ + Internal wrapper around a torch optimizer. + + Conditionally will perform `step` and `zero_grad` if gradients should be synchronized when performing gradient + accumulation. + + Args: + optimizer (`torch.optim.optimizer.Optimizer`): + The optimizer to wrap. + device_placement (`bool`, *optional*, defaults to `True`): + Whether or not the optimizer should handle device placement. If so, it will place the state dictionary of + `optimizer` on the right device. + scaler (`torch.cuda.amp.grad_scaler.GradScaler`, *optional*): + The scaler to use in the step function if training with mixed precision. + """ + + def __init__(self, optimizer, device_placement=True, scaler=None): + self.optimizer = optimizer + self.scaler = scaler + self.accelerator_state = AcceleratorState() + self.gradient_state = GradientState() + self.device_placement = device_placement + self._is_overflow = False + + if self.scaler is not None: + self._accelerate_step_called = False + self._optimizer_original_step_method = self.optimizer.step + self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step) + + # Handle device placement + if device_placement: + state_dict = self.optimizer.state_dict() + if self.accelerator_state.distributed_type == DistributedType.XLA: + xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device) + else: + state_dict = move_to_device(state_dict, self.accelerator_state.device) + self.optimizer.load_state_dict(state_dict) + + @property + def state(self): + return self.optimizer.state + + @state.setter + def state(self, state): + self.optimizer.state = state + + @property + def param_groups(self): + return self.optimizer.param_groups + + @param_groups.setter + def param_groups(self, param_groups): + self.optimizer.param_groups = param_groups + + @property + def defaults(self): + return self.optimizer.defaults + + @defaults.setter + def defaults(self, defaults): + self.optimizer.defaults = defaults + + def add_param_group(self, param_group): + self.optimizer.add_param_group(param_group) + + def load_state_dict(self, state_dict): + if self.accelerator_state.distributed_type == DistributedType.XLA and self.device_placement: + xm.send_cpu_data_to_device(state_dict, self.accelerator_state.device) + self.optimizer.load_state_dict(state_dict) + + def state_dict(self): + return self.optimizer.state_dict() + + def zero_grad(self, set_to_none=None): + if self.gradient_state.sync_gradients: + accept_arg = "set_to_none" in inspect.signature(self.optimizer.zero_grad).parameters + if accept_arg: + if set_to_none is None: + set_to_none = True + self.optimizer.zero_grad(set_to_none=set_to_none) + else: + if set_to_none is not None: + raise ValueError("`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer.") + self.optimizer.zero_grad() + + def train(self): + """ + Sets the optimizer to "train" mode. Useful for optimizers like `schedule_free` + """ + if hasattr(self.optimizer, "train") and callable(self.optimizer.train): + self.optimizer.train() + + def eval(self): + """ + Sets the optimizer to "eval" mode. Useful for optimizers like `schedule_free` + """ + if hasattr(self.optimizer, "eval") and callable(self.optimizer.eval): + self.optimizer.eval() + + def step(self, closure=None): + if is_lomo_available(): + from lomo_optim import AdaLomo, Lomo + + if ( + not self.gradient_state.is_xla_gradients_synced + and self.accelerator_state.distributed_type == DistributedType.XLA + ): + gradients = xm._fetch_gradients(self.optimizer) + xm.all_reduce("sum", gradients, scale=1.0 / xm.xrt_world_size()) + self.gradient_state.is_xla_gradients_synced = True + + if is_lomo_available(): + # `step` should be a no-op for LOMO optimizers. + if isinstance(self.optimizer, (Lomo, AdaLomo)): + return + + if self.gradient_state.sync_gradients: + if self.scaler is not None: + self.optimizer.step = self._optimizer_patched_step_method + + self.scaler.step(self.optimizer, closure) + self.scaler.update() + + if not self._accelerate_step_called: + # If the optimizer step was skipped, gradient overflow was detected. + self._is_overflow = True + else: + self._is_overflow = False + # Reset the step method to the original one + self.optimizer.step = self._optimizer_original_step_method + # Reset the indicator + self._accelerate_step_called = False + else: + self.optimizer.step(closure) + if self.accelerator_state.distributed_type == DistributedType.XLA: + self.gradient_state.is_xla_gradients_synced = False + + def _switch_parameters(self, parameters_map): + for param_group in self.optimizer.param_groups: + param_group["params"] = [parameters_map.get(p, p) for p in param_group["params"]] + + @property + def is_overflow(self): + """Whether or not the optimizer step was done, or skipped because of gradient overflow.""" + warnings.warn( + "The `is_overflow` property is deprecated and will be removed in version 1.0 of Accelerate use " + "`optimizer.step_was_skipped` instead.", + FutureWarning, + ) + return self._is_overflow + + @property + def step_was_skipped(self): + """Whether or not the optimizer step was skipped.""" + return self._is_overflow + + def __getstate__(self): + _ignored_keys = [ + "_accelerate_step_called", + "_optimizer_original_step_method", + "_optimizer_patched_step_method", + ] + return {k: v for k, v in self.__dict__.items() if k not in _ignored_keys} + + def __setstate__(self, state): + self.__dict__.update(state) + if self.scaler is not None: + self._accelerate_step_called = False + self._optimizer_original_step_method = self.optimizer.step + self._optimizer_patched_step_method = patch_optimizer_step(self, self.optimizer.step) + + +def patch_optimizer_step(accelerated_optimizer: AcceleratedOptimizer, method): + def patched_step(*args, **kwargs): + accelerated_optimizer._accelerate_step_called = True + return method(*args, **kwargs) + + return patched_step diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/scheduler.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/scheduler.py new file mode 100644 index 0000000000000000000000000000000000000000..1fa8a13f238afd7b908ee8e8cb8e0620f48d4ff8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/scheduler.py @@ -0,0 +1,98 @@ +# 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. + +# We ignore warnings about stepping the scheduler since we step it ourselves during gradient accumulation + +import warnings + +from .state import AcceleratorState, GradientState + + +warnings.filterwarnings("ignore", category=UserWarning, module="torch.optim.lr_scheduler") + + +class AcceleratedScheduler: + """ + A wrapper around a learning rate scheduler that will only step when the optimizer(s) have a training step. Useful + to avoid making a scheduler step too fast when gradients went overflow and there was no training step (in mixed + precision training) + + When performing gradient accumulation scheduler lengths should not be changed accordingly, Accelerate will always + step the scheduler to account for it. + + Args: + scheduler (`torch.optim.lr_scheduler._LRScheduler`): + The scheduler to wrap. + optimizers (one or a list of `torch.optim.Optimizer`): + The optimizers used. + step_with_optimizer (`bool`, *optional*, defaults to `True`): + Whether or not the scheduler should be stepped at each optimizer step. + split_batches (`bool`, *optional*, defaults to `False`): + Whether or not the dataloaders split one batch across the different processes (so batch size is the same + regardless of the number of processes) or create batches on each process (so batch size is the original + batch size multiplied by the number of processes). + """ + + def __init__(self, scheduler, optimizers, step_with_optimizer: bool = True, split_batches: bool = False): + self.scheduler = scheduler + self.optimizers = optimizers if isinstance(optimizers, (list, tuple)) else [optimizers] + self.split_batches = split_batches + self.step_with_optimizer = step_with_optimizer + self.gradient_state = GradientState() + + def step(self, *args, **kwargs): + if not self.step_with_optimizer: + # No link between scheduler and optimizer -> just step + self.scheduler.step(*args, **kwargs) + return + + # Otherwise, first make sure the optimizer was stepped. + if not self.gradient_state.sync_gradients: + if self.gradient_state.adjust_scheduler: + self.scheduler._step_count += 1 + return + + for opt in self.optimizers: + if opt.step_was_skipped: + return + if self.split_batches: + # Split batches -> the training dataloader batch size is not changed so one step per training step + self.scheduler.step(*args, **kwargs) + else: + # Otherwise the training dataloader batch size was multiplied by `num_processes`, so we need to do + # num_processes steps per training step + num_processes = AcceleratorState().num_processes + for _ in range(num_processes): + # Special case when using OneCycle and `drop_last` was not used + if hasattr(self.scheduler, "total_steps"): + if self.scheduler._step_count <= self.scheduler.total_steps: + self.scheduler.step(*args, **kwargs) + else: + self.scheduler.step(*args, **kwargs) + + # Passthroughs + def get_last_lr(self): + return self.scheduler.get_last_lr() + + def state_dict(self): + return self.scheduler.state_dict() + + def load_state_dict(self, state_dict): + self.scheduler.load_state_dict(state_dict) + + def get_lr(self): + return self.scheduler.get_lr() + + def print_lr(self, *args, **kwargs): + return self.scheduler.print_lr(*args, **kwargs) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/state.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/state.py new file mode 100644 index 0000000000000000000000000000000000000000..37c96babb9e2f4d4c4701a6fd8c55434d5f9b217 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/state.py @@ -0,0 +1,1234 @@ +# 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. + +from __future__ import annotations + +import logging +import os +import threading +import warnings +from contextlib import contextmanager +from functools import partial +from typing import Any, Callable, Optional + +import torch + +from .utils import ( + DistributedType, + DynamoBackend, + GradientAccumulationPlugin, + check_cuda_p2p_ib_support, + check_fp8_capability, + get_ccl_version, + get_cpu_distributed_information, + get_int_from_env, + is_ccl_available, + is_datasets_available, + is_deepspeed_available, + is_fp8_available, + is_ipex_available, + is_mlu_available, + is_mps_available, + is_musa_available, + is_npu_available, + is_torch_xla_available, + is_xpu_available, + parse_choice_from_env, + parse_flag_from_env, + set_numa_affinity, +) +from .utils.dataclasses import SageMakerDistributedType + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + +if is_mlu_available(check_device=False): + import torch_mlu # noqa: F401 + +if is_musa_available(check_device=False): + import torch_musa # noqa: F401 + +if is_npu_available(check_device=False): + import torch_npu # noqa: F401 + +logger = logging.getLogger(__name__) + + +def is_initialized() -> bool: + """ + Checks if the `AcceleratorState` has been initialized from `Accelerator`. Same as `AcceleratorState.initialized`, + but works as a module method. + """ + return AcceleratorState._shared_state != {} + + +# Lambda function that does nothing +def do_nothing(*args, **kwargs): + return None + + +class ThreadLocalSharedDict(threading.local): + """ + Descriptor that holds a dict shared between instances of a class in the same thread. + + Note: Descriptors have slightly different semantics than just a dict field on its own. + `PartialState(...)._shared_state` and `PartialState._shared_state` (instance vs class) give the same value: the + underlying _storage dict. Likewise, `PartialState(...)._shared_state = {...}` overrides the _storage dict inside + the descriptor as you would expect. However, `PartialState._shared_state = {}` actually replaces the descriptor + object with a dict instead Thus, you should modify the _storage dict in-place (e.g. `_shared_state.clear()`). + + See Python documentation for an explanation of descriptors: https://docs.python.org/3/howto/descriptor.html + + This is required for using PyTorch/XLA with PJRT in multithreaded mode (required for TPU v2 and v3). + + See https://github.com/pytorch/xla/blob/r2.0/docs/pjrt.md#multithreading-on-tpu-v2v3 + """ + + def __init__(self, thread_local: bool = False): + self._storage = {} + + def __get__(self, obj, objtype=None): + return self._storage + + def __set__(self, obj, value): + self._storage = value + + +# Prefer global shared dictionary, except when using TPU. +SharedDict = dict if not is_torch_xla_available() else ThreadLocalSharedDict + + +# Inspired by Alex Martelli's 'Borg'. +class PartialState: + """ + Singleton class that has information about the current training environment and functions to help with process + control. Designed to be used when only process control and device execution states are needed. Does *not* need to + be initialized from `Accelerator`. + + Args: + cpu (`bool`, *optional*): + Whether or not to force the script to execute on CPU. Will ignore any accelerators available if set to + `True` and force the execution on the CPU. + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments to pass to the relevent `init_process_group` function. Valid `kwargs` can be + found in [`utils.InitProcessGroupKwargs`]. See the example section for detailed usage. + + **Available attributes:** + + - **device** (`torch.device`) -- The device to use. + - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently + in use. + - **local_process_index** (`int`) -- The index of the current process on the current server. + - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type + of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8'). + - **num_processes** (`int`) -- The number of processes currently launched in parallel. + - **process_index** (`int`) -- The index of the current process. + - **is_last_process** (`bool`) -- Whether or not the current process is the last one. + - **is_main_process** (`bool`) -- Whether or not the current process is the main one. + - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node. + - **debug** (`bool`) -- Whether or not the current script is being run in debug mode. + + Example: + ```python + from accelerate.utils import InitProcessGroupKwargs + + # To include `InitProcessGroupKwargs`, init then call `.to_kwargs()` + kwargs = InitProcessGroupKwargs(...).to_kwargs() + state = PartialState(**kwargs) + ``` + """ + + _shared_state = SharedDict() + _known_attrs = [ + "_cpu", + "_mixed_precision", + "_shared_state", + "backend", + "debug", + "device", + "distributed_type", + "fork_launched", + "local_process_index", + "num_processes", + "process_index", + ] + + def __init__(self, cpu: bool = False, **kwargs): + self.__dict__ = self._shared_state + if not self.initialized: + self._cpu = cpu + self.backend = None + env_device = os.environ.get("ACCELERATE_TORCH_DEVICE", None) + self.device = torch.device(env_device) if env_device is not None else None + self.debug = parse_flag_from_env("ACCELERATE_DEBUG_MODE") + use_sagemaker_dp = kwargs.pop("_use_sagemaker_dp", None) + dist_information = None + if use_sagemaker_dp is None: + use_sagemaker_dp = ( + os.environ.get("ACCELERATE_USE_SAGEMAKER", "false") == "true" + and os.environ.get("ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE") != SageMakerDistributedType.NO + ) + + # Sets up self.backend + imports + original_backend = kwargs.pop("backend", None) + backend, distributed_type = self._prepare_backend(cpu, use_sagemaker_dp, original_backend) + if original_backend is not None and backend != original_backend: + raise ValueError(f"Your assigned backend {original_backend} is not avaliable, please use {backend}") + self.backend = backend + self.distributed_type = distributed_type + use_deepspeed = False + if not cpu and self.backend != "xla": + if int(os.environ.get("LOCAL_RANK", -1)) != -1: + # Deal with spawning deepspeed + if os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true": + if not is_deepspeed_available(): + raise ImportError( + "DeepSpeed is not available => install it using `pip3 install deepspeed` or build it from source" + ) + from deepspeed import comm as dist + + if not dist.is_initialized(): + dist.init_distributed(dist_backend=self.backend, auto_mpi_discovery=False, **kwargs) + # We need to flag to `use_deepspeed` to be True to override `distributed_type` later + use_deepspeed = True + # Deal with all other backends but XPU and CPU, that gets handled special later + elif ( + self.distributed_type not in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU) + and not torch.distributed.is_initialized() + ): + torch.distributed.init_process_group(backend=self.backend, **kwargs) + # XPU and CPU require special env configs to be set + if self.distributed_type in (DistributedType.MULTI_XPU, DistributedType.MULTI_CPU): + dist_information = get_cpu_distributed_information() + os.environ["RANK"] = str(dist_information.rank) + os.environ["WORLD_SIZE"] = str(dist_information.world_size) + os.environ["LOCAL_RANK"] = str(dist_information.local_rank) + os.environ["LOCAL_WORLD_SIZE"] = str(dist_information.local_world_size) + if not os.environ.get("MASTER_PORT", None): + os.environ["MASTER_PORT"] = "29500" + if ( + not os.environ.get("MASTER_ADDR", None) + and dist_information.local_world_size != dist_information.world_size + and self.backend != "mpi" + ): + raise ValueError( + "Tried to launch on distributed with multinode, but `MASTER_ADDR` env was not set, " + "please try exporting rank 0's hostname as `MASTER_ADDR`" + ) + kwargs["rank"] = dist_information.rank + kwargs["world_size"] = dist_information.world_size + + if ( + self.distributed_type == DistributedType.MULTI_CPU + and get_int_from_env(["OMP_NUM_THREADS"], 0) == 0 + ): + import psutil + + num_cpu_threads_per_process = int( + psutil.cpu_count(logical=False) / dist_information.local_world_size + ) + if num_cpu_threads_per_process == 0: + num_cpu_threads_per_process = 1 + torch.set_num_threads(num_cpu_threads_per_process) + warnings.warn( + f"OMP_NUM_THREADS/MKL_NUM_THREADS unset, we set it at {num_cpu_threads_per_process} to improve oob" + " performance." + ) + + if not torch.distributed.is_initialized(): + torch.distributed.init_process_group(backend=self.backend, **kwargs) + + # No backend == no distributed training + if self.backend is None: + self.distributed_type = DistributedType.NO + self.num_processes = 1 + self.process_index = 0 + self.local_process_index = 0 + elif self.backend == "xla": + # XLA needs device setting first for `set_replication` + self.set_device() + xm.set_replication(self.device, xm.get_xla_supported_devices()) + self.num_processes = xm.xrt_world_size() + self.process_index = xm.get_ordinal() + if is_torch_xla_available(check_is_tpu=True): + self.local_process_index = xm.get_local_ordinal() + else: + self.local_process_index = int(os.environ.get("LOCAL_RANK", -1)) + else: + self.num_processes = torch.distributed.get_world_size() + self.process_index = torch.distributed.get_rank() + self.local_process_index = ( + int(os.environ.get("LOCAL_RANK", -1)) if dist_information is None else dist_information.local_rank + ) + self.set_device() + # Now we can change to deepseed + if use_deepspeed: + self.distributed_type = DistributedType.DEEPSPEED + + # Set CPU affinity if enabled + if parse_flag_from_env("ACCELERATE_CPU_AFFINITY", False): + set_numa_affinity(self.local_process_index) + + # Check for old RTX 4000's that can't use P2P or IB and are on old drivers + if self.device.type == "cuda" and not check_cuda_p2p_ib_support(): + if "NCCL_P2P_DISABLE" not in os.environ or "NCCL_IB_DISABLE" not in os.environ: + raise NotImplementedError( + "Using RTX 4000 series doesn't support faster communication broadband via P2P or IB. " + 'Please set `NCCL_P2P_DISABLE="1"` and `NCCL_IB_DISABLE="1" or use `accelerate launch` which ' + "will do this automatically." + ) + # Important: This should be the *only* code outside of `self.initialized!` + self.fork_launched = parse_flag_from_env("FORK_LAUNCHED", 0) + + def __repr__(self) -> str: + return ( + f"Distributed environment: {self.distributed_type}{(' Backend: ' + self.backend) if self.backend else ''}\n" + f"Num processes: {self.num_processes}\n" + f"Process index: {self.process_index}\n" + f"Local process index: {self.local_process_index}\n" + f"Device: {self.device}\n" + ) + + @staticmethod + def _reset_state(): + "Resets `_shared_state`, is used internally and should not be called" + PartialState._shared_state.clear() + + @property + def initialized(self) -> bool: + "Returns whether the `PartialState` has been initialized" + return self._shared_state != {} + + @property + def use_distributed(self): + """ + Whether the Accelerator is configured for distributed training + """ + return self.distributed_type != DistributedType.NO and self.num_processes > 1 + + @property + def is_last_process(self) -> bool: + "Returns whether the current process is the last one" + return self.process_index == self.num_processes - 1 + + @property + def is_main_process(self) -> bool: + "Returns whether the current process is the main process" + return ( + self.process_index == 0 if self.distributed_type != DistributedType.MEGATRON_LM else self.is_last_process + ) + + @property + def is_local_main_process(self) -> bool: + "Returns whether the current process is the main process on the local node" + return ( + self.local_process_index == 0 + if self.distributed_type != DistributedType.MEGATRON_LM + else self.is_last_process + ) + + def wait_for_everyone(self): + """ + Will stop the execution of the current process until every other process has reached that point (so this does + nothing when the script is only run in one process). Useful to do before saving a model. + + Example: + + ```python + >>> # Assuming two GPU processes + >>> import time + >>> from accelerate.state import PartialState + + >>> state = PartialState() + >>> if state.is_main_process: + ... time.sleep(2) + >>> else: + ... print("I'm waiting for the main process to finish its sleep...") + >>> state.wait_for_everyone() + >>> # Should print on every process at the same time + >>> print("Everyone is here") + ``` + """ + if self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_CPU, + DistributedType.DEEPSPEED, + DistributedType.FSDP, + ): + torch.distributed.barrier() + elif self.distributed_type == DistributedType.XLA: + xm.rendezvous("accelerate.utils.wait_for_everyone") + + def _goes_first(self, is_main: bool): + if not is_main: + self.wait_for_everyone() + + yield + + if is_main: + self.wait_for_everyone() + + @contextmanager + def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False): + """ + Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing + distributed inference, such as with different prompts. + + Note that when using a `dict`, all keys need to have the same number of elements. + + Args: + inputs (`list`, `tuple`, `torch.Tensor`, `dict` of `list`/`tuple`/`torch.Tensor`, or `datasets.Dataset`): + The input to split between processes. + apply_padding (`bool`, `optional`, defaults to `False`): + Whether to apply padding by repeating the last element of the input so that all processes have the same + number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing + in less inputs than there are processes. If so, just remember to drop the padded elements afterwards. + + + Example: + + ```python + # Assume there are two processes + from accelerate import PartialState + + state = PartialState() + with state.split_between_processes(["A", "B", "C"]) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C"] + + with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C", "C"] + ``` + """ + if self.num_processes == 1: + yield inputs + return + length = len(inputs) + # Nested dictionary of any types + if isinstance(inputs, dict): + length = len(inputs[list(inputs.keys())[0]]) + if not all(len(v) == length for v in inputs.values()): + raise ValueError("All values in the dictionary must have the same length") + num_samples_per_process, num_extras = divmod(length, self.num_processes) + start_index = self.process_index * num_samples_per_process + min(self.process_index, num_extras) + end_index = start_index + num_samples_per_process + (1 if self.process_index < num_extras else 0) + + def _split_values(inputs, start_index, end_index): + if isinstance(inputs, (list, tuple, torch.Tensor)): + if start_index >= len(inputs): + result = inputs[-1:] + else: + result = inputs[start_index:end_index] + if apply_padding: + if isinstance(result, torch.Tensor): + from accelerate.utils import pad_across_processes, send_to_device + + # The tensor needs to be on the device before we can pad it + tensorized_result = send_to_device(result, self.device) + result = pad_across_processes(tensorized_result, pad_index=inputs[-1]) + else: + result += [result[-1]] * (num_samples_per_process + 1 - len(result)) + return result + elif isinstance(inputs, dict): + for key in inputs.keys(): + inputs[key] = _split_values(inputs[key], start_index, end_index) + return inputs + else: + if is_datasets_available(): + from datasets import Dataset + + if isinstance(inputs, Dataset): + if start_index >= len(inputs): + start_index = len(inputs) - 1 + if end_index > len(inputs): + end_index = len(inputs) + result_idcs = list(range(start_index, end_index)) + if apply_padding: + result_idcs += [end_index - 1] * (num_samples_per_process + 1 - len(result_idcs)) + return inputs.select(result_idcs) + return inputs + + yield _split_values(inputs, start_index, end_index) + + @contextmanager + def main_process_first(self): + """ + Lets the main process go first inside a with block. + + The other processes will enter the with block after the main process exits. + + Example: + + ```python + >>> from accelerate import Accelerator + + >>> accelerator = Accelerator() + >>> with accelerator.main_process_first(): + ... # This will be printed first by process 0 then in a seemingly + ... # random order by the other processes. + ... print(f"This will be printed by process {accelerator.process_index}") + ``` + """ + yield from self._goes_first(self.is_main_process) + + @contextmanager + def local_main_process_first(self): + """ + Lets the local main process go inside a with block. + + The other processes will enter the with block after the main process exits. + + Example: + + ```python + >>> from accelerate.state import PartialState + + >>> state = PartialState() + >>> with state.local_main_process_first(): + ... # This will be printed first by local process 0 then in a seemingly + ... # random order by the other processes. + ... print(f"This will be printed by process {state.local_process_index}") + ``` + """ + yield from self._goes_first(self.is_local_main_process) + + def on_main_process(self, function: Callable[..., Any] = None): + """ + Decorator that only runs the decorated function on the main process. + + Args: + function (`Callable`): The function to decorate. + + Example: + + ```python + >>> from accelerate.state import PartialState + + >>> state = PartialState() + + + >>> @state.on_main_process + ... def print_something(): + ... print("This will be printed by process 0 only.") + + + >>> print_something() + "This will be printed by process 0 only" + ``` + """ + if not self.initialized: + raise ValueError("The `PartialState` or `Accelerator` must be initialized before calling this function.") + if self.is_main_process or not self.use_distributed: + return function + return do_nothing + + def on_local_main_process(self, function: Callable[..., Any] = None): + """ + Decorator that only runs the decorated function on the local main process. + + Args: + function (`Callable`): The function to decorate. + + Example: + ```python + # Assume we have 2 servers with 4 processes each. + from accelerate.state import PartialState + + state = PartialState() + + + @state.on_local_main_process + def print_something(): + print("This will be printed by process 0 only on each server.") + + + print_something() + # On server 1: + "This will be printed by process 0 only" + # On server 2: + "This will be printed by process 0 only" + ``` + """ + if self.is_local_main_process or not self.use_distributed: + return function + return do_nothing + + def on_last_process(self, function: Callable[..., Any]): + """ + Decorator that only runs the decorated function on the last process. + + Args: + function (`Callable`): The function to decorate. + + Example: + ```python + # Assume we have 4 processes. + from accelerate.state import PartialState + + state = PartialState() + + + @state.on_last_process + def print_something(): + print(f"Printed on process {state.process_index}") + + + print_something() + "Printed on process 3" + ``` + """ + if self.is_last_process or not self.use_distributed: + return function + return do_nothing + + def on_process(self, function: Callable[..., Any] = None, process_index: int = None): + """ + Decorator that only runs the decorated function on the process with the given index. + + Args: + function (`Callable`, `optional`): + The function to decorate. + process_index (`int`, `optional`): + The index of the process on which to run the function. + + Example: + ```python + # Assume we have 4 processes. + from accelerate.state import PartialState + + state = PartialState() + + + @state.on_process(process_index=2) + def print_something(): + print(f"Printed on process {state.process_index}") + + + print_something() + "Printed on process 2" + ``` + """ + if function is None: + return partial(self.on_process, process_index=process_index) + if (self.process_index == process_index) or (not self.use_distributed): + return function + return do_nothing + + def on_local_process(self, function: Callable[..., Any] = None, local_process_index: int = None): + """ + Decorator that only runs the decorated function on the process with the given index on the current node. + + Args: + function (`Callable`, *optional*): + The function to decorate. + local_process_index (`int`, *optional*): + The index of the local process on which to run the function. + + Example: + ```python + # Assume we have 2 servers with 4 processes each. + from accelerate import Accelerator + + accelerator = Accelerator() + + + @accelerator.on_local_process(local_process_index=2) + def print_something(): + print(f"Printed on process {accelerator.local_process_index}") + + + print_something() + # On server 1: + "Printed on process 2" + # On server 2: + "Printed on process 2" + ``` + """ + if function is None: + return partial(self.on_local_process, local_process_index=local_process_index) + if (self.local_process_index == local_process_index) or (not self.use_distributed): + return function + return do_nothing + + def print(self, *args, **kwargs): + if self.is_local_main_process: + print(*args, **kwargs) + + @property + def default_device(self) -> torch.device: + """ + Returns the default device which is: + - MPS if `torch.backends.mps.is_available()` and `torch.backends.mps.is_built()` both return True. + - CUDA if `torch.cuda.is_available()` + - MLU if `is_mlu_available()` + - MUSA if `is_musa_available()` + - NPU if `is_npu_available()` + - CPU otherwise + """ + if is_mps_available(): + os.environ["PYTORCH_ENABLE_MPS_FALLBACK"] = "1" + return torch.device("mps") + elif is_mlu_available(): + return torch.device("mlu") + elif is_musa_available(): + return torch.device("musa") + # NPU should be checked before CUDA when using `transfer_to_npu` + # See issue #3020: https://github.com/huggingface/accelerate/issues/3020 + elif is_npu_available(): + return torch.device("npu") + elif torch.cuda.is_available(): + return torch.device("cuda") + elif is_xpu_available(): + return torch.device("xpu:0") + else: + return torch.device("cpu") + + def _prepare_backend( + self, cpu: bool = False, sagemaker_dp=False, backend: str = None + ) -> tuple[str, DistributedType]: + "Prepares any imports needed before initializing the distributed backend and sets `self.backend` properly" + distributed_type = None + if sagemaker_dp: + import smdistributed.dataparallel.torch.torch_smddp # noqa + + backend = "smddp" + distributed_type = DistributedType.MULTI_GPU + elif is_torch_xla_available(): + backend = "xla" + distributed_type = DistributedType.XLA + elif int(os.environ.get("LOCAL_RANK", -1)) != -1 and not cpu: + if is_mlu_available(): + backend = "cncl" + distributed_type = DistributedType.MULTI_MLU + elif is_musa_available(): + backend = "mccl" + distributed_type = DistributedType.MULTI_MUSA + # NPU should be checked before CUDA when using `transfer_to_npu` + # See issue #3020: https://github.com/huggingface/accelerate/issues/3020 + elif is_npu_available(): + backend = "hccl" + distributed_type = DistributedType.MULTI_NPU + elif torch.cuda.is_available(): + if backend is None: + backend = "nccl" + distributed_type = DistributedType.MULTI_GPU + + if distributed_type is None and ( + int(os.environ.get("LOCAL_RANK", -1)) != -1 + or get_int_from_env(["PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE", "WORLD_SIZE"], 1) > 1 + ): + if not cpu and is_xpu_available(): + distributed_type = DistributedType.MULTI_XPU + else: + distributed_type = DistributedType.MULTI_CPU + + if ( + backend in (None, "ccl") + and is_ccl_available() + and (get_int_from_env(["CCL_WORKER_COUNT"], 0) > 0 or distributed_type == DistributedType.MULTI_XPU) + ): + if get_ccl_version() >= "1.12": + import oneccl_bindings_for_pytorch # noqa: F401 + else: + import torch_ccl # noqa: F401 + + backend = "ccl" + elif backend in (None, "mpi") and torch.distributed.is_mpi_available(): + backend = "mpi" + else: + backend = "gloo" + if distributed_type is None: + distributed_type = DistributedType.NO + + return backend, distributed_type + + def set_device(self): + """ + Sets the device in `self.device` to the current distributed environment. + """ + if self.device is not None: + return + if self.distributed_type == DistributedType.NO: + self.device = torch.device("cpu") if self._cpu else self.default_device + return + device = str(self.distributed_type).split(".")[-1].replace("MULTI_", "").lower() + if device not in ("cpu", "gpu", "mlu", "musa", "npu", "xpu", "xla"): + raise ValueError( + f"Can't set device for {self.distributed_type} ({device}), verify we should be calling `_set_device()` for it!" + ) + if device == "xla": + self.device = xm.xla_device() + else: + if device == "gpu": + device = "cuda" + device_module = getattr(torch, device) + device_index = self.local_process_index % device_module.device_count() + self.device = torch.device(device, device_index) + device_module.set_device(self.device) + + def destroy_process_group(self, group=None): + """ + Destroys the process group. If one is not specified, the default process group is destroyed. + """ + if self.fork_launched and group is None: + return + # needed when using torch.distributed.init_process_group + if torch.distributed.is_initialized(): + torch.distributed.destroy_process_group(group) + + def __getattr__(self, name: str): + # By this point we know that no attributes of `self` contain `name`, + # so we just modify the error message + if name in self._known_attrs: + raise AttributeError( + f"`PartialState` object has no attribute `{name}`. " + "This happens if `PartialState._reset_state()` was called and " + "an `Accelerator` or `PartialState` was not reinitialized." + ) + # Raise a typical AttributeError + raise AttributeError(f"'PartialState' object has no attribute '{name}'") + + +class AcceleratorState: + """ + Singleton class that has information about the current training environment. + + **Available attributes:** + + - **device** (`torch.device`) -- The device to use. + - **distributed_type** ([`~accelerate.state.DistributedType`]) -- The type of distributed environment currently + in use. + - **initialized** (`bool`) -- Whether or not the `AcceleratorState` has been initialized from `Accelerator`. + - **local_process_index** (`int`) -- The index of the current process on the current server. + - **mixed_precision** (`str`) -- Whether or not the current script will use mixed precision, and if so the type + of mixed precision being performed. (Choose from 'no','fp16','bf16 or 'fp8'). + - **num_processes** (`int`) -- The number of processes currently launched in parallel. + - **process_index** (`int`) -- The index of the current process. + - **is_last_process** (`bool`) -- Whether or not the current process is the last one. + - **is_main_process** (`bool`) -- Whether or not the current process is the main one. + - **is_local_main_process** (`bool`) -- Whether or not the current process is the main one on the local node. + - **debug** (`bool`) -- Whether or not the current script is being run in debug mode. + """ + + _shared_state = SharedDict() + _known_attrs = PartialState._known_attrs + [ + "deepspeed_plugin", + "use_ipex", + "fsdp_plugin", + "megatron_lm_plugin", + "dynamo_plugin", + ] + + def __init__( + self, + mixed_precision: str = None, + cpu: bool = False, + dynamo_plugin=None, + deepspeed_plugin=None, + fsdp_plugin=None, + megatron_lm_plugin=None, + _from_accelerator: bool = False, + **kwargs, + ): + self.__dict__ = self._shared_state + if parse_flag_from_env("ACCELERATE_USE_CPU"): + cpu = True + if PartialState._shared_state == {}: + PartialState(cpu, **kwargs) + self.__dict__.update(PartialState._shared_state) + self._check_initialized(mixed_precision, cpu) + if not self.initialized: + self.deepspeed_plugin = None + self.use_ipex = None + mixed_precision = ( + parse_choice_from_env("ACCELERATE_MIXED_PRECISION", "no") + if mixed_precision is None + else mixed_precision.lower() + ) + if mixed_precision == "fp8": + if not is_fp8_available(): + raise ValueError( + "Using `fp8` precision requires `transformer_engine` or `MS-AMP` to be installed." + ) + elif not check_fp8_capability(): + logger.warning( + f"The current device has compute capability of {torch.cuda.get_device_capability()} which is " + "insufficient for FP8 mixed precision training (requires a GPU Hopper/Ada Lovelace " + "or higher, compute capability of 8.9 or higher). Will use FP16 instead." + ) + mixed_precision = "fp16" + + self.dynamo_plugin = dynamo_plugin + if not _from_accelerator: + raise ValueError( + "Please make sure to properly initialize your accelerator via `accelerator = Accelerator()` " + "before using any functionality from the `accelerate` library." + ) + # deepspeed handles mixed_precision using deepspeed_config + self._mixed_precision = "no" if self.distributed_type == DistributedType.DEEPSPEED else mixed_precision + if self.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_tpu=True): + if mixed_precision == "bf16": + if os.environ.get("ACCELERATE_DOWNCAST_BF16"): + os.environ["XLA_USE_BF16"] = str(0) + os.environ["XLA_DOWNCAST_BF16"] = str(1) + self.downcast_bfloat = True + else: + os.environ["XLA_USE_BF16"] = str(1) + os.environ["XLA_DOWNCAST_BF16"] = str(0) + self.downcast_bfloat = False + elif os.environ.get("ACCELERATE_USE_DEEPSPEED", "false") == "true" and not cpu: + self.deepspeed_plugin = deepspeed_plugin + elif self.distributed_type in [ + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + ]: + if os.environ.get("ACCELERATE_USE_FSDP", "false") == "true" or fsdp_plugin is not None: + self.distributed_type = DistributedType.FSDP + if self._mixed_precision != "no": + fsdp_plugin.set_mixed_precision(self._mixed_precision) + self.fsdp_plugin = fsdp_plugin + if os.environ.get("ACCELERATE_USE_MEGATRON_LM", "false") == "true" and self.distributed_type not in [ + DistributedType.MULTI_XPU, + ]: + self.distributed_type = DistributedType.MEGATRON_LM + megatron_lm_plugin.set_mixed_precision(self._mixed_precision) + self.megatron_lm_plugin = megatron_lm_plugin + elif self.distributed_type in [DistributedType.MULTI_CPU, DistributedType.MULTI_XPU, DistributedType.NO]: + if is_ipex_available(): + # check if user disables it explicitly + self.use_ipex = parse_flag_from_env("ACCELERATE_USE_IPEX", default=True) + else: + self.use_ipex = False + if ( + self.dynamo_plugin.backend != DynamoBackend.NO + and self._mixed_precision == "no" + and self.device.type == "cuda" + ): + torch.backends.cuda.matmul.allow_tf32 = True + if ( + self.dynamo_plugin.backend != DynamoBackend.NO + and self._mixed_precision == "no" + and self.device.type == "musa" + ): + torch.backends.musa.matmul.allow_tf32 = True + PartialState._shared_state["distributed_type"] = self.distributed_type + + @property + def initialized(self) -> bool: + return self._shared_state != PartialState._shared_state + + def __repr__(self): + repr = PartialState().__repr__() + f"\nMixed precision type: {self.mixed_precision}\n" + if self.distributed_type == DistributedType.DEEPSPEED: + repr += f"ds_config: {self.deepspeed_plugin.deepspeed_config}\n" + return repr + + def _check_initialized(self, mixed_precision=None, cpu=None): + "Checks if a modification is trying to be made and the `AcceleratorState` has already been initialized" + if self.initialized: + err = "AcceleratorState has already been initialized and cannot be changed, restart your runtime completely and pass `{flag}` to `Accelerator()`." + if cpu and self.device.type != "cpu": + raise ValueError(err.format(flag="cpu=True")) + if ( + mixed_precision is not None + and mixed_precision != self._mixed_precision + and self.distributed_type != DistributedType.DEEPSPEED + ): + raise ValueError(err.format(flag=f"mixed_precision='{mixed_precision}'")) + + # For backward compatibility + @property + def use_fp16(self): + warnings.warn( + "The `use_fp16` property is deprecated and will be removed in version 1.0 of Accelerate use " + "`AcceleratorState.mixed_precision == 'fp16'` instead.", + FutureWarning, + ) + return self._mixed_precision != "no" + + @property + def mixed_precision(self): + if self.distributed_type == DistributedType.DEEPSPEED: + config = self.deepspeed_plugin.deepspeed_config + if config.get("fp16", {}).get("enabled", False): + mixed_precision = "fp16" + elif config.get("bf16", {}).get("enabled", False): + mixed_precision = "bf16" + else: + mixed_precision = "no" + else: + mixed_precision = self._mixed_precision + return mixed_precision + + @staticmethod + def _reset_state(reset_partial_state: bool = False): + "Resets `_shared_state`, is used internally and should not be called" + AcceleratorState._shared_state.clear() + if reset_partial_state: + PartialState._reset_state() + + def destroy_process_group(self, group=None): + """ + Destroys the process group. If one is not specified, the default process group is destroyed. + + If `self.fork_lauched` is `True` and `group` is `None`, nothing happens. + """ + PartialState().destroy_process_group(group) + + @property + def fork_launched(self): + return PartialState().fork_launched + + @property + def use_distributed(self): + """ + Whether the Accelerator is configured for distributed training + """ + return PartialState().use_distributed + + @property + def is_last_process(self) -> bool: + "Returns whether the current process is the last one" + return PartialState().is_last_process + + @property + def is_main_process(self) -> bool: + "Returns whether the current process is the main process" + return PartialState().is_main_process + + @property + def is_local_main_process(self) -> bool: + "Returns whether the current process is the main process on the local node" + return PartialState().is_local_main_process + + def wait_for_everyone(self): + PartialState().wait_for_everyone() + + @contextmanager + def split_between_processes(self, inputs: list | tuple | dict | torch.Tensor, apply_padding: bool = False): + """ + Splits `input` between `self.num_processes` quickly and can be then used on that process. Useful when doing + distributed inference, such as with different prompts. + + Note that when using a `dict`, all keys need to have the same number of elements. + + Args: + inputs (`list`, `tuple`, `torch.Tensor`, or `dict` of `list`/`tuple`/`torch.Tensor`): + The input to split between processes. + apply_padding (`bool`, `optional`, defaults to `False`): + Whether to apply padding by repeating the last element of the input so that all processes have the same + number of elements. Useful when trying to perform actions such as `gather()` on the outputs or passing + in less inputs than there are processes. If so, just remember to drop the padded elements afterwards. + + + Example: + + ```python + # Assume there are two processes + from accelerate.state import AcceleratorState + + state = AcceleratorState() + with state.split_between_processes(["A", "B", "C"]) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C"] + + with state.split_between_processes(["A", "B", "C"], apply_padding=True) as inputs: + print(inputs) + # Process 0 + ["A", "B"] + # Process 1 + ["C", "C"] + ``` + """ + with PartialState().split_between_processes(inputs, apply_padding=apply_padding) as inputs: + yield inputs + + @contextmanager + def main_process_first(self): + """ + Lets the main process go first inside a with block. + + The other processes will enter the with block after the main process exits. + """ + with PartialState().main_process_first(): + yield + + @contextmanager + def local_main_process_first(self): + """ + Lets the local main process go inside a with block. + + The other processes will enter the with block after the main process exits. + """ + with PartialState().local_main_process_first(): + yield + + def print(self, *args, **kwargs): + PartialState().print(*args, **kwargs) + + def __getattr__(self, name: str): + # By this point we know that no attributes of `self` contain `name`, + # so we just modify the error message + if name in self._known_attrs: + raise AttributeError( + f"`AcceleratorState` object has no attribute `{name}`. " + "This happens if `AcceleratorState._reset_state()` was called and " + "an `Accelerator` or `PartialState` was not reinitialized." + ) + # Raise a typical AttributeError + raise AttributeError(f"'AcceleratorState' object has no attribute '{name}'") + + +class GradientState: + """ + Singleton class that has information related to gradient synchronization for gradient accumulation + + **Available attributes:** + + - **end_of_dataloader** (`bool`) -- Whether we have reached the end the current dataloader + - **remainder** (`int`) -- The number of extra samples that were added from padding the dataloader + - **sync_gradients** (`bool`) -- Whether the gradients should be synced across all devices + - **active_dataloader** (`Optional[DataLoader]`) -- The dataloader that is currently being iterated over + - **dataloader_references** (`List[Optional[DataLoader]]`) -- A list of references to the dataloaders that are + being iterated over + - **num_steps** (`int`) -- The number of steps to accumulate over + - **adjust_scheduler** (`bool`) -- Whether the scheduler should be adjusted to account for the gradient + accumulation + - **sync_with_dataloader** (`bool`) -- Whether the gradients should be synced at the end of the dataloader + iteration and the number of total steps reset + - **is_xla_gradients_synced** (`bool`) -- Whether the XLA gradients have been synchronized. It is initialized + as false. Once gradients have been reduced before the optimizer step, this flag is set to true. Subsequently, + after each step, the flag is reset to false. FSDP will always synchronize the gradients, hence + is_xla_gradients_synced is always true. + """ + + _shared_state = SharedDict() + + def __init__(self, gradient_accumulation_plugin: Optional[GradientAccumulationPlugin] = None): + self.__dict__ = self._shared_state + if not self.initialized: + self.sync_gradients = True + self.active_dataloader = None + self.dataloader_references = [None] + self.plugin_kwargs = ( + gradient_accumulation_plugin.to_kwargs() if gradient_accumulation_plugin is not None else {} + ) + self._is_xla_gradients_synced = False + + # Plugin args are different and can be updated + if gradient_accumulation_plugin is not None and self.plugin_kwargs != gradient_accumulation_plugin.to_kwargs(): + self.plugin_kwargs = gradient_accumulation_plugin.to_kwargs() + + @property + def num_steps(self) -> int: + "Returns the number of steps to accumulate over" + return self.plugin_kwargs.get("num_steps", 1) + + @property + def adjust_scheduler(self) -> bool: + "Returns whether the scheduler should be adjusted" + return self.plugin_kwargs.get("adjust_scheduler", False) + + @property + def sync_with_dataloader(self) -> bool: + "Returns whether the gradients should be synced at the end of the dataloader iteration and the number of total steps reset" + return self.plugin_kwargs.get("sync_with_dataloader", True) + + @property + def initialized(self) -> bool: + "Returns whether the `GradientState` has been initialized" + return GradientState._shared_state != {} + + @property + def end_of_dataloader(self) -> bool: + "Returns whether we have reached the end of the current dataloader" + if not self.in_dataloader: + return False + return self.active_dataloader.end_of_dataloader + + @property + def remainder(self) -> int: + "Returns the number of extra samples that were added from padding the dataloader" + if not self.in_dataloader: + return -1 + return self.active_dataloader.remainder + + def __repr__(self): + return ( + f"Sync Gradients: {self.sync_gradients}\n" + f"At end of current dataloader: {self.end_of_dataloader}\n" + f"Extra samples added: {self.remainder}\n" + f"Gradient accumulation plugin: {self.plugin_kwargs}\n" + ) + + @property + def is_xla_gradients_synced(self): + "Returns the value of is_xla_gradients_synced. FSDP will always synchronize the gradients, hence is_xla_gradients_synced is always true." + if parse_flag_from_env("ACCELERATE_USE_FSDP", default=False): + return True + return self._is_xla_gradients_synced + + @is_xla_gradients_synced.setter + def is_xla_gradients_synced(self, is_synced): + "Set the _is_xla_gradients_synced attribute." + self._is_xla_gradients_synced = is_synced + + def _set_sync_gradients(self, sync_gradients): + "Private function that sets whether gradients should be synchronized. Users should not have to call this." + self.sync_gradients = sync_gradients + # Allow grad-sync to automatically work on TPUs + if ( + self.sync_gradients + and is_torch_xla_available(check_is_tpu=True) + and PartialState().distributed_type == DistributedType.XLA + ): + xm.mark_step() + + def _add_dataloader(self, dataloader): + "Private function that adds a dataloader to `self.dataloader_references` and sets `in_dataloader` to `True`. Users should not have to call this." + self.active_dataloader = dataloader + self.dataloader_references.append(self.active_dataloader) + + def _remove_dataloader(self, dataloader): + "Private function that removes a dataloader from `self.dataloader_references` and sets `in_dataloader` to `False` if there are no more dataloaders. Users should not have to call this." + self.dataloader_references.remove(dataloader) + self.active_dataloader = self.dataloader_references[-1] + + @property + def in_dataloader(self) -> bool: + "Returns whether the current process is in a dataloader" + return self.active_dataloader is not None + + @staticmethod + def _reset_state(): + "Resets `_shared_state`, is used internally and should not be called" + GradientState._shared_state.clear() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/__init__.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e07f52647694a813fbaf1e043d350f65001cae73 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/__init__.py @@ -0,0 +1,54 @@ +# 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. +from .testing import ( + DEFAULT_LAUNCH_COMMAND, + are_the_same_tensors, + assert_exception, + capture_call_output, + device_count, + execute_subprocess_async, + get_launch_command, + memory_allocated_func, + path_in_accelerate_package, + require_bnb, + require_cpu, + require_cuda, + require_huggingface_suite, + require_mlu, + require_mps, + require_multi_device, + require_multi_gpu, + require_multi_xpu, + require_musa, + require_non_cpu, + require_non_torch_xla, + require_non_xpu, + require_npu, + require_pippy, + require_single_device, + require_single_gpu, + require_single_xpu, + require_torch_min_version, + require_torchvision, + require_tpu, + require_transformer_engine, + require_xpu, + skip, + slow, + torch_device, +) +from .training import RegressionDataset, RegressionModel, RegressionModel4XPU + + +from .scripts import test_script, test_sync, test_ops # isort: skip diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/examples.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/examples.py new file mode 100644 index 0000000000000000000000000000000000000000..ed41d38c9092385ba9730472aa10b5208f48c67b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/examples.py @@ -0,0 +1,146 @@ +#!/usr/bin/env python + +# 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. +""" +A collection of utilities for comparing `examples/complete_*_example.py` scripts with the capabilities inside of each +`examples/by_feature` example. `compare_against_test` is the main function that should be used when testing, while the +others are used to either get the code that matters, or to preprocess them (such as stripping comments) +""" + +import os +from typing import List + + +def get_function_contents_by_name(lines: List[str], name: str): + """ + Extracts a function from `lines` of segmented source code with the name `name`. + + Args: + lines (`List[str]`): + Source code of a script seperated by line. + name (`str`): + The name of the function to extract. Should be either `training_function` or `main` + """ + if name != "training_function" and name != "main": + raise ValueError(f"Incorrect function name passed: {name}, choose either 'main' or 'training_function'") + good_lines, found_start = [], False + for line in lines: + if not found_start and f"def {name}" in line: + found_start = True + good_lines.append(line) + continue + if found_start: + if name == "training_function" and "def main" in line: + return good_lines + if name == "main" and "if __name__" in line: + return good_lines + good_lines.append(line) + + +def clean_lines(lines: List[str]): + """ + Filters `lines` and removes any entries that start with a comment ('#') or is just a newline ('\n') + + Args: + lines (`List[str]`): + Source code of a script seperated by line. + """ + return [line for line in lines if not line.lstrip().startswith("#") and line != "\n"] + + +def compare_against_test(base_filename: str, feature_filename: str, parser_only: bool, secondary_filename: str = None): + """ + Tests whether the additional code inside of `feature_filename` was implemented in `base_filename`. This should be + used when testing to see if `complete_*_.py` examples have all of the implementations from each of the + `examples/by_feature/*` scripts. + + It utilizes `nlp_example.py` to extract out all of the repeated training code, so that only the new additional code + is examined and checked. If something *other* than `nlp_example.py` should be used, such as `cv_example.py` for the + `complete_cv_example.py` script, it should be passed in for the `secondary_filename` parameter. + + Args: + base_filename (`str` or `os.PathLike`): + The filepath of a single "complete" example script to test, such as `examples/complete_cv_example.py` + feature_filename (`str` or `os.PathLike`): + The filepath of a single feature example script. The contents of this script are checked to see if they + exist in `base_filename` + parser_only (`bool`): + Whether to compare only the `main()` sections in both files, or to compare the contents of + `training_loop()` + secondary_filename (`str`, *optional*): + A potential secondary filepath that should be included in the check. This function extracts the base + functionalities off of "examples/nlp_example.py", so if `base_filename` is a script other than + `complete_nlp_example.py`, the template script should be included here. Such as `examples/cv_example.py` + """ + with open(base_filename) as f: + base_file_contents = f.readlines() + with open(os.path.abspath(os.path.join("examples", "nlp_example.py"))) as f: + full_file_contents = f.readlines() + with open(feature_filename) as f: + feature_file_contents = f.readlines() + if secondary_filename is not None: + with open(secondary_filename) as f: + secondary_file_contents = f.readlines() + + # This is our base, we remove all the code from here in our `full_filename` and `feature_filename` to find the new content + if parser_only: + base_file_func = clean_lines(get_function_contents_by_name(base_file_contents, "main")) + full_file_func = clean_lines(get_function_contents_by_name(full_file_contents, "main")) + feature_file_func = clean_lines(get_function_contents_by_name(feature_file_contents, "main")) + if secondary_filename is not None: + secondary_file_func = clean_lines(get_function_contents_by_name(secondary_file_contents, "main")) + else: + base_file_func = clean_lines(get_function_contents_by_name(base_file_contents, "training_function")) + full_file_func = clean_lines(get_function_contents_by_name(full_file_contents, "training_function")) + feature_file_func = clean_lines(get_function_contents_by_name(feature_file_contents, "training_function")) + if secondary_filename is not None: + secondary_file_func = clean_lines( + get_function_contents_by_name(secondary_file_contents, "training_function") + ) + + _dl_line = "train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)\n" + + # Specific code in our script that differs from the full version, aka what is new + new_feature_code = [] + passed_idxs = [] # We keep track of the idxs just in case it's a repeated statement + it = iter(feature_file_func) + for i in range(len(feature_file_func) - 1): + if i not in passed_idxs: + line = next(it) + if (line not in full_file_func) and (line.lstrip() != _dl_line): + if "TESTING_MOCKED_DATALOADERS" not in line: + new_feature_code.append(line) + passed_idxs.append(i) + else: + # Skip over the `config['num_epochs'] = 2` statement + _ = next(it) + + # Extract out just the new parts from the full_file_training_func + new_full_example_parts = [] + passed_idxs = [] # We keep track of the idxs just in case it's a repeated statement + for i, line in enumerate(base_file_func): + if i not in passed_idxs: + if (line not in full_file_func) and (line.lstrip() != _dl_line): + if "TESTING_MOCKED_DATALOADERS" not in line: + new_full_example_parts.append(line) + passed_idxs.append(i) + + # Finally, get the overall diff + diff_from_example = [line for line in new_feature_code if line not in new_full_example_parts] + if secondary_filename is not None: + diff_from_two = [line for line in full_file_contents if line not in secondary_file_func] + diff_from_example = [line for line in diff_from_example if line not in diff_from_two] + + return diff_from_example diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/__init__.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/__init__.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c9cbe26c257b515f657c05e1996d517e69613972 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/__init__.py @@ -0,0 +1,13 @@ +# 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. diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py new file mode 100644 index 0000000000000000000000000000000000000000..7b86a40b20721699bd3df4e9969d5823d7b3d9e3 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py @@ -0,0 +1,269 @@ +# Copyright 2022 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. +import argparse +import json +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils.deepspeed import DummyOptim, DummyScheduler + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"): + """ + Creates a set of `DataLoader`s for the `glue` dataset. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + model_name (`str`, *optional*): + """ + tokenizer = AutoTokenizer.from_pretrained(model_name) + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +def evaluation_loop(accelerator, model, eval_dataloader, metric): + model.eval() + samples_seen = 0 + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + # It is slightly faster to call this once, than multiple times + predictions, references = accelerator.gather( + (predictions, batch["labels"]) + ) # If we are in a multiprocess environment, the last batch has duplicates + if accelerator.use_distributed: + if step == len(eval_dataloader) - 1: + predictions = predictions[: len(eval_dataloader.dataset) - samples_seen] + references = references[: len(eval_dataloader.dataset) - samples_seen] + else: + samples_seen += references.shape[0] + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + return eval_metric["accuracy"] + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator() + + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + model_name = args.model_name_or_path + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True) + + # Instantiate optimizer + optimizer_cls = ( + AdamW + if accelerator.state.deepspeed_plugin is None + or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config + else DummyOptim + ) + optimizer = optimizer_cls(params=model.parameters(), lr=lr) + + if accelerator.state.deepspeed_plugin is not None: + gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config[ + "gradient_accumulation_steps" + ] + else: + gradient_accumulation_steps = 1 + max_training_steps = (len(train_dataloader) * num_epochs) // gradient_accumulation_steps + + # Instantiate scheduler + if ( + accelerator.state.deepspeed_plugin is None + or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config + ): + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=max_training_steps, + ) + else: + lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # We need to keep track of how many total steps we have iterated over + overall_step = 0 + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + metric = evaluate.load("glue", "mrpc") + ending_epoch = num_epochs + + if args.partial_train_epoch is not None: + ending_epoch = args.partial_train_epoch + + if args.resume_from_checkpoint: + accelerator.load_state(args.resume_from_checkpoint) + epoch_string = args.resume_from_checkpoint.split("epoch_")[1] + state_epoch_num = "" + for char in epoch_string: + if char.isdigit(): + state_epoch_num += char + else: + break + starting_epoch = int(state_epoch_num) + 1 + accuracy = evaluation_loop(accelerator, model, eval_dataloader, metric) + accelerator.print("resumed checkpoint performance:", accuracy) + accelerator.print("resumed checkpoint's scheduler's lr:", lr_scheduler.get_lr()[0]) + accelerator.print("resumed optimizers's lr:", optimizer.param_groups[0]["lr"]) + with open(os.path.join(args.output_dir, f"state_{starting_epoch - 1}.json")) as f: + resumed_state = json.load(f) + assert resumed_state["accuracy"] == accuracy, "Accuracy mismatch, loading from checkpoint failed" + assert ( + resumed_state["lr"] == lr_scheduler.get_lr()[0] + ), "Scheduler learning rate mismatch, loading from checkpoint failed" + assert ( + resumed_state["optimizer_lr"] == optimizer.param_groups[0]["lr"] + ), "Optimizer learning rate mismatch, loading from checkpoint failed" + assert resumed_state["epoch"] == starting_epoch - 1, "Epoch mismatch, loading from checkpoint failed" + return + + # Now we train the model + state = {} + for epoch in range(starting_epoch, ending_epoch): + model.train() + for step, batch in enumerate(train_dataloader): + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + overall_step += 1 + output_dir = f"epoch_{epoch}" + output_dir = os.path.join(args.output_dir, output_dir) + accelerator.save_state(output_dir) + accuracy = evaluation_loop(accelerator, model, eval_dataloader, metric) + state["accuracy"] = accuracy + state["lr"] = lr_scheduler.get_lr()[0] + state["optimizer_lr"] = optimizer.param_groups[0]["lr"] + state["epoch"] = epoch + state["step"] = overall_step + accelerator.print(f"epoch {epoch}:", state) + + accelerator.wait_for_everyone() + if accelerator.is_main_process: + with open(os.path.join(args.output_dir, f"state_{epoch}.json"), "w") as f: + json.dump(state, f) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.") + parser.add_argument( + "--model_name_or_path", + type=str, + default="bert-base-cased", + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--resume_from_checkpoint", + type=str, + default=None, + help="If the training should continue from a checkpoint folder.", + ) + parser.add_argument( + "--partial_train_epoch", + type=int, + default=None, + help="If passed, the training will stop after this number of epochs.", + ) + parser.add_argument( + "--num_epochs", + type=int, + default=2, + help="Number of train epochs.", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} + + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..dfbf5c9f90ce0727523e3b43a1dce1600a514961 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_metrics.py @@ -0,0 +1,307 @@ +# 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. + +import logging +import math +import os +from copy import deepcopy + +import datasets +import evaluate +import torch +import transformers +from datasets import load_dataset +from torch.utils.data import DataLoader, IterableDataset +from transformers import AutoModelForSequenceClassification, AutoTokenizer + +from accelerate import Accelerator, DataLoaderConfiguration, DistributedType +from accelerate.data_loader import DataLoaderDispatcher +from accelerate.test_utils import RegressionDataset, RegressionModel, torch_device +from accelerate.utils import is_torch_xla_available, set_seed + + +os.environ["TRANSFORMERS_NO_ADVISORY_WARNINGS"] = "true" + + +class ListHandler(logging.Handler): + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self.logs = [] + + def emit(self, record): + self.logs.append(record) + + +def get_basic_setup(accelerator, num_samples=82, batch_size=16): + "Returns everything needed to perform basic training" + set_seed(42) + model = RegressionModel() + ddp_model = deepcopy(model) + dset = RegressionDataset(length=num_samples) + dataloader = DataLoader(dset, batch_size=batch_size) + model.to(accelerator.device) + ddp_model, dataloader = accelerator.prepare(ddp_model, dataloader) + return model, ddp_model, dataloader + + +def get_dataloader(accelerator: Accelerator, use_longest=False): + tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/mrpc-bert-base-cased") + dataset = load_dataset("glue", "mrpc", split="validation") + + def tokenize_function(examples): + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + with accelerator.main_process_first(): + tokenized_datasets = dataset.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + if use_longest: + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + + return DataLoader(tokenized_datasets, shuffle=False, collate_fn=collate_fn, batch_size=16) + + +def get_mrpc_setup(dispatch_batches, split_batches): + dataloader_config = DataLoaderConfiguration(dispatch_batches=dispatch_batches, split_batches=split_batches) + accelerator = Accelerator(dataloader_config=dataloader_config) + dataloader = get_dataloader(accelerator, not dispatch_batches) + model = AutoModelForSequenceClassification.from_pretrained( + "hf-internal-testing/mrpc-bert-base-cased", return_dict=True + ) + ddp_model, ddp_dataloader = accelerator.prepare(model, dataloader) + return { + "ddp": [ddp_model, ddp_dataloader, torch_device], + "no": [model, dataloader, accelerator.device], + }, accelerator + + +def generate_predictions(model, dataloader, accelerator): + logits_and_targets = [] + for batch in dataloader: + input, target = batch.values() + with torch.no_grad(): + logit = model(input) + logit, target = accelerator.gather_for_metrics((logit, target)) + logits_and_targets.append((logit, target)) + logits, targs = [], [] + for logit, targ in logits_and_targets: + logits.append(logit) + targs.append(targ) + logits, targs = torch.cat(logits), torch.cat(targs) + return logits, targs + + +def test_torch_metrics( + accelerator: Accelerator, num_samples=82, dispatch_batches=False, split_batches=False, batch_size=16 +): + _, ddp_model, dataloader = get_basic_setup(accelerator, num_samples, batch_size) + logits, _ = generate_predictions(ddp_model, dataloader, accelerator) + assert ( + len(logits) == num_samples + ), f"Unexpected number of inputs:\n Expected: {num_samples}\n Actual: {len(logits)}" + + +def test_mrpc(dispatch_batches: bool = False, split_batches: bool = False): + metric = evaluate.load("glue", "mrpc") + setup, accelerator = get_mrpc_setup(dispatch_batches, split_batches) + # First do baseline + model, dataloader, device = setup["no"] + model.to(device) + model.eval() + for batch in dataloader: + batch.to(device) + with torch.inference_mode(): + outputs = model(**batch) + preds = outputs.logits.argmax(dim=-1) + metric.add_batch(predictions=preds, references=batch["labels"]) + baseline = metric.compute() + + # Then do distributed + model, dataloader, device = setup["ddp"] + model.eval() + for batch in dataloader: + with torch.inference_mode(): + outputs = model(**batch) + preds = outputs.logits.argmax(dim=-1) + references = batch["labels"] + preds, references = accelerator.gather_for_metrics((preds, references)) + metric.add_batch(predictions=preds, references=references) + distributed = metric.compute() + + for key in "accuracy f1".split(): + assert math.isclose( + baseline[key], distributed[key] + ), f"Baseline and Distributed are not the same for key {key}:\n\tBaseline: {baseline[key]}\n\tDistributed: {distributed[key]}\n" + + +def test_gather_for_metrics_with_non_tensor_objects_iterable_dataset(): + class DummyIterableDataset(IterableDataset): + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __iter__(self): + yield from self.data + + iterable_dataset = DummyIterableDataset([n for n in range(30)]) + dataloader = DataLoader(iterable_dataset, batch_size=4) + accelerator = Accelerator() + prepared_dataloader = accelerator.prepare(dataloader) + + if accelerator.is_main_process: + logger = logging.root.manager.loggerDict["accelerate.accelerator"] + list_handler = ListHandler() + logger.addHandler(list_handler) + + batches_for_metrics = [] + for batch in prepared_dataloader: + batches_for_metrics.append(accelerator.gather_for_metrics(batch)) + + assert torch.cat(batches_for_metrics).size(0) == 30 + + if accelerator.is_main_process: + assert len(list_handler.logs) == 0 + logger.removeHandler(list_handler) + + +def test_gather_for_metrics_with_iterable_dataset(): + class DummyIterableDataset(IterableDataset): + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __iter__(self): + yield from self.data + + iterable_dataset = DummyIterableDataset(torch.as_tensor(range(30))) + dataloader = DataLoader(iterable_dataset, batch_size=4) + + accelerator = Accelerator() + prepared_dataloader = accelerator.prepare(dataloader) + + assert isinstance(prepared_dataloader, DataLoaderDispatcher) + + if accelerator.is_main_process: + logger = logging.root.manager.loggerDict["accelerate.accelerator"] + list_handler = ListHandler() + logger.addHandler(list_handler) + + batches_for_metrics = [] + for batch in prepared_dataloader: + batches_for_metrics.append(accelerator.gather_for_metrics(batch)) + + assert torch.cat(batches_for_metrics).size(0) == 30 + + if accelerator.is_main_process: + assert len(list_handler.logs) == 0 + + logger.removeHandler(list_handler) + + +def test_gather_for_metrics_drop_last(): + accelerator = Accelerator() + per_device_batch_size = 5 + num_items = (10 * accelerator.num_processes) + 1 + dataloader = DataLoader(range(num_items), batch_size=per_device_batch_size, drop_last=True) + dataloader = accelerator.prepare(dataloader) + + iterator = iter(dataloader) + next(iterator) # Skip first batch tensor([0, 1, 2, 3, 4], device='cuda:0') + batch = next(iterator) + gathered_items = accelerator.gather_for_metrics(batch) + + # Should return a full set of complete batches from each GPU + num_expected_items = per_device_batch_size * accelerator.num_processes + assert gathered_items.size(0) == ( + num_expected_items + ), f"Expected number of items: {num_expected_items}, Actual: {gathered_items.size(0)}" + + +def main(): + dataloader_config = DataLoaderConfiguration(split_batches=False, dispatch_batches=False) + accelerator = Accelerator(dataloader_config=dataloader_config) + if accelerator.is_local_main_process: + datasets.utils.logging.set_verbosity_warning() + transformers.utils.logging.set_verbosity_warning() + else: + datasets.utils.logging.set_verbosity_error() + transformers.utils.logging.set_verbosity_error() + # TorchXLA does not support batch dispatching. 'put_on_device' is always False for + # TorchXLA, which can cause a value error in 'prepare_data_loader' function. + dispatch_batches_options = [False] if accelerator.state.distributed_type == DistributedType.XLA else [True, False] + + # Temporarily close this test for TorchXLA due to the 'Cannot set version_counter for + # inference tensor' error in inference mode. Reopen it after TorchXLA fixes this bug. + # These are a bit slower so they should only be ran on the GPU or TPU + if accelerator.device.type != "cpu" and not is_torch_xla_available(): + if accelerator.is_local_main_process: + print("**Testing gather_for_metrics**") + for split_batches in [True, False]: + for dispatch_batches in dispatch_batches_options: + if accelerator.is_local_main_process: + print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`") + test_mrpc(dispatch_batches, split_batches) + accelerator.state._reset_state() + print("test_gather_for_metrics_with_iterable_dataset") + test_gather_for_metrics_with_iterable_dataset() + print("test gather_for_metrics_with_non_tensor_objects_iterable_dataset") + test_gather_for_metrics_with_non_tensor_objects_iterable_dataset() + + # MpDeviceLoader in TorchXLA is an asynchronous loader that preloads several batches into cache. + # This can cause the 'end_of_dataloader' of DataLoaderStateMixin to be set earlier than intended. + # Skip this test when TorchXLA is enabled. + if accelerator.state.distributed_type != DistributedType.XLA: + if accelerator.is_local_main_process: + print("**Test torch metrics**") + for split_batches in [True, False]: + for dispatch_batches in dispatch_batches_options: + dataloader_config = DataLoaderConfiguration( + split_batches=split_batches, dispatch_batches=dispatch_batches + ) + accelerator = Accelerator(dataloader_config=dataloader_config) + if accelerator.is_local_main_process: + print(f"With: `split_batches={split_batches}`, `dispatch_batches={dispatch_batches}`, length=99") + test_torch_metrics(accelerator, 99) + accelerator.state._reset_state() + if accelerator.is_local_main_process: + print("**Test last batch is not dropped when perfectly divisible**") + accelerator = Accelerator() + test_torch_metrics(accelerator, 512) + accelerator.state._reset_state() + if accelerator.is_local_main_process: + print("**Test that `drop_last` is taken into account**") + test_gather_for_metrics_drop_last() + accelerator.end_training() + accelerator.state._reset_state() + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py new file mode 100644 index 0000000000000000000000000000000000000000..93e3a34ffb152dc250e764a60520d43f04b3b1f8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py @@ -0,0 +1,291 @@ +# Copyright 2022 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. +import argparse +import gc +import json +import os + +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils import is_mlu_available, is_musa_available, is_npu_available, is_xpu_available +from accelerate.utils.deepspeed import DummyOptim, DummyScheduler + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +# Converting Bytes to Megabytes +def b2mb(x): + return int(x / 2**20) + + +# This context manager is used to track the peak memory usage of the process +class TorchTracemalloc: + def __enter__(self): + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + torch.cuda.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.cuda.memory_allocated() + elif is_mlu_available(): + torch.mlu.empty_cache() + torch.mlu.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.mlu.memory_allocated() + elif is_musa_available(): + torch.musa.empty_cache() + torch.musa.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.musa.memory_allocated() + elif is_npu_available(): + torch.npu.empty_cache() + torch.npu.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.npu.memory_allocated() + elif is_xpu_available(): + torch.xpu.empty_cache() + torch.xpu.reset_max_memory_allocated() # reset the peak gauge to zero + self.begin = torch.xpu.memory_allocated() + return self + + def __exit__(self, *exc): + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + self.end = torch.cuda.memory_allocated() + self.peak = torch.cuda.max_memory_allocated() + elif is_mlu_available(): + torch.mlu.empty_cache() + torch.mlu.memory_allocated() # reset the peak gauge to zero + self.begin = torch.mlu.max_memory_allocated() + elif is_musa_available(): + torch.musa.empty_cache() + torch.musa.memory_allocated() # reset the peak gauge to zero + self.begin = torch.musa.max_memory_allocated() + elif is_npu_available(): + torch.npu.empty_cache() + self.end = torch.npu.memory_allocated() + self.peak = torch.npu.max_memory_allocated() + elif is_xpu_available(): + torch.xpu.empty_cache() + self.end = torch.xpu.memory_allocated() + self.peak = torch.xpu.max_memory_allocated() + self.used = b2mb(self.end - self.begin) + self.peaked = b2mb(self.peak - self.begin) + # print(f"delta used/peak {self.used:4d}/{self.peaked:4d}") + + +def get_dataloaders( + accelerator: Accelerator, + batch_size: int = 16, + model_name: str = "bert-base-cased", + n_train: int = 320, + n_val: int = 160, +): + """ + Creates a set of `DataLoader`s for the `glue` dataset. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + model_name (`str`, *optional*): + The name of the model to use. + n_train (`int`, *optional*): + The number of training examples to use. + n_val (`int`, *optional*): + The number of validation examples to use. + """ + tokenizer = AutoTokenizer.from_pretrained(model_name) + datasets = load_dataset( + "glue", "mrpc", split={"train": f"train[:{n_train}]", "validation": f"validation[:{n_val}]"} + ) + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator() + + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + model_name = args.model_name_or_path + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name, args.n_train, args.n_val) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True) + + # Instantiate optimizer + optimizer_cls = ( + AdamW + if accelerator.state.deepspeed_plugin is None + or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config + else DummyOptim + ) + optimizer = optimizer_cls(params=model.parameters(), lr=lr) + + if accelerator.state.deepspeed_plugin is not None: + gradient_accumulation_steps = accelerator.state.deepspeed_plugin.deepspeed_config[ + "gradient_accumulation_steps" + ] + else: + gradient_accumulation_steps = 1 + max_training_steps = (len(train_dataloader) * num_epochs) // gradient_accumulation_steps + + # Instantiate scheduler + if ( + accelerator.state.deepspeed_plugin is None + or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config + ): + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=max_training_steps, + ) + else: + lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # We need to keep track of how many total steps we have iterated over + overall_step = 0 + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + + # Now we train the model + train_total_peak_memory = {} + for epoch in range(starting_epoch, num_epochs): + with TorchTracemalloc() as tracemalloc: + model.train() + for step, batch in enumerate(train_dataloader): + outputs = model(**batch) + loss = outputs.loss + loss = loss / gradient_accumulation_steps + accelerator.backward(loss) + if step % gradient_accumulation_steps == 0: + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + overall_step += 1 + + # Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage + accelerator.print(f"Memory before entering the train : {b2mb(tracemalloc.begin)}") + accelerator.print(f"Memory consumed at the end of the train (end-begin): {tracemalloc.used}") + accelerator.print(f"Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}") + accelerator.print( + f"Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}" + ) + train_total_peak_memory[f"epoch-{epoch}"] = tracemalloc.peaked + b2mb(tracemalloc.begin) + if args.peak_memory_upper_bound is not None: + assert ( + train_total_peak_memory[f"epoch-{epoch}"] <= args.peak_memory_upper_bound + ), "Peak memory usage exceeded the upper bound" + + accelerator.wait_for_everyone() + if accelerator.is_main_process: + with open(os.path.join(args.output_dir, "peak_memory_utilization.json"), "w") as f: + json.dump(train_total_peak_memory, f) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.") + parser.add_argument( + "--model_name_or_path", + type=str, + default="bert-base-cased", + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--peak_memory_upper_bound", + type=float, + default=None, + help="The upper bound of peak memory usage in MB. If set, the training will throw an error if the peak memory usage exceeds this value.", + ) + parser.add_argument( + "--n_train", + type=int, + default=320, + help="Number of training examples to use.", + ) + parser.add_argument( + "--n_val", + type=int, + default=160, + help="Number of validation examples to use.", + ) + parser.add_argument( + "--num_epochs", + type=int, + default=1, + help="Number of train epochs.", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py new file mode 100644 index 0000000000000000000000000000000000000000..f1f7ddd579f1761777de488673dbf55ea3fc182d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_performance.py @@ -0,0 +1,244 @@ +# Copyright 2022 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. +import argparse +import json +import os + +import evaluate +import torch +from datasets import load_dataset +from torch.optim import AdamW +from torch.utils.data import DataLoader +from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed + +from accelerate import Accelerator, DistributedType +from accelerate.utils.deepspeed import DummyOptim, DummyScheduler + + +MAX_GPU_BATCH_SIZE = 16 +EVAL_BATCH_SIZE = 32 + + +def get_dataloaders(accelerator: Accelerator, batch_size: int = 16, model_name: str = "bert-base-cased"): + """ + Creates a set of `DataLoader`s for the `glue` dataset. + + Args: + accelerator (`Accelerator`): + An `Accelerator` object + batch_size (`int`, *optional*): + The batch size for the train and validation DataLoaders. + model_name (`str`, *optional*): + """ + tokenizer = AutoTokenizer.from_pretrained(model_name) + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, batched=True, remove_columns=["idx", "sentence1", "sentence2"], load_from_cache_file=False + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE + ) + + return train_dataloader, eval_dataloader + + +def training_function(config, args): + # Initialize accelerator + accelerator = Accelerator() + + # Sample hyper-parameters for learning rate, batch size, seed and a few other HPs + lr = config["lr"] + num_epochs = int(config["num_epochs"]) + seed = int(config["seed"]) + batch_size = int(config["batch_size"]) + model_name = args.model_name_or_path + + set_seed(seed) + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size, model_name) + + # Instantiate the model (we build the model here so that the seed also control new weights initialization) + model = AutoModelForSequenceClassification.from_pretrained(model_name, return_dict=True) + + # Instantiate optimizer + optimizer_cls = ( + AdamW + if accelerator.state.deepspeed_plugin is None + or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config + else DummyOptim + ) + optimizer = optimizer_cls(params=model.parameters(), lr=lr) + + max_training_steps = len(train_dataloader) * num_epochs + + # Instantiate scheduler + linear_decay_scheduler = False + if ( + accelerator.state.deepspeed_plugin is None + or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config + ): + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=0, + num_training_steps=max_training_steps, + ) + linear_decay_scheduler = True + else: + lr_scheduler = DummyScheduler(optimizer, total_num_steps=max_training_steps, warmup_num_steps=0) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # We also need to keep track of the stating epoch so files are named properly + starting_epoch = 0 + + # Now we train the model + metric = evaluate.load("glue", "mrpc") + best_performance = 0 + performance_metric = {} + expected_lr_after_first_optim_step = lr * ( + 1 - 1 / (max_training_steps / accelerator.num_processes / accelerator.gradient_accumulation_steps) + ) + lr_scheduler_check_completed = False + for epoch in range(starting_epoch, num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + with accelerator.accumulate(model): + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + # assert the learning rate after first optimizer step + if ( + accelerator.sync_gradients + and not lr_scheduler_check_completed + and linear_decay_scheduler + and accelerator.state.mixed_precision == "no" + ): + assert ( + lr_scheduler.get_last_lr()[0] == expected_lr_after_first_optim_step + ), f"Wrong lr found at second step, expected {expected_lr_after_first_optim_step}, got {lr_scheduler.get_last_lr()[0]}" + lr_scheduler_check_completed = True + + model.eval() + samples_seen = 0 + for step, batch in enumerate(eval_dataloader): + # We could avoid this line since we set the accelerator with `device_placement=True`. + batch.to(accelerator.device) + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + # It is slightly faster to call this once, than multiple times + predictions, references = accelerator.gather( + (predictions, batch["labels"]) + ) # If we are in a multiprocess environment, the last batch has duplicates + if accelerator.use_distributed: + if step == len(eval_dataloader) - 1: + predictions = predictions[: len(eval_dataloader.dataset) - samples_seen] + references = references[: len(eval_dataloader.dataset) - samples_seen] + else: + samples_seen += references.shape[0] + metric.add_batch( + predictions=predictions, + references=references, + ) + + eval_metric = metric.compute() + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}:", eval_metric) + performance_metric[f"epoch-{epoch}"] = eval_metric["accuracy"] + + if best_performance < eval_metric["accuracy"]: + best_performance = eval_metric["accuracy"] + + # check that the LR is 0 + if linear_decay_scheduler and accelerator.state.mixed_precision == "no": + assert ( + lr_scheduler.get_last_lr()[0] == 0 + ), f"Wrong lr found at last step, expected 0, got {lr_scheduler.get_last_lr()[0]}" + + if args.performance_lower_bound is not None: + assert ( + args.performance_lower_bound <= best_performance + ), f"Best performance metric {best_performance} is lower than the lower bound {args.performance_lower_bound}" + + accelerator.wait_for_everyone() + if accelerator.is_main_process: + with open(os.path.join(args.output_dir, "all_results.json"), "w") as f: + json.dump(performance_metric, f) + accelerator.end_training() + + +def main(): + parser = argparse.ArgumentParser(description="Simple example of training script tracking peak GPU memory usage.") + parser.add_argument( + "--model_name_or_path", + type=str, + default="bert-base-cased", + help="Path to pretrained model or model identifier from huggingface.co/models.", + required=False, + ) + parser.add_argument( + "--output_dir", + type=str, + default=".", + help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.", + ) + parser.add_argument( + "--performance_lower_bound", + type=float, + default=None, + help="Optional lower bound for the performance metric. If set, the training will throw error when the performance metric drops below this value.", + ) + parser.add_argument( + "--num_epochs", + type=int, + default=3, + help="Number of train epochs.", + ) + args = parser.parse_args() + config = {"lr": 2e-5, "num_epochs": args.num_epochs, "seed": 42, "batch_size": 16} + training_function(config, args) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py new file mode 100644 index 0000000000000000000000000000000000000000..389b963e0cb544c4b9eb08ad72f871ecead30f01 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_pippy.py @@ -0,0 +1,116 @@ +# Copyright 2024 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. +import torch +from transformers import ( + BertConfig, + BertForMaskedLM, + GPT2Config, + GPT2ForSequenceClassification, +) + +from accelerate import PartialState +from accelerate.inference import prepare_pippy +from accelerate.utils import DistributedType, set_seed + + +model_to_config = { + "bert": (BertForMaskedLM, BertConfig, 512), + "gpt2": (GPT2ForSequenceClassification, GPT2Config, 1024), +} + + +def get_model_and_data_for_text(model_name, device, num_processes: int = 2): + initializer, config, seq_len = model_to_config[model_name] + config_args = {} + # Eventually needed for batch inference tests on gpt-2 when bs != 1 + # if model_name == "gpt2": + # config_args["pad_token_id"] = 0 + model_config = config(**config_args) + model = initializer(model_config) + kwargs = dict(low=0, high=model_config.vocab_size, device=device, dtype=torch.int64, requires_grad=False) + trace_input = torch.randint(size=(1, seq_len), **kwargs) + inference_inputs = torch.randint(size=(num_processes, seq_len), **kwargs) + return model, trace_input, inference_inputs + + +def test_bert(batch_size: int = 2): + set_seed(42) + state = PartialState() + model, trace_input, inference_inputs = get_model_and_data_for_text("bert", "cpu", batch_size) + model = prepare_pippy(model, example_args=(trace_input,), no_split_module_classes=model._no_split_modules) + # For inference args need to be a tuple + inputs = inference_inputs.to("cuda") + with torch.no_grad(): + output = model(inputs) + # Zach: Check that we just grab the real outputs we need at the end + if not state.is_last_process: + assert output is None, "Output was not generated on just the last process!" + else: + assert output is not None, "Output was not generated in the last process!" + + +def test_gpt2(batch_size: int = 2): + set_seed(42) + state = PartialState() + model, trace_input, inference_inputs = get_model_and_data_for_text("gpt2", "cpu", batch_size) + model = prepare_pippy(model, example_args=(trace_input,), no_split_module_classes=model._no_split_modules) + # For inference args need to be a tuple + inputs = inference_inputs.to("cuda") + with torch.no_grad(): + output = model(inputs) + # Zach: Check that we just grab the real outputs we need at the end + if not state.is_last_process: + assert output is None, "Output was not generated on just the last process!" + else: + assert output is not None, "Output was not generated in the last process!" + + +# Currently disabled, enable again once PyTorch pippy interface can trace a resnet34 +# def test_resnet(batch_size: int = 2): +# set_seed(42) +# state = PartialState() +# model = resnet34() +# input_tensor = torch.rand(1, 3, 224, 224) +# model = prepare_pippy( +# model, +# example_args=(input_tensor,), +# ) +# inference_inputs = torch.rand(batch_size, 3, 224, 224) +# inputs = send_to_device(inference_inputs, "cuda:0") +# with torch.no_grad(): +# output = model(inputs) +# # Zach: Check that we just grab the real outputs we need at the end +# if not state.is_last_process: +# assert output is None, "Output was not generated on just the last process!" +# else: +# assert output is not None, "Output was not generated in the last process!" + + +if __name__ == "__main__": + state = PartialState() + state.print("Testing pippy integration...") + try: + if state.distributed_type == DistributedType.MULTI_GPU: + state.print("Testing GPT2...") + test_gpt2() + # Issue: When modifying the tokenizer for batch GPT2 inference, there's an issue + # due to references + # NameError: cannot access free variable 'chunk_args_list' where it is not associated with a value in enclosing scope + # test_gpt2(3) + state.print("Testing BERT...") + test_bert() + else: + print("Less than two GPUs found, not running tests!") + finally: + state.destroy_process_group() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py new file mode 100644 index 0000000000000000000000000000000000000000..2bbb324c8cde4611a53cb94b721e0258c6ba7f56 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py @@ -0,0 +1,53 @@ +# 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. + +import torch.distributed + +from accelerate.test_utils import require_huggingface_suite, torch_device +from accelerate.utils import is_transformers_available + + +if is_transformers_available(): + from transformers import AutoModel, TrainingArguments + + +GPT2_TINY = "sshleifer/tiny-gpt2" + + +@require_huggingface_suite +def init_torch_dist_then_launch_deepspeed(): + backend = "ccl" if torch_device == "xpu" else "nccl" + torch.distributed.init_process_group(backend=backend) + deepspeed_config = { + "zero_optimization": { + "stage": 3, + }, + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + } + train_args = TrainingArguments( + output_dir="./", + deepspeed=deepspeed_config, + ) + model = AutoModel.from_pretrained(GPT2_TINY) + assert train_args is not None + assert model is not None + + +def main(): + init_torch_dist_then_launch_deepspeed() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_cli.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_cli.py new file mode 100644 index 0000000000000000000000000000000000000000..c85828cd49624372ae1866082e5580c60f8c9293 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_cli.py @@ -0,0 +1,26 @@ +# 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. +import torch + + +def main(): + if torch.cuda.is_available(): + num_gpus = torch.cuda.device_count() + else: + num_gpus = 0 + print(f"Successfully ran on {num_gpus} GPUs") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py new file mode 100644 index 0000000000000000000000000000000000000000..01c939db15bebf59c3666e56706b7225e63e8342 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py @@ -0,0 +1,78 @@ +# 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. +import torch + +from accelerate import Accelerator, DDPCommunicationHookType, DistributedDataParallelKwargs, PartialState + + +class MockModel(torch.nn.Module): + def __init__(self): + super().__init__() + torch.manual_seed(0) + self.p = torch.nn.Parameter(torch.randn(40, 20)) + + def forward(self, x, rank): + return self.p * (x ** (1 + rank)) + + +def _run_and_get_grads(model, rank): + torch.manual_seed(2024) + input = torch.randn(40, 20) + output = model(input, rank) + output.mean().backward() + param = next(model.parameters()) + return param.grad + + +def test_ddp_comm_hook(comm_hook, comm_wrapper, comm_state_option): + ddp_kwargs = DistributedDataParallelKwargs( + comm_hook=comm_hook, + comm_wrapper=comm_wrapper, + comm_state_option=comm_state_option, + ) + accelerator = Accelerator(kwargs_handlers=[ddp_kwargs]) + + model = accelerator.prepare(MockModel()) + hook_grads = _run_and_get_grads(model, accelerator.local_process_index) + + reference_model = torch.nn.parallel.DistributedDataParallel( + MockModel().to(accelerator.device), + device_ids=[accelerator.local_process_index], + output_device=accelerator.local_process_index, + ) + reference_grads = _run_and_get_grads(reference_model, accelerator.local_process_index) + + torch.testing.assert_close(hook_grads, reference_grads, rtol=1e-2, atol=1e-2) + + +def main(): + for comm_hook, comm_wrapper, comm_state_option in [ + (DDPCommunicationHookType.NO, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.FP16, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.BF16, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.FP16, {}), + (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.BF16, {}), + (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.NO, {"matrix_approximation_rank": 2}), + (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.NO, {}), + (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.FP16, {}), + (DDPCommunicationHookType.BATCHED_POWER_SGD, DDPCommunicationHookType.BF16, {}), + ]: + print(f"Test DDP comm hook: {comm_hook}, comm wrapper: {comm_wrapper}") + test_ddp_comm_hook(comm_hook, comm_wrapper, comm_state_option) + PartialState().destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py new file mode 100644 index 0000000000000000000000000000000000000000..5c59a6d7326df61c09b99c5301f6bd82f102e1f1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_distributed_data_loop.py @@ -0,0 +1,396 @@ +#!/usr/bin/env python + +# 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. + +import tempfile +import warnings +from typing import List +from unittest.mock import Mock + +import torch +from torch.utils.data import ( + BatchSampler, + DataLoader, + Dataset, + IterableDataset, + RandomSampler, + TensorDataset, + default_collate, +) + +from accelerate.accelerator import Accelerator, DataLoaderConfiguration +from accelerate.utils.dataclasses import DistributedType + + +NUM_ELEMENTS = 22 +NUM_WORKERS = 4 +BATCH_SIZE = 4 + + +class DummyDataset(Dataset): + def __len__(self): + return NUM_ELEMENTS + + def __getitem__(self, index): + squeeze = False + + if isinstance(index, int): + index = [index] + squeeze = True + elif isinstance(index, slice): + index = list(range(*index.indices(self.size))) + else: + index = list(index) + + batch = [{"index": i, "label": i % 2, "random_augmentation": torch.rand(1).item()} for i in index] + + if squeeze: + batch = batch[0] + + return batch + + +class DummyIterableDataset(IterableDataset): + def __init__(self, data): + self.data = data + + def __iter__(self): + yield from self.data + + +def create_accelerator(even_batches=True): + dataloader_config = DataLoaderConfiguration(even_batches=even_batches) + accelerator = Accelerator(dataloader_config=dataloader_config) + assert accelerator.num_processes == 2, "this script expects that two GPUs are available" + return accelerator + + +def create_dataloader( + accelerator: Accelerator, dataset_size: int, batch_size: int, iterable: bool = False, shuffle: bool = False +): + """ + Create a simple DataLoader to use during the test cases + """ + values = torch.as_tensor(range(dataset_size)) + if shuffle: + values = values[torch.randperm(values.size(0))] + if iterable: + dataset = DummyIterableDataset(values) + else: + dataset = TensorDataset(torch.as_tensor(range(dataset_size))) + + dl = DataLoader(dataset, batch_size=batch_size) + dl = accelerator.prepare(dl) + + return dl + + +def verify_dataloader_batch_sizes( + accelerator: Accelerator, + dataset_size: int, + batch_size: int, + process_0_expected_batch_sizes: List[int], + process_1_expected_batch_sizes: List[int], +): + """ + A helper function for verifying the batch sizes coming from a prepared dataloader in each process + """ + dl = create_dataloader(accelerator=accelerator, dataset_size=dataset_size, batch_size=batch_size) + + batch_sizes = [len(batch[0]) for batch in dl] + + if accelerator.process_index == 0: + assert batch_sizes == process_0_expected_batch_sizes + elif accelerator.process_index == 1: + assert batch_sizes == process_1_expected_batch_sizes + + +def test_default_ensures_even_batch_sizes(): + accelerator = create_accelerator() + + # without padding, we would expect a different number of batches + verify_dataloader_batch_sizes( + accelerator, + dataset_size=3, + batch_size=1, + process_0_expected_batch_sizes=[1, 1], + process_1_expected_batch_sizes=[1, 1], + ) + + # without padding, we would expect the same number of batches, but different sizes + verify_dataloader_batch_sizes( + accelerator, + dataset_size=7, + batch_size=2, + process_0_expected_batch_sizes=[2, 2], + process_1_expected_batch_sizes=[2, 2], + ) + + +def test_can_disable_even_batches(): + accelerator = create_accelerator(even_batches=False) + + verify_dataloader_batch_sizes( + accelerator, + dataset_size=3, + batch_size=1, + process_0_expected_batch_sizes=[1, 1], + process_1_expected_batch_sizes=[1], + ) + + verify_dataloader_batch_sizes( + accelerator, + dataset_size=7, + batch_size=2, + process_0_expected_batch_sizes=[2, 2], + process_1_expected_batch_sizes=[2, 1], + ) + + +def test_can_join_uneven_inputs(): + accelerator = create_accelerator(even_batches=False) + + model = torch.nn.Linear(1, 1) + ddp_model = accelerator.prepare(model) + + dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) + + batch_idxs = [] + with accelerator.join_uneven_inputs([ddp_model]): + for batch_idx, batch in enumerate(dl): + output = ddp_model(batch[0].float()) + loss = output.sum() + loss.backward() + batch_idxs.append(batch_idx) + + accelerator.wait_for_everyone() + + if accelerator.process_index == 0: + assert batch_idxs == [0, 1] + elif accelerator.process_index == 1: + assert batch_idxs == [0] + + +def test_join_raises_warning_for_non_ddp_distributed(accelerator): + with warnings.catch_warnings(record=True) as w: + with accelerator.join_uneven_inputs([Mock()]): + pass + + assert issubclass(w[-1].category, UserWarning) + assert "only supported for multi-GPU" in str(w[-1].message) + + +def test_join_can_override_even_batches(): + default_even_batches = True + overridden_even_batches = False + accelerator = create_accelerator(even_batches=default_even_batches) + model = torch.nn.Linear(1, 1) + ddp_model = accelerator.prepare(model) + train_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) + valid_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) + + with accelerator.join_uneven_inputs([ddp_model], even_batches=overridden_even_batches): + train_dl_overridden_value = train_dl.batch_sampler.even_batches + valid_dl_overridden_value = valid_dl.batch_sampler.even_batches + + assert train_dl_overridden_value == overridden_even_batches + assert valid_dl_overridden_value == overridden_even_batches + assert train_dl.batch_sampler.even_batches == default_even_batches + assert valid_dl.batch_sampler.even_batches == default_even_batches + + +def test_join_can_override_for_mixed_type_dataloaders(): + default_even_batches = True + overridden_even_batches = False + accelerator = create_accelerator(even_batches=default_even_batches) + model = torch.nn.Linear(1, 1) + ddp_model = accelerator.prepare(model) + create_dataloader(accelerator, dataset_size=3, batch_size=1, iterable=True) + batch_dl = create_dataloader(accelerator, dataset_size=3, batch_size=1) + + with warnings.catch_warnings(): + warnings.filterwarnings("ignore") + try: + with accelerator.join_uneven_inputs([ddp_model], even_batches=overridden_even_batches): + batch_dl_overridden_value = batch_dl.batch_sampler.even_batches + except AttributeError: + # ensure attribute error is not raised when processing iterable dl + raise AssertionError + + assert batch_dl_overridden_value == overridden_even_batches + assert batch_dl.batch_sampler.even_batches == default_even_batches + + +def test_join_raises_warning_for_iterable_when_overriding_even_batches(): + accelerator = create_accelerator() + model = torch.nn.Linear(1, 1) + ddp_model = accelerator.prepare(model) + create_dataloader(accelerator, dataset_size=3, batch_size=1, iterable=True) + + with warnings.catch_warnings(record=True) as w: + with accelerator.join_uneven_inputs([ddp_model], even_batches=False): + pass + + assert issubclass(w[-1].category, UserWarning) + assert "only supported for map-style datasets" in str(w[-1].message) + + +def test_data_loader(data_loader, accelerator): + # Prepare the DataLoader + data_loader = accelerator.prepare(data_loader) + + all_examples = [] + for i, batch in enumerate(data_loader): + index, _ = accelerator.gather_for_metrics((batch["index"], batch["label"])) + all_examples.extend(index.detach().cpu().numpy().tolist()) + + # Sort the examples + sorted_all_examples = sorted(all_examples) + + # Check if all elements are present in the sorted list of iterated samples + assert ( + len(set(sorted_all_examples)) == NUM_ELEMENTS + ), "Not all the dataset elements have been iterated in an epoch due to duplication of samples across processes." + + +def test_stateful_dataloader(accelerator): + """ + Tests that a stateful dataloader can be iterated over, saved after a few batches using `load_state_dict`, and then + resumed from the saved state. + + The result should be the same as the rest of the data that iterated over after saving. + """ + old_dataloader_config = accelerator.dataloader_config + try: + accelerator.dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True) + prepared_dl = create_dataloader( + accelerator, dataset_size=32 * accelerator.num_processes, batch_size=4, iterable=True, shuffle=True + ) + untrained_batches = [] + # Calculate what step that will be + total_batches = 32 * accelerator.num_processes // (4 * accelerator.num_processes) + last_batch_num = total_batches - 1 + for step, batch in enumerate(prepared_dl): + # Step just before + if step == last_batch_num - 1: + state_dict = prepared_dl.state_dict() + if step >= last_batch_num: + # Otherwise grab the "unseen" batches + untrained_batches.append(batch) + not_skipped_batches = accelerator.gather(untrained_batches) + prepared_dl.load_state_dict(state_dict) + resumed_batches = [] + for batch in prepared_dl: + resumed_batches.append(batch) + resumed_batches = accelerator.gather(resumed_batches) + for b1, b2 in zip(not_skipped_batches, resumed_batches): + for v1, v2 in zip(b1, b2): + assert torch.equal(v1, v2), f"Batch {b1} and {b2} are not equal" + finally: + accelerator.dataloader_config = old_dataloader_config + + +def test_stateful_dataloader_save_state(accelerator): + """ + Tests that a stateful dataloader can be iterated over, saved after a few batches using `Accelerator.save_state`, + and then resumed from the saved state. + + The result should be the same as the rest of the data that iterated over after saving. + """ + old_dataloader_config = accelerator.dataloader_config + try: + with tempfile.TemporaryDirectory() as tmpdir: + accelerator.dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=True) + prepared_dl = create_dataloader( + accelerator, dataset_size=32 * accelerator.num_processes, batch_size=4, iterable=True, shuffle=True + ) + untrained_batches = [] + # Calculate what step that will be + total_batches = 32 * accelerator.num_processes // (4 * accelerator.num_processes) + last_batch_num = total_batches - 1 + for step, batch in enumerate(prepared_dl): + # Step just before + if step == last_batch_num - 1: + accelerator.save_state(tmpdir) + if step >= last_batch_num: + # Otherwise grab the "unseen" batches + untrained_batches.append(batch) + not_skipped_batches = accelerator.gather(untrained_batches) + accelerator.load_state(tmpdir) + resumed_batches = [] + for batch in prepared_dl: + resumed_batches.append(batch) + resumed_batches = accelerator.gather(resumed_batches) + for b1, b2 in zip(not_skipped_batches, resumed_batches): + for v1, v2 in zip(b1, b2): + assert torch.equal(v1, v2), f"Batch {b1} and {b2} are not equal" + finally: + accelerator.dataloader_config = old_dataloader_config + + +def main(): + accelerator = create_accelerator() + torch.manual_seed(accelerator.process_index) + + accelerator.print("Test that even_batches variable ensures uniform batches across processes") + test_default_ensures_even_batch_sizes() + + accelerator.print("Run tests with even_batches disabled") + test_can_disable_even_batches() + + accelerator.print("Test joining uneven inputs") + test_can_join_uneven_inputs() + + accelerator.print("Test overriding even_batches when joining uneven inputs") + test_join_can_override_even_batches() + + accelerator.print("Test overriding even_batches for mixed dataloader types") + test_join_can_override_for_mixed_type_dataloaders() + + accelerator.print("Test overriding even_batches raises a warning for iterable dataloaders") + test_join_raises_warning_for_iterable_when_overriding_even_batches() + + accelerator.print("Test join with non DDP distributed raises warning") + original_state = accelerator.state.distributed_type + accelerator.state.distributed_type = DistributedType.FSDP + test_join_raises_warning_for_non_ddp_distributed(accelerator) + accelerator.state.distributed_type = original_state + + dataset = DummyDataset() + # Conventional Dataloader with shuffle=False + loader = DataLoader(dataset, shuffle=False, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS) + test_data_loader(loader, accelerator) + + # Conventional Dataloader with shuffle=True + loader = DataLoader(dataset, shuffle=True, batch_size=BATCH_SIZE, num_workers=NUM_WORKERS) + test_data_loader(loader, accelerator) + + # Dataloader with batch_sampler + sampler = BatchSampler(RandomSampler(dataset), batch_size=BATCH_SIZE, drop_last=False) + loader = DataLoader(dataset, batch_sampler=sampler, num_workers=NUM_WORKERS) + test_data_loader(loader, accelerator) + + # Dataloader with sampler as an instance of `BatchSampler` + sampler = BatchSampler(RandomSampler(dataset), batch_size=BATCH_SIZE, drop_last=False) + loader = DataLoader(dataset, sampler=sampler, batch_size=None, collate_fn=default_collate, num_workers=NUM_WORKERS) + test_data_loader(loader, accelerator) + test_stateful_dataloader(accelerator) + test_stateful_dataloader_save_state(accelerator) + + accelerator.end_training() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_merge_weights.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_merge_weights.py new file mode 100644 index 0000000000000000000000000000000000000000..a13908640476137b35011ed3f8dc36916c808fce --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_merge_weights.py @@ -0,0 +1,161 @@ +# 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. + +import gc +import logging +import shutil +from pathlib import Path + +import torch +from safetensors.torch import load_file +from torch.distributed.fsdp.fully_sharded_data_parallel import ShardingStrategy, StateDictType +from torch.utils.data import DataLoader + +from accelerate import Accelerator, FullyShardedDataParallelPlugin +from accelerate.commands.merge import merge_command, merge_command_parser +from accelerate.state import AcceleratorState +from accelerate.test_utils.training import RegressionDataset +from accelerate.utils import merge_fsdp_weights, patch_environment, save_fsdp_model + + +logging.basicConfig(level=logging.INFO) + +parser = merge_command_parser() + + +class TinyModel(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear1 = torch.nn.Linear(16, 16) + self.activation = torch.nn.ReLU() + self.linear2 = torch.nn.Linear(16, 16) + self.softmax = torch.nn.Softmax() + + def forward(self, x): + return self.linear2(self.activation(self.linear1(x))) + + +def setup(): + if AcceleratorState._shared_state != {}: + AcceleratorState()._reset_state() + plugin = FullyShardedDataParallelPlugin( + sharding_strategy=ShardingStrategy.FULL_SHARD, state_dict_type=StateDictType.SHARDED_STATE_DICT + ) + model = TinyModel() + with patch_environment(fsdp_auto_wrap_policy="SIZE_BASED_WRAP"): + plugin.set_auto_wrap_policy(model) + accelerator = Accelerator(fsdp_plugin=plugin) + model = accelerator.prepare(model) + return model, plugin, accelerator + + +def mock_training(accelerator, model): + train_set = RegressionDataset(length=128, seed=42) + train_dl = DataLoader(train_set, batch_size=16, shuffle=False) + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + return model + + +def check_weights(operation, state_1, state_2): + for weight_1, weight_2 in zip(state_1.values(), state_2.values()): + if str(weight_1.device) != "cuda": + weight_1 = weight_1.to("cuda") + if str(weight_2.device) != "cuda": + weight_2 = weight_2.to("cuda") + if operation == "same": + assert torch.allclose(weight_1, weight_2) + else: + assert not torch.allclose(weight_1, weight_2) + + +def check_safetensors_weights(path, model): + safe_state_dict = load_file(path / "model.safetensors") + safe_loaded_model = TinyModel() + check_weights("diff", model.state_dict(), safe_loaded_model.state_dict()) + safe_loaded_model.load_state_dict(safe_state_dict) + check_weights("same", model.state_dict(), safe_loaded_model.state_dict()) + + +def check_pytorch_weights(path, model): + nonsafe_state_dict = torch.load(path / "pytorch_model.bin") + nonsafe_loaded_model = TinyModel() + check_weights("diff", model.state_dict(), nonsafe_loaded_model.state_dict()) + nonsafe_loaded_model.load_state_dict(nonsafe_state_dict) + check_weights("same", model.state_dict(), nonsafe_loaded_model.state_dict()) + + +def test_merge_weights_safetensors(model, path): + # Should now be saved at `path/merged.safetensors` + merge_fsdp_weights(path / "pytorch_model_fsdp_0", path, safe_serialization=True) + check_safetensors_weights(path, model) + + +def test_merge_weights_command_safetensors(model, path): + args = parser.parse_args([str(path / "pytorch_model_fsdp_0"), str(path)]) + merge_command(args) + check_safetensors_weights(path, model) + + +def test_merge_weights_pytorch(model, path): + # Should now be saved at `path/merged.bin` + merge_fsdp_weights(path / "pytorch_model_fsdp_0", path, safe_serialization=False) + check_pytorch_weights(path, model) + + +def test_merge_weights_command_pytorch(model, path): + args = parser.parse_args([str(path / "pytorch_model_fsdp_0"), str(path), "--unsafe_serialization"]) + merge_command(args) + check_pytorch_weights(path, model) + + +if __name__ == "__main__": + # Note this test requires at least two accelerators! + model, plugin, accelerator = setup() + if accelerator.num_processes > 1: + try: + # Initial setup for things + out_path = Path("test_merge_weights_fsdp_weights") + if not out_path.exists(): + out_path.mkdir(parents=True, exist_ok=True) + + # Train briefly once weights aren't the baseline + model = mock_training(accelerator, model) + accelerator.wait_for_everyone() + + gc.collect() # Needed for some lingering refs after training + save_fsdp_model(plugin, accelerator, model, out_path) + accelerator.wait_for_everyone() + + # Finally we can test + test_merge_weights_safetensors(model, out_path) + test_merge_weights_command_safetensors(model, out_path) + test_merge_weights_pytorch(model, out_path) + test_merge_weights_command_pytorch(model, out_path) + except Exception: + raise + finally: + # Cleanup in case of any failures + if accelerator.is_main_process: + shutil.rmtree(out_path) + accelerator.wait_for_everyone() + accelerator.end_training() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_notebook.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_notebook.py new file mode 100644 index 0000000000000000000000000000000000000000..267c11b50b22250e781f94e3643b8895cc6aeb02 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_notebook.py @@ -0,0 +1,118 @@ +# 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. +""" +Test file to ensure that in general certain situational setups for notebooks work. +""" + +import os +import time +from multiprocessing import Queue + +from pytest import mark, raises +from torch.distributed.elastic.multiprocessing.errors import ChildFailedError + +from accelerate import PartialState, notebook_launcher +from accelerate.test_utils import require_bnb +from accelerate.utils import is_bnb_available + + +def basic_function(): + # Just prints the PartialState + print(f"PartialState:\n{PartialState()}") + + +def tough_nut_function(queue: Queue): + if queue.empty(): + return + trial = queue.get() + if trial > 0: + queue.put(trial - 1) + raise RuntimeError("The nut hasn't cracked yet! Try again.") + + print(f"PartialState:\n{PartialState()}") + + +def bipolar_sleep_function(sleep_sec: int): + state = PartialState() + if state.process_index % 2 == 0: + raise RuntimeError("I'm an even process. I don't like to sleep.") + else: + time.sleep(sleep_sec) + + +NUM_PROCESSES = int(os.environ.get("ACCELERATE_NUM_PROCESSES", 1)) + + +def test_can_initialize(): + notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES) + + +@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test static rendezvous backends") +def test_static_rdzv_backend(): + notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES, rdzv_backend="static") + + +@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test c10d rendezvous backends") +def test_c10d_rdzv_backend(): + notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES, rdzv_backend="c10d") + + +@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test fault tolerance") +def test_fault_tolerant(max_restarts: int = 3): + queue = Queue() + queue.put(max_restarts) + notebook_launcher(tough_nut_function, (queue,), num_processes=NUM_PROCESSES, max_restarts=max_restarts) + + +@mark.skipif(NUM_PROCESSES < 2, reason="Need at least 2 processes to test monitoring") +def test_monitoring(monitor_interval: float = 0.01, sleep_sec: int = 100): + start_time = time.time() + with raises(ChildFailedError, match="I'm an even process. I don't like to sleep."): + notebook_launcher( + bipolar_sleep_function, + (sleep_sec,), + num_processes=NUM_PROCESSES, + monitor_interval=monitor_interval, + ) + assert time.time() - start_time < sleep_sec, "Monitoring did not stop the process in time." + + +@require_bnb +def test_problematic_imports(): + with raises(RuntimeError, match="Please keep these imports"): + import bitsandbytes as bnb # noqa: F401 + + notebook_launcher(basic_function, (), num_processes=NUM_PROCESSES) + + +def main(): + print("Test basic notebook can be ran") + test_can_initialize() + print("Test static rendezvous backend") + test_static_rdzv_backend() + print("Test c10d rendezvous backend") + test_c10d_rdzv_backend() + print("Test fault tolerant") + test_fault_tolerant() + print("Test monitoring") + test_monitoring() + if is_bnb_available(): + print("Test problematic imports (bnb)") + test_problematic_imports() + if NUM_PROCESSES > 1: + PartialState().destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_ops.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_ops.py new file mode 100644 index 0000000000000000000000000000000000000000..e70d0fe504f2bba38394f15c26262baccce26bfd --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_ops.py @@ -0,0 +1,180 @@ +#!/usr/bin/env python + +# 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. + +import torch + +from accelerate import PartialState +from accelerate.test_utils.testing import assert_exception +from accelerate.utils.dataclasses import DistributedType +from accelerate.utils.operations import ( + DistributedOperationException, + broadcast, + copy_tensor_to_devices, + gather, + gather_object, + pad_across_processes, + reduce, +) + + +def create_tensor(state): + return (torch.arange(state.num_processes) + 1.0 + (state.num_processes * state.process_index)).to(state.device) + + +def test_gather(state): + tensor = create_tensor(state) + gathered_tensor = gather(tensor) + assert gathered_tensor.tolist() == list(range(1, state.num_processes**2 + 1)) + + +def test_gather_object(state): + # Gather objects in TorchXLA is not supported. + if state.distributed_type == DistributedType.XLA: + return + obj = [state.process_index] + gathered_obj = gather_object(obj) + assert len(gathered_obj) == state.num_processes, f"{gathered_obj}, {len(gathered_obj)} != {state.num_processes}" + assert gathered_obj == list(range(state.num_processes)), f"{gathered_obj} != {list(range(state.num_processes))}" + + +def test_gather_non_contigous(state): + # Skip this test because the 'is_contiguous' function of XLA tensor always returns True. + if state.distributed_type == DistributedType.XLA: + return + # Create a non-contiguous tensor + tensor = torch.arange(12).view(4, 3).t().to(state.device) + assert not tensor.is_contiguous() + # Shouldn't error out + _ = gather(tensor) + + +def test_broadcast(state): + tensor = create_tensor(state) + broadcasted_tensor = broadcast(tensor) + assert broadcasted_tensor.shape == torch.Size([state.num_processes]) + assert broadcasted_tensor.tolist() == list(range(1, state.num_processes + 1)) + + +def test_pad_across_processes(state): + # We need to pad the tensor with one more element if we are the main process + # to ensure that we can pad + if state.is_main_process: + tensor = torch.arange(state.num_processes + 1).to(state.device) + else: + tensor = torch.arange(state.num_processes).to(state.device) + padded_tensor = pad_across_processes(tensor) + assert padded_tensor.shape == torch.Size([state.num_processes + 1]) + if not state.is_main_process: + assert padded_tensor.tolist() == list(range(0, state.num_processes)) + [0] + + +def test_reduce_sum(state): + # For now runs on only two processes + if state.num_processes != 2: + return + tensor = create_tensor(state) + reduced_tensor = reduce(tensor, "sum") + truth_tensor = torch.tensor([4.0, 6]).to(state.device) + assert torch.allclose(reduced_tensor, truth_tensor), f"{reduced_tensor} != {truth_tensor}" + + +def test_reduce_mean(state): + # For now runs on only two processes + if state.num_processes != 2: + return + tensor = create_tensor(state) + reduced_tensor = reduce(tensor, "mean") + truth_tensor = torch.tensor([2.0, 3]).to(state.device) + assert torch.allclose(reduced_tensor, truth_tensor), f"{reduced_tensor} != {truth_tensor}" + + +def test_op_checker(state): + # Must be in a distributed state, and gathering is currently not supported in TorchXLA. + if state.distributed_type in [DistributedType.NO, DistributedType.XLA]: + return + state.debug = True + # `pad_across_processes` + if state.process_index == 0: + data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)} + else: + data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4, 5]]]).to(state.device)} + + with assert_exception(DistributedOperationException): + pad_across_processes(data, dim=0) + + # `reduce` + if state.process_index == 0: + data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)} + else: + data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]]).to(state.device)} + + with assert_exception(DistributedOperationException): + reduce(data) + + # `broadcast` + if state.process_index == 0: + data = {"tensor": torch.tensor([[0.0, 1, 2, 3, 4]]).to(state.device)} + else: + data = {"tensor": torch.tensor([[[0.0, 1, 2, 3, 4], [5, 6, 7, 8, 9]]]).to(state.device)} + + with assert_exception(DistributedOperationException): + broadcast(data) + + state.debug = False + + +def test_copy_tensor_to_devices(state): + if state.distributed_type not in [DistributedType.MULTI_GPU, DistributedType.XLA]: + return + if state.is_main_process: + tensor = torch.tensor([1, 2, 3], dtype=torch.int).to(state.device) + else: + tensor = None + tensor = copy_tensor_to_devices(tensor) + assert torch.allclose(tensor, torch.tensor([1, 2, 3], dtype=torch.int, device=state.device)) + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +def main(): + state = PartialState() + state.print(f"State: {state}") + state.print("testing gather") + test_gather(state) + state.print("testing gather_object") + test_gather_object(state) + state.print("testing gather non-contigous") + test_gather_non_contigous(state) + state.print("testing broadcast") + test_broadcast(state) + state.print("testing pad_across_processes") + test_pad_across_processes(state) + state.print("testing reduce_sum") + test_reduce_sum(state) + state.print("testing reduce_mean") + test_reduce_mean(state) + state.print("testing op_checker") + test_op_checker(state) + state.print("testing sending tensors across devices") + test_copy_tensor_to_devices(state) + state.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_script.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_script.py new file mode 100644 index 0000000000000000000000000000000000000000..1d54d098a6331608ccba3834b184184002ce6a0c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_script.py @@ -0,0 +1,829 @@ +#!/usr/bin/env python + +# 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. + +import contextlib +import io +import math +import time +from copy import deepcopy +from pathlib import Path + +import numpy as np +import torch +from torch.utils.data import DataLoader, Dataset + +from accelerate import Accelerator +from accelerate.data_loader import SeedableRandomSampler, prepare_data_loader +from accelerate.state import AcceleratorState +from accelerate.test_utils import RegressionDataset, are_the_same_tensors +from accelerate.utils import ( + DataLoaderConfiguration, + DistributedType, + gather, + is_bf16_available, + is_datasets_available, + is_ipex_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_pytest_available, + is_xpu_available, + set_seed, + synchronize_rng_states, +) + + +# TODO: remove RegressionModel4XPU once ccl support empty buffer in broadcasting. +if is_xpu_available(): + from accelerate.test_utils import RegressionModel4XPU as RegressionModel +else: + from accelerate.test_utils import RegressionModel + + +def generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler=False): + "Creates a dataloader that can also use the `SeedableRandomSampler`" + if use_seedable_sampler: + # The SeedableRandomSampler is needed during distributed setups + # for full reproducability across processes with the `DataLoader` + sampler = SeedableRandomSampler( + generator=generator, + data_source=train_set, + num_samples=len(train_set), + ) + return DataLoader(train_set, batch_size=batch_size, sampler=sampler) + else: + return DataLoader(train_set, batch_size=batch_size, shuffle=True, generator=generator) + + +def print_main(state): + print(f"Printing from the main process {state.process_index}") + + +def print_local_main(state): + print(f"Printing from the local main process {state.local_process_index}") + + +def print_last(state): + print(f"Printing from the last process {state.process_index}") + + +def print_on(state, process_idx): + print(f"Printing from process {process_idx}: {state.process_index}") + + +def process_execution_check(): + accelerator = Accelerator() + num_processes = accelerator.num_processes + # Test main_process_first context manager + path = Path("check_main_process_first.txt") + with accelerator.main_process_first(): + if accelerator.is_main_process: + time.sleep(0.1) # ensure main process takes longest + with open(path, "a+") as f: + f.write("Currently in the main process\n") + else: + with open(path, "a+") as f: + f.write("Now on another process\n") + accelerator.wait_for_everyone() + + if accelerator.is_main_process: + with open(path) as f: + text = "".join(f.readlines()) + try: + assert text.startswith("Currently in the main process\n"), "Main process was not first" + if num_processes > 1: + assert text.endswith("Now on another process\n"), "Main process was not first" + assert ( + text.count("Now on another process\n") == accelerator.num_processes - 1 + ), f"Only wrote to file {text.count('Now on another process') + 1} times, not {accelerator.num_processes}" + except AssertionError: + path.unlink() + raise + + if accelerator.is_main_process and path.exists(): + path.unlink() + accelerator.wait_for_everyone() + # Test the decorators + f = io.StringIO() + with contextlib.redirect_stdout(f): + accelerator.on_main_process(print_main)(accelerator.state) + result = f.getvalue().rstrip() + if accelerator.is_main_process: + assert result == "Printing from the main process 0", f"{result} != Printing from the main process 0" + else: + assert f.getvalue().rstrip() == "", f'{result} != ""' + f.truncate(0) + f.seek(0) + + with contextlib.redirect_stdout(f): + accelerator.on_local_main_process(print_local_main)(accelerator.state) + if accelerator.is_local_main_process: + assert f.getvalue().rstrip() == "Printing from the local main process 0" + else: + assert f.getvalue().rstrip() == "" + f.truncate(0) + f.seek(0) + + with contextlib.redirect_stdout(f): + accelerator.on_last_process(print_last)(accelerator.state) + if accelerator.is_last_process: + assert f.getvalue().rstrip() == f"Printing from the last process {accelerator.state.num_processes - 1}" + else: + assert f.getvalue().rstrip() == "" + f.truncate(0) + f.seek(0) + + for process_idx in range(num_processes): + with contextlib.redirect_stdout(f): + accelerator.on_process(print_on, process_index=process_idx)(accelerator.state, process_idx) + if accelerator.process_index == process_idx: + assert f.getvalue().rstrip() == f"Printing from process {process_idx}: {accelerator.process_index}" + else: + assert f.getvalue().rstrip() == "" + f.truncate(0) + f.seek(0) + + +def init_state_check(): + # Test we can instantiate this twice in a row. + state = AcceleratorState() + if state.local_process_index == 0: + print("Testing, testing. 1, 2, 3.") + print(state) + + +def rng_sync_check(): + state = AcceleratorState() + synchronize_rng_states(["torch"]) + assert are_the_same_tensors(torch.get_rng_state()), "RNG states improperly synchronized on CPU." + if state.distributed_type == DistributedType.MULTI_GPU: + synchronize_rng_states(["cuda"]) + assert are_the_same_tensors(torch.cuda.get_rng_state()), "RNG states improperly synchronized on GPU." + elif state.distributed_type == DistributedType.MULTI_XPU: + synchronize_rng_states(["xpu"]) + assert are_the_same_tensors(torch.xpu.get_rng_state()), "RNG states improperly synchronized on XPU." + generator = torch.Generator() + synchronize_rng_states(["generator"], generator=generator) + assert are_the_same_tensors(generator.get_state()), "RNG states improperly synchronized in generator." + + if state.local_process_index == 0: + print("All rng are properly synched.") + + +def dl_preparation_check(): + state = AcceleratorState() + length = 32 * state.num_processes + + dl = DataLoader(range(length), batch_size=8) + dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index, put_on_device=True) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result) + + print(state.process_index, result, type(dl)) + assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result." + + dl = DataLoader(range(length), batch_size=8) + dl = prepare_data_loader( + dl, + state.device, + state.num_processes, + state.process_index, + put_on_device=True, + split_batches=True, + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result) + assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result." + + if state.process_index == 0: + print("Non-shuffled dataloader passing.") + + dl = DataLoader(range(length), batch_size=8, shuffle=True) + dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index, put_on_device=True) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result).tolist() + result.sort() + assert result == list(range(length)), "Wrong shuffled dataloader result." + + dl = DataLoader(range(length), batch_size=8, shuffle=True) + dl = prepare_data_loader( + dl, + state.device, + state.num_processes, + state.process_index, + put_on_device=True, + split_batches=True, + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result).tolist() + result.sort() + assert result == list(range(length)), "Wrong shuffled dataloader result." + + if state.local_process_index == 0: + print("Shuffled dataloader passing.") + + +def central_dl_preparation_check(): + state = AcceleratorState() + length = 32 * state.num_processes + + dl = DataLoader(range(length), batch_size=8) + dl = prepare_data_loader( + dl, state.device, state.num_processes, state.process_index, put_on_device=True, dispatch_batches=True + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result) + assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result." + + dl = DataLoader(range(length), batch_size=8) + dl = prepare_data_loader( + dl, + state.device, + state.num_processes, + state.process_index, + put_on_device=True, + split_batches=True, + dispatch_batches=True, + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result) + assert torch.equal(result.cpu(), torch.arange(0, length).long()), "Wrong non-shuffled dataloader result." + + if state.process_index == 0: + print("Non-shuffled central dataloader passing.") + + dl = DataLoader(range(length), batch_size=8, shuffle=True) + dl = prepare_data_loader( + dl, state.device, state.num_processes, state.process_index, put_on_device=True, dispatch_batches=True + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result).tolist() + result.sort() + assert result == list(range(length)), "Wrong shuffled dataloader result." + + dl = DataLoader(range(length), batch_size=8, shuffle=True) + dl = prepare_data_loader( + dl, + state.device, + state.num_processes, + state.process_index, + put_on_device=True, + split_batches=True, + dispatch_batches=True, + ) + result = [] + for batch in dl: + result.append(gather(batch)) + result = torch.cat(result).tolist() + result.sort() + assert result == list(range(length)), "Wrong shuffled dataloader result." + + if state.local_process_index == 0: + print("Shuffled central dataloader passing.") + + +def custom_sampler_check(): + state = AcceleratorState() + + class CustomDataset(Dataset): + def __init__(self, data): + self.data = data + + def __len__(self): + return len(self.data) + + def __getitem__(self, index): + return self.data[index] + + class CustomBatchSampler: + def __init__(self, dataset_length: int, batch_size: int, shuffle: bool = True): + self.batch_size = batch_size + self.data_index = np.arange(dataset_length) + self.shuffle = shuffle + + def __iter__(self): + num_batches = len(self) + if self.shuffle: + index = np.random.permutation(self.data_index) + else: + index = self.data_index + output = np.array_split(index, num_batches) + yield from output + + def __len__(self): + return math.ceil(len(self.data_index) / self.batch_size) + + dataset = CustomDataset(range(32 * state.num_processes)) + sampler = CustomBatchSampler(len(dataset), batch_size=8) + dl = DataLoader(dataset, batch_sampler=sampler) + dl = prepare_data_loader(dl, state.device, state.num_processes, state.process_index) + # We need just ensure that `dl.batch_sampler` (or `dl.batch_sampler.batch_sampler` is indeed the old batch sampler + if hasattr(dl.batch_sampler, "batch_sampler"): + assert isinstance( + dl.batch_sampler.batch_sampler, CustomBatchSampler + ), "Custom sampler was changed after calling `prepare_data_loader`" + else: + assert isinstance( + dl.batch_sampler, CustomBatchSampler + ), "Custom sampler was changed after calling `prepare_data_loader`" + + +def check_seedable_sampler(): + # Set seed + set_seed(42) + train_set = RegressionDataset(length=10, seed=42) + train_dl = DataLoader(train_set, batch_size=2, shuffle=True) + + config = DataLoaderConfiguration(use_seedable_sampler=True) + accelerator = Accelerator(dataloader_config=config) + train_dl = accelerator.prepare(train_dl) + original_items = [] + for _ in range(3): + for batch in train_dl: + original_items.append(batch["x"]) + original_items = torch.cat(original_items) + + # Set seed again and the epoch + set_seed(42) + train_dl.set_epoch(0) + new_items = [] + for _ in range(3): + for batch in train_dl: + new_items.append(batch["x"]) + new_items = torch.cat(new_items) + assert torch.allclose(original_items, new_items), "Did not obtain the same items with the same seed and epoch." + + +def check_seedable_sampler_in_batch_sampler_shard(): + set_seed(42) + + config = DataLoaderConfiguration(use_seedable_sampler=True) + accelerator = Accelerator(dataloader_config=config) + assert accelerator.num_processes > 1, "This test requires more than one process." + + dataloader = DataLoader(list(range(10)), batch_size=1, shuffle=True) + prepared_data_loader = prepare_data_loader( + dataloader=dataloader, + use_seedable_sampler=True, + ) + + target_sampler = prepared_data_loader.batch_sampler.batch_sampler.sampler + assert isinstance( + target_sampler, SeedableRandomSampler + ), "Sampler in BatchSamplerShard is not SeedableRandomSampler." + + +def mock_training(length, batch_size, generator, use_seedable_sampler=False): + set_seed(42) + generator.manual_seed(42) + train_set = RegressionDataset(length=length, seed=42) + + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + for epoch in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + loss.backward() + optimizer.step() + return train_set, model + + +def training_check(use_seedable_sampler=False): + state = AcceleratorState() + generator = torch.Generator() + batch_size = 8 + length = batch_size * 4 * state.num_processes + + train_set, old_model = mock_training(length, batch_size * state.num_processes, generator, use_seedable_sampler) + assert are_the_same_tensors(old_model.a), "Did not obtain the same model on both processes." + assert are_the_same_tensors(old_model.b), "Did not obtain the same model on both processes." + + accelerator = Accelerator() + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training." + assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training." + + accelerator.print("Training yielded the same results on one CPU or distributed setup with no batch split.") + + dataloader_config = DataLoaderConfiguration(split_batches=True, use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader( + train_set, generator, batch_size * state.num_processes, use_seedable_sampler + ) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training." + assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training." + + accelerator.print("Training yielded the same results on one CPU or distributes setup with batch split.") + + if torch.cuda.is_available() or is_npu_available() or is_mlu_available() or is_musa_available(): + # Mostly a test that FP16 doesn't crash as the operation inside the model is not converted to FP16 + print("FP16 training check.") + AcceleratorState._reset_state() + dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(mixed_precision="fp16", dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training." + assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training." + + if torch.cuda.is_available(): + # Mostly a test that model.forward will have autocast when running unwrap_model(model, keep_fp32_wrapper=True) + print("Keep fp32 wrapper check.") + AcceleratorState._reset_state() + accelerator = Accelerator(mixed_precision="fp16") + + model = torch.nn.Linear(2, 4) + model = accelerator.prepare(model) + model_with_fp32_wrapper = accelerator.unwrap_model(model, keep_fp32_wrapper=True) + + # Run forward with fp16 as input. + # When the model is with mixed precision wrapper, no error will be raised. + input_tensor = torch.Tensor([1, 2]).to(dtype=torch.float16, device=accelerator.device) + output = model_with_fp32_wrapper(input_tensor) + + # BF16 support is only for CPU + TPU, and some GPU + if is_bf16_available(): + # Mostly a test that BF16 doesn't crash as the operation inside the model is not converted to BF16 + print("BF16 training check.") + AcceleratorState._reset_state() + dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(mixed_precision="bf16", dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training." + assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training." + + # IPEX support is only for CPU + if is_ipex_available(): + print("ipex BF16 training check.") + AcceleratorState._reset_state() + dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(mixed_precision="bf16", cpu=True, dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on CPU or distributed training." + assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on CPU or distributed training." + + # XPU support is only for XPU + if is_xpu_available(): + print("xpu BF16 training check.") + AcceleratorState._reset_state() + dataloader_config = DataLoaderConfiguration(use_seedable_sampler=use_seedable_sampler) + accelerator = Accelerator(mixed_precision="bf16", cpu=False, dataloader_config=dataloader_config) + train_dl = generate_baseline_dataloader(train_set, generator, batch_size, use_seedable_sampler) + model = RegressionModel() + optimizer = torch.optim.SGD(model.parameters(), lr=0.1) + + train_dl, model, optimizer = accelerator.prepare(train_dl, model, optimizer) + set_seed(42) + generator.manual_seed(42) + for _ in range(3): + for batch in train_dl: + model.zero_grad() + output = model(batch["x"]) + loss = torch.nn.functional.mse_loss(output, batch["y"]) + accelerator.backward(loss) + optimizer.step() + + model = accelerator.unwrap_model(model).cpu() + assert torch.allclose(old_model.a, model.a), "Did not obtain the same model on XPU or distributed training." + assert torch.allclose(old_model.b, model.b), "Did not obtain the same model on XPU or distributed training." + + +def test_split_between_processes_dataset(datasets_Dataset): + state = AcceleratorState() + data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes)]) + with state.split_between_processes(data, apply_padding=False) as results: + assert ( + len(results) == 2 + ), f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}" + + data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes - 1)]) + with state.split_between_processes(data, apply_padding=False) as results: + if state.is_last_process: + assert ( + len(results) == 1 + ), f"Last process did not receive a single item. Process index: {state.process_index}; Length: {len(results)}" + else: + assert ( + len(results) == 2 + ), f"One of the intermediate processes did not receive two items. Process index: {state.process_index}; Length: {len(results)}" + + data = datasets_Dataset.from_list([dict(k=v) for v in range(2 * state.num_processes - 1)]) + with state.split_between_processes(data, apply_padding=True) as results: + if state.num_processes == 1: + assert ( + len(results) == 1 + ), f"Single process did not receive a single item. Process index: {state.process_index}; Length: {len(results)}" + else: + assert ( + len(results) == 2 + ), f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}" + + state.wait_for_everyone() + + +def test_split_between_processes_list(): + state = AcceleratorState() + data = list(range(0, 2 * state.num_processes)) + with state.split_between_processes(data) as results: + assert ( + len(results) == 2 + ), f"Each process did not have two items. Process index: {state.process_index}; Length: {len(results)}" + + data = list(range(0, (3 * state.num_processes) - 1)) + with state.split_between_processes(data, apply_padding=True) as results: + if state.is_last_process: + # Test that the last process gets the extra item(s) + num_samples_per_device = math.ceil(len(data) / state.num_processes) + assert ( + len(results) == num_samples_per_device + ), f"Last process did not get the extra item(s). Process index: {state.process_index}; Length: {len(results)}" + state.wait_for_everyone() + + +def test_split_between_processes_nested_dict(): + state = AcceleratorState() + a = [1, 2, 3, 4, 5, 6, 7, 8] + b = ["a", "b", "c", "d", "e", "f", "g", "h"] + c = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8]) + if state.num_processes in (1, 2, 4): + data = {"a": a, "b": b, "c": c} + data_copy = deepcopy(data) + with state.split_between_processes(data) as results: + if state.process_index == 0: + assert results["a"] == data_copy["a"][: 8 // state.num_processes] + elif state.num_processes == 2: + assert results["a"] == data_copy["a"][4:] + elif state.process_index == 3: + # We return a list each time + assert results["a"] == data_copy["a"][-2:], f'Expected: {data_copy["a"][-2]}, Actual: {results["a"]}' + if state.process_index == 0: + assert results["b"] == data_copy["b"][: 8 // state.num_processes] + elif state.num_processes == 2: + assert results["b"] == data_copy["b"][4:] + elif state.process_index == 3: + assert results["b"] == data_copy["b"][-2:] + if state.process_index == 0: + assert torch.allclose( + results["c"], data_copy["c"][: 8 // state.num_processes] + ), f"Did not obtain expected values on process 0, expected `{data['c'][:8 // state.num_processes]}`, received: {results['c']}" + elif state.num_processes == 2: + assert torch.allclose( + results["c"], data_copy["c"][4:] + ), f"Did not obtain expected values on process 2, expected `{data['c'][4:]}`, received: {results['c']}" + elif state.process_index == 3: + assert torch.allclose( + results["c"], data_copy["c"][-2:] + ), f"Did not obtain expected values on process 4, expected `{data['c'][-2:]}`, received: {results['c']}" + + state.wait_for_everyone() + + +def test_split_between_processes_tensor(): + state = AcceleratorState() + if state.num_processes > 1: + data = torch.tensor([[0, 1, 2, 3], [4, 5, 6, 7]]).to(state.device) + with state.split_between_processes(data) as results: + if state.process_index == 0: + assert torch.allclose(results, torch.tensor([0, 1, 2, 3]).to(state.device)) + else: + assert torch.allclose(results, torch.tensor([4, 5, 6, 7]).to(state.device)) + state.wait_for_everyone() + + +def test_split_between_processes_evenly(): + state = AcceleratorState() + if state.num_processes in (1, 2, 4, 8): + data = list(range(17)) + num_samples_per_process = len(data) // state.num_processes + num_extras = len(data) % state.num_processes + with state.split_between_processes(data) as results: + if state.process_index < num_extras: + assert ( + len(results) == num_samples_per_process + 1 + ), f"Each Process should have even elements. Expected: {num_samples_per_process + 1}, Actual: {len(results)}" + else: + assert ( + len(results) == num_samples_per_process + ), f"Each Process should have even elements. Expected: {num_samples_per_process}, Actual: {len(results)}" + state.wait_for_everyone() + + +def test_trigger(): + accelerator = Accelerator() + # should start with being false + assert accelerator.check_trigger() is False + + # set a breakpoint on the main process + if accelerator.is_main_process: + accelerator.set_trigger() + + # check it's been activated across all processes + # calls `all_reduce` and triggers a sync + assert accelerator.check_trigger() is True + + # check it's been reset after the sync + assert accelerator.check_trigger() is False + + +def test_reinstantiated_state(): + import pytest + + AcceleratorState._reset_state() + simple_model = torch.nn.Linear(1, 1) + # First define an accelerator + accelerator = Accelerator() + # Then call `reset_state`, breaking the state existing in the accelerator + AcceleratorState._reset_state() + # Now try and prepare a simple model, should raise the custom error early + with pytest.raises(AttributeError) as cm: + accelerator.prepare(simple_model) + assert "`AcceleratorState` object has no attribute" in str(cm.value.args[0]) + assert "This happens if `AcceleratorState._reset_state()`" in str(cm.value.args[0]) + + +def main(): + accelerator = Accelerator() + state = accelerator.state + if state.local_process_index == 0: + print("**Initialization**") + init_state_check() + state.wait_for_everyone() + + if state.distributed_type == DistributedType.MULTI_GPU: + num_processes_per_node = torch.cuda.device_count() + else: + num_processes_per_node = state.num_processes + + # We only run this test on non-multinode + if num_processes_per_node == state.num_processes: + if state.process_index == 0: + print("\n**Test process execution**") + process_execution_check() + + if state.process_index == 0: + print("\n**Test split between processes as a list**") + test_split_between_processes_list() + + if state.process_index == 0: + print("\n**Test split between processes as a dict**") + test_split_between_processes_nested_dict() + + if state.process_index == 0: + print("\n**Test split between processes as a tensor**") + test_split_between_processes_tensor() + + if state.process_index == 0: + print("\n**Test split between processes evenly**") + test_split_between_processes_evenly() + + if state.process_index == 0: + print("\n**Test split between processes as a datasets.Dataset**") + if is_datasets_available(): + from datasets import Dataset as datasets_Dataset + + test_split_between_processes_dataset(datasets_Dataset) + else: + print("Skipped because Hugging Face datasets is not available") + + if state.local_process_index == 0: + print("\n**Test random number generator synchronization**") + rng_sync_check() + + if state.local_process_index == 0: + print("\n**DataLoader integration test**") + dl_preparation_check() + if state.distributed_type != DistributedType.XLA: + central_dl_preparation_check() + custom_sampler_check() + check_seedable_sampler() + + if state.num_processes > 1: + check_seedable_sampler_in_batch_sampler_shard() + + # Trainings are not exactly the same in DeepSpeed and CPU mode + if state.distributed_type == DistributedType.DEEPSPEED: + return + + if state.local_process_index == 0: + print("\n**Training integration test**") + training_check(use_seedable_sampler=False) + training_check(use_seedable_sampler=True) + + if state.local_process_index == 0: + print("\n**Breakpoint trigger test**") + test_trigger() + + if is_pytest_available(): + if state.local_process_index == 0: + print("\n**Test reinstantiated state**") + test_reinstantiated_state() + + state.destroy_process_group() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_sync.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_sync.py new file mode 100644 index 0000000000000000000000000000000000000000..20b5b2c752e8351371b89e0bd58193e1bffc91c7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/scripts/test_sync.py @@ -0,0 +1,404 @@ +# 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. + +from copy import deepcopy + +import torch +import torch.nn.functional as F +from torch.optim import AdamW +from torch.optim.lr_scheduler import LambdaLR +from torch.utils.data import DataLoader + +from accelerate.accelerator import Accelerator, DataLoaderConfiguration, GradientAccumulationPlugin +from accelerate.state import GradientState +from accelerate.test_utils import RegressionDataset, RegressionModel +from accelerate.utils import DistributedType, set_seed + + +def check_model_parameters(model_a, model_b, did_step, iteration, **kwargs): + for param, grad_param in zip(model_a.parameters(), model_b.parameters()): + if not param.requires_grad: + continue + if not did_step: + # Grads should not be in sync + assert ( + torch.allclose(param.grad, grad_param.grad, **kwargs) is False + ), f"Gradients in sync when they should not be at iteration {iteration}:\nmodel_a grad ({param.grad}) == model_b grad ({grad_param.grad})" + else: + # Grads should be in sync + assert ( + torch.allclose(param.grad, grad_param.grad, **kwargs) is True + ), f"Gradients not in sync when they should be at iteration {iteration}:\nmodel_a grad ({param.grad}) != model_b grad ({grad_param.grad})" + + +def step_model(model, input, target, accelerator, do_backward=True): + model.train() + output = model(input) + loss = F.mse_loss(output, target.to(output.device)) + if not do_backward: + loss /= accelerator.gradient_accumulation_steps + loss.backward() + else: + accelerator.backward(loss) + + +def get_training_setup(accelerator, sched=False): + "Returns everything needed to perform basic training" + set_seed(42) + model = RegressionModel() + ddp_model = deepcopy(model) + dset = RegressionDataset(length=80) + dataloader = DataLoader(dset, batch_size=16) + model.to(accelerator.device) + if sched: + opt = AdamW(params=model.parameters(), lr=1e-3) + ddp_opt = AdamW(params=ddp_model.parameters(), lr=1e-3) + sched = LambdaLR(opt, lr_lambda=lambda epoch: epoch**0.65) + ddp_sched = LambdaLR(ddp_opt, lr_lambda=lambda epoch: epoch**0.65) + # Make a copy of `model` + if sched: + ddp_model, ddp_opt, ddp_sched, dataloader = accelerator.prepare(ddp_model, ddp_opt, ddp_sched, dataloader) + else: + ddp_model, dataloader = accelerator.prepare(ddp_model, dataloader) + if sched: + return (model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched) + return model, ddp_model, dataloader + + +def test_noop_sync(accelerator): + # Test when on a single CPU or GPU that the context manager does nothing + model, ddp_model, dataloader = get_training_setup(accelerator) + # Use a single batch + ddp_input, ddp_target = next(iter(dataloader)).values() + for iteration in range(3): + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + # Perform our initial ground truth step in non "DDP" + step_model(model, input, target, accelerator) + # Do "gradient accumulation" (noop) + if iteration % 2 == 0: + # Accumulate grads locally + with accelerator.no_sync(ddp_model): + step_model(ddp_model, ddp_input, ddp_target, accelerator) + else: + # Sync grads + step_model(ddp_model, ddp_input, ddp_target, accelerator) + + # Since `no_sync` is a noop, `ddp_model` and `model` grads should always be in sync + check_model_parameters(model, ddp_model, True, iteration) + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + assert torch.allclose( + param.grad, ddp_param.grad + ), f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" + + # Shuffle ddp_input on each iteration + torch.manual_seed(1337 + iteration) + ddp_input = ddp_input[torch.randperm(len(ddp_input))] + + +def test_distributed_sync(accelerator): + # Test on distributed setup that context manager behaves properly + model, ddp_model, dataloader = get_training_setup(accelerator) + # Use a single batch + ddp_input, ddp_target = next(iter(dataloader)).values() + for iteration in range(3): + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + # Perform our initial ground truth step in non "DDP" + step_model(model, input, target, accelerator) + # Do "gradient accumulation" (noop) + if iteration % 2 == 0: + # Accumulate grads locally + with accelerator.no_sync(ddp_model): + step_model(ddp_model, ddp_input, ddp_target, accelerator) + else: + # Sync grads + step_model(ddp_model, ddp_input, ddp_target, accelerator) + + # DDP model and model should only be in sync when not (iteration % 2 == 0) + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + if iteration % 2 == 0: + # Grads should not be in sync + assert ( + torch.allclose(param.grad, ddp_param.grad) is False + ), f"Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})" + else: + # Grads should be in sync + assert ( + torch.allclose(param.grad, ddp_param.grad) is True + ), f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" + + # Shuffle ddp_input on each iteration + torch.manual_seed(1337 + iteration) + ddp_input = ddp_input[torch.randperm(len(ddp_input))] + + +def test_distributed_sync_multiple_fwd(accelerator): + # Test on distributed setup that context manager behaves properly when used with multiple forwards followed by multiple backwards + model, ddp_model, dataloader = get_training_setup(accelerator) + # Do multiple forwards + losses = [] + num_iterations = 3 + for iteration in range(num_iterations): + ddp_input, ddp_target = next(iter(dataloader)).values() + + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + + # Perform our initial ground truth step in non "DDP" + step_model(model, input, target, accelerator) + + # Accumulate grads locally + with accelerator.no_sync(ddp_model): + ddp_output = ddp_model(ddp_input) + loss = F.mse_loss(ddp_output, ddp_target.to(ddp_output.device)) + losses.append(loss) + + # Do multiple backwards and sync only at the last backward + for iteration in range(num_iterations): + loss = losses[iteration] + + if iteration < num_iterations - 1: + # Accumulate grads locally + accelerator.backward(loss) + + # DDP model and model should only be in sync after last backward + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + # Grads should not be in sync + assert ( + torch.allclose(param.grad, ddp_param.grad) is False + ), f"Gradients in sync when they should not be:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})" + + else: + # Sync grads if last backward + with accelerator.trigger_sync_in_backward(ddp_model): + accelerator.backward(loss) + + # DDP model and model should only be in sync after last backward + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + # Grads should be in sync + assert ( + torch.allclose(param.grad, ddp_param.grad) is True + ), f"Gradients not in sync when they should be:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" + + +def test_gradient_accumulation(split_batches=False, dispatch_batches=False, sync_each_batch=False): + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2, sync_each_batch=sync_each_batch) + accelerator = Accelerator( + split_batches=split_batches, + dispatch_batches=dispatch_batches, + gradient_accumulation_plugin=gradient_accumulation_plugin, + ) + # Test that context manager behaves properly + model, ddp_model, dataloader = get_training_setup(accelerator) + for iteration, batch in enumerate(dataloader): + ddp_input, ddp_target = batch.values() + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + # Perform our initial ground truth step in non "DDP" + step_model(model, input, target, accelerator, False) + # Do "gradient accumulation" (noop) + with accelerator.accumulate(ddp_model): + step_model(ddp_model, ddp_input, ddp_target, accelerator) + + # DDP model and model should only be in sync when not (iteration % 2 == 0) + for param, ddp_param in zip(model.parameters(), ddp_model.parameters()): + if not param.requires_grad: + continue + if ((iteration + 1) % 2 == 0) or (iteration == len(dataloader) - 1) or sync_each_batch: + # Grads should be in sync + assert ( + torch.allclose(param.grad, ddp_param.grad) is True + ), f"Gradients not in sync when they should be at iteration {iteration}:\nModel grad ({param.grad}) != DDP grad ({ddp_param.grad})" + else: + # Grads should not be in sync + assert ( + torch.allclose(param.grad, ddp_param.grad) is False + ), f"Gradients in sync when they should not be at iteration {iteration}:\nModel grad ({param.grad}) == DDP grad ({ddp_param.grad})" + + # Shuffle ddp_input on each iteration + torch.manual_seed(1337 + iteration) + ddp_input = ddp_input[torch.randperm(len(ddp_input))] + GradientState._reset_state() + + +def test_gradient_accumulation_with_opt_and_scheduler( + split_batches=False, dispatch_batches=False, sync_each_batch=False +): + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2, sync_each_batch=sync_each_batch) + dataloader_config = DataLoaderConfiguration(split_batches=split_batches, dispatch_batches=dispatch_batches) + accelerator = Accelerator( + dataloader_config=dataloader_config, + gradient_accumulation_plugin=gradient_accumulation_plugin, + ) + # Test that context manager behaves properly + model, opt, sched, dataloader, ddp_model, ddp_opt, ddp_sched = get_training_setup(accelerator, True) + for iteration, batch in enumerate(dataloader): + ddp_input, ddp_target = batch.values() + # Gather the distributed inputs and targs for the base model + input, target = accelerator.gather((ddp_input, ddp_target)) + input, target = input.to(accelerator.device), target.to(accelerator.device) + # Perform our initial ground truth step in non "DDP" + model.train() + ddp_model.train() + step_model(model, input, target, accelerator, False) + opt.step() + + if ((iteration + 1) % 2 == 0) or ((iteration + 1) == len(dataloader)): + if split_batches: + sched.step() + else: + for _ in range(accelerator.num_processes): + sched.step() + + # Perform gradient accumulation under wrapper + with accelerator.accumulate(ddp_model): + step_model(ddp_model, ddp_input, ddp_target, accelerator) + ddp_opt.step() + ddp_sched.step() + + # Learning rates should be the same + assert ( + opt.param_groups[0]["lr"] == ddp_opt.param_groups[0]["lr"] + ), f'Learning rates found in each optimizer did not align\nopt: {opt.param_groups[0]["lr"]}\nDDP opt: {ddp_opt.param_groups[0]["lr"]}\n' + did_step = (((iteration + 1) % 2) == 0) or ((iteration + 1) == len(dataloader)) + if accelerator.num_processes > 1: + check_model_parameters( + model, + ddp_model, + did_step or sync_each_batch, # syncs at each grad_accum interval of if sync_each_batch==True + iteration, + rtol=1e-3, # needs a relative tolerance due to roundoff errors + ) + + if did_step: + opt.zero_grad() # flush gradients every accum step + ddp_opt.zero_grad() + + # Shuffle ddp_input on each iteration + torch.manual_seed(1337 + iteration) + GradientState._reset_state() + + +def test_dataloader_break(): + accelerator = Accelerator() + first_dset = RegressionDataset(length=80) + first_dataloader = DataLoader(first_dset, batch_size=16) + second_dset = RegressionDataset(length=96) + second_dataloader = DataLoader(second_dset, batch_size=16) + first_dataloader, second_dataloader = accelerator.prepare(first_dataloader, second_dataloader) + + assert accelerator.gradient_state.active_dataloader is None + for iteration, _ in enumerate(first_dataloader): + assert id(accelerator.gradient_state.active_dataloader) == id(first_dataloader) + if iteration < len(first_dataloader) - 1: + assert not accelerator.gradient_state.end_of_dataloader + if iteration == 1: + for batch_num, _ in enumerate(second_dataloader): + assert id(accelerator.gradient_state.active_dataloader) == id(second_dataloader) + if batch_num < len(second_dataloader) - 1: + assert not accelerator.gradient_state.end_of_dataloader + else: + assert accelerator.gradient_state.end_of_dataloader + else: + assert accelerator.gradient_state.end_of_dataloader + assert accelerator.gradient_state.active_dataloader is None + + +def main(): + accelerator = Accelerator() + state = accelerator.state + if state.local_process_index == 0: + print("**Test `accumulate` gradient accumulation with dataloader break**") + if state.distributed_type != DistributedType.XLA: + test_dataloader_break() + if state.distributed_type == DistributedType.NO: + if state.local_process_index == 0: + print("**Test NOOP `no_sync` context manager**") + test_noop_sync(accelerator) + if state.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_CPU, + ): + if state.local_process_index == 0: + print("**Test Distributed `no_sync` context manager**") + test_distributed_sync(accelerator) + if state.local_process_index == 0: + print("**Test Distributed `no_sync` context manager with multiple forwards**") + test_distributed_sync_multiple_fwd(accelerator) + if state.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + ): + for split_batch in [True, False]: + for dispatch_batches in [True, False]: + for sync_each_batch in [True, False]: + if state.local_process_index == 0: + print( + "**Test `accumulate` gradient accumulation, ", + f"`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}` and `sync_each_batch={sync_each_batch}`**", + ) + test_gradient_accumulation(split_batch, dispatch_batches, sync_each_batch) + + # Currently will break on torch 2.0 +, need to investigate why + if state.local_process_index == 0: + print( + "**Test `accumulate` gradient accumulation with optimizer and scheduler, ", + "`split_batches=False`, `dispatch_batches=False`, `sync_each_batch=False`**", + ) + test_gradient_accumulation_with_opt_and_scheduler() + if state.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_NPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + ): + for split_batch in [True, False]: + for dispatch_batches in [True, False]: + for sync_each_batch in [True, False]: + if not split_batch and not dispatch_batches and not sync_each_batch: + continue + if state.local_process_index == 0: + print( + "**Test `accumulate` gradient accumulation with optimizer and scheduler, ", + f"`split_batches={split_batch}` and `dispatch_batches={dispatch_batches}` and `sync_each_batch={sync_each_batch}`**", + ) + test_gradient_accumulation_with_opt_and_scheduler(split_batch, dispatch_batches, sync_each_batch) + state.destroy_process_group() + + +def _mp_fn(index): + # For xla_spawn (TPUs) + main() + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/testing.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/testing.py new file mode 100644 index 0000000000000000000000000000000000000000..5b9305c5c9b759dab37e87b284848e69517e9f41 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/testing.py @@ -0,0 +1,689 @@ +# 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. + +import asyncio +import inspect +import io +import os +import shutil +import subprocess +import sys +import tempfile +import unittest +from contextlib import contextmanager +from functools import partial +from pathlib import Path +from typing import List, Union +from unittest import mock + +import torch + +import accelerate + +from ..state import AcceleratorState, PartialState +from ..utils import ( + gather, + is_bnb_available, + is_clearml_available, + is_comet_ml_available, + is_cuda_available, + is_datasets_available, + is_deepspeed_available, + is_dvclive_available, + is_import_timer_available, + is_mlu_available, + is_mps_available, + is_musa_available, + is_npu_available, + is_pandas_available, + is_pippy_available, + is_schedulefree_available, + is_tensorboard_available, + is_timm_available, + is_torch_version, + is_torch_xla_available, + is_torchdata_stateful_dataloader_available, + is_torchvision_available, + is_transformer_engine_available, + is_transformers_available, + is_triton_available, + is_wandb_available, + is_xpu_available, + str_to_bool, +) + + +def get_backend(): + if is_torch_xla_available(): + return "xla", torch.cuda.device_count(), torch.cuda.memory_allocated + elif is_cuda_available(): + return "cuda", torch.cuda.device_count(), torch.cuda.memory_allocated + elif is_mps_available(min_version="2.0"): + return "mps", 1, torch.mps.current_allocated_memory + elif is_mps_available(): + return "mps", 1, lambda: 0 + elif is_mlu_available(): + return "mlu", torch.mlu.device_count(), torch.mlu.memory_allocated + elif is_musa_available(): + return "musa", torch.musa.device_count(), torch.musa.memory_allocated + elif is_npu_available(): + return "npu", torch.npu.device_count(), torch.npu.memory_allocated + elif is_xpu_available(): + return "xpu", torch.xpu.device_count(), torch.xpu.memory_allocated + else: + return "cpu", 1, lambda: 0 + + +torch_device, device_count, memory_allocated_func = get_backend() + + +def get_launch_command(**kwargs) -> list: + """ + Wraps around `kwargs` to help simplify launching from `subprocess`. + + Example: + ```python + # returns ['accelerate', 'launch', '--num_processes=2', '--device_count=2'] + get_launch_command(num_processes=2, device_count=2) + ``` + """ + command = ["accelerate", "launch"] + for k, v in kwargs.items(): + if isinstance(v, bool) and v: + command.append(f"--{k}") + elif v is not None: + command.append(f"--{k}={v}") + return command + + +DEFAULT_LAUNCH_COMMAND = get_launch_command(num_processes=device_count, monitor_interval=0.1) + + +def parse_flag_from_env(key, default=False): + try: + value = os.environ[key] + except KeyError: + # KEY isn't set, default to `default`. + _value = default + else: + # KEY is set, convert it to True or False. + try: + _value = str_to_bool(value) + except ValueError: + # More values are supported, but let's keep the message simple. + raise ValueError(f"If set, {key} must be yes or no.") + return _value + + +_run_slow_tests = parse_flag_from_env("RUN_SLOW", default=False) + + +def skip(test_case): + "Decorator that skips a test unconditionally" + return unittest.skip("Test was skipped")(test_case) + + +def slow(test_case): + """ + Decorator marking a test as slow. Slow tests are skipped by default. Set the RUN_SLOW environment variable to a + truthy value to run them. + """ + return unittest.skipUnless(_run_slow_tests, "test is slow")(test_case) + + +def require_cpu(test_case): + """ + Decorator marking a test that must be only ran on the CPU. These tests are skipped when a GPU is available. + """ + return unittest.skipUnless(torch_device == "cpu", "test requires only a CPU")(test_case) + + +def require_non_cpu(test_case): + """ + Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no + hardware accelerator available. + """ + return unittest.skipUnless(torch_device != "cpu", "test requires a GPU")(test_case) + + +def require_cuda(test_case): + """ + Decorator marking a test that requires CUDA. These tests are skipped when there are no GPU available or when + TorchXLA is available. + """ + return unittest.skipUnless(is_cuda_available() and not is_torch_xla_available(), "test requires a GPU")(test_case) + + +def require_xpu(test_case): + """ + Decorator marking a test that requires XPU. These tests are skipped when there are no XPU available. + """ + return unittest.skipUnless(is_xpu_available(), "test requires a XPU")(test_case) + + +def require_non_xpu(test_case): + """ + Decorator marking a test that should be skipped for XPU. + """ + return unittest.skipUnless(torch_device != "xpu", "test requires a non-XPU")(test_case) + + +def require_mlu(test_case): + """ + Decorator marking a test that requires MLU. These tests are skipped when there are no MLU available. + """ + return unittest.skipUnless(is_mlu_available(), "test require a MLU")(test_case) + + +def require_musa(test_case): + """ + Decorator marking a test that requires MUSA. These tests are skipped when there are no MUSA available. + """ + return unittest.skipUnless(is_musa_available(), "test require a MUSA")(test_case) + + +def require_npu(test_case): + """ + Decorator marking a test that requires NPU. These tests are skipped when there are no NPU available. + """ + return unittest.skipUnless(is_npu_available(), "test require a NPU")(test_case) + + +def require_mps(test_case): + """ + Decorator marking a test that requires MPS backend. These tests are skipped when torch doesn't support `mps` + backend. + """ + return unittest.skipUnless(is_mps_available(), "test requires a `mps` backend support in `torch`")(test_case) + + +def require_huggingface_suite(test_case): + """ + Decorator marking a test that requires transformers and datasets. These tests are skipped when they are not. + """ + return unittest.skipUnless( + is_transformers_available() and is_datasets_available(), + "test requires the Hugging Face suite", + )(test_case) + + +def require_transformers(test_case): + """ + Decorator marking a test that requires transformers. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_transformers_available(), "test requires the transformers library")(test_case) + + +def require_timm(test_case): + """ + Decorator marking a test that requires timm. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_timm_available(), "test requires the timm library")(test_case) + + +def require_torchvision(test_case): + """ + Decorator marking a test that requires torchvision. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_torchvision_available(), "test requires the torchvision library")(test_case) + + +def require_triton(test_case): + """ + Decorator marking a test that requires triton. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_triton_available(), "test requires the triton library")(test_case) + + +def require_schedulefree(test_case): + """ + Decorator marking a test that requires schedulefree. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_schedulefree_available(), "test requires the schedulefree library")(test_case) + + +def require_bnb(test_case): + """ + Decorator marking a test that requires bitsandbytes. These tests are skipped when they are not. + """ + return unittest.skipUnless(is_bnb_available(), "test requires the bitsandbytes library")(test_case) + + +def require_tpu(test_case): + """ + Decorator marking a test that requires TPUs. These tests are skipped when there are no TPUs available. + """ + return unittest.skipUnless(is_torch_xla_available(check_is_tpu=True), "test requires TPU")(test_case) + + +def require_non_torch_xla(test_case): + """ + Decorator marking a test as requiring an environment without TorchXLA. These tests are skipped when TorchXLA is + available. + """ + return unittest.skipUnless(not is_torch_xla_available(), "test requires an env without TorchXLA")(test_case) + + +def require_single_device(test_case): + """ + Decorator marking a test that requires a single device. These tests are skipped when there is no hardware + accelerator available or number of devices is more than one. + """ + return unittest.skipUnless(torch_device != "cpu" and device_count == 1, "test requires a hardware accelerator")( + test_case + ) + + +def require_single_gpu(test_case): + """ + Decorator marking a test that requires CUDA on a single GPU. These tests are skipped when there are no GPU + available or number of GPUs is more than one. + """ + return unittest.skipUnless(torch.cuda.device_count() == 1, "test requires a GPU")(test_case) + + +def require_single_xpu(test_case): + """ + Decorator marking a test that requires CUDA on a single XPU. These tests are skipped when there are no XPU + available or number of xPUs is more than one. + """ + return unittest.skipUnless(torch.xpu.device_count() == 1, "test requires a XPU")(test_case) + + +def require_multi_device(test_case): + """ + Decorator marking a test that requires a multi-device setup. These tests are skipped on a machine without multiple + devices. + """ + return unittest.skipUnless(device_count > 1, "test requires multiple hardware accelerators")(test_case) + + +def require_multi_gpu(test_case): + """ + Decorator marking a test that requires a multi-GPU setup. These tests are skipped on a machine without multiple + GPUs. + """ + return unittest.skipUnless(torch.cuda.device_count() > 1, "test requires multiple GPUs")(test_case) + + +def require_multi_xpu(test_case): + """ + Decorator marking a test that requires a multi-XPU setup. These tests are skipped on a machine without multiple + XPUs. + """ + return unittest.skipUnless(torch.xpu.device_count() > 1, "test requires multiple XPUs")(test_case) + + +def require_deepspeed(test_case): + """ + Decorator marking a test that requires DeepSpeed installed. These tests are skipped when DeepSpeed isn't installed + """ + return unittest.skipUnless(is_deepspeed_available(), "test requires DeepSpeed")(test_case) + + +def require_fsdp(test_case): + """ + Decorator marking a test that requires FSDP installed. These tests are skipped when FSDP isn't installed + """ + return unittest.skipUnless(is_torch_version(">=", "1.12.0"), "test requires torch version >= 1.12.0")(test_case) + + +def require_torch_min_version(test_case=None, version=None): + """ + Decorator marking that a test requires a particular torch version to be tested. These tests are skipped when an + installed torch version is less than the required one. + """ + if test_case is None: + return partial(require_torch_min_version, version=version) + return unittest.skipUnless(is_torch_version(">=", version), f"test requires torch version >= {version}")(test_case) + + +def require_tensorboard(test_case): + """ + Decorator marking a test that requires tensorboard installed. These tests are skipped when tensorboard isn't + installed + """ + return unittest.skipUnless(is_tensorboard_available(), "test requires Tensorboard")(test_case) + + +def require_wandb(test_case): + """ + Decorator marking a test that requires wandb installed. These tests are skipped when wandb isn't installed + """ + return unittest.skipUnless(is_wandb_available(), "test requires wandb")(test_case) + + +def require_comet_ml(test_case): + """ + Decorator marking a test that requires comet_ml installed. These tests are skipped when comet_ml isn't installed + """ + return unittest.skipUnless(is_comet_ml_available(), "test requires comet_ml")(test_case) + + +def require_clearml(test_case): + """ + Decorator marking a test that requires clearml installed. These tests are skipped when clearml isn't installed + """ + return unittest.skipUnless(is_clearml_available(), "test requires clearml")(test_case) + + +def require_dvclive(test_case): + """ + Decorator marking a test that requires dvclive installed. These tests are skipped when dvclive isn't installed + """ + return unittest.skipUnless(is_dvclive_available(), "test requires dvclive")(test_case) + + +def require_pandas(test_case): + """ + Decorator marking a test that requires pandas installed. These tests are skipped when pandas isn't installed + """ + return unittest.skipUnless(is_pandas_available(), "test requires pandas")(test_case) + + +def require_pippy(test_case): + """ + Decorator marking a test that requires pippy installed. These tests are skipped when pippy isn't installed + """ + return unittest.skipUnless(is_pippy_available(), "test requires pippy")(test_case) + + +def require_import_timer(test_case): + """ + Decorator marking a test that requires tuna interpreter installed. These tests are skipped when tuna isn't + installed + """ + return unittest.skipUnless(is_import_timer_available(), "test requires tuna interpreter")(test_case) + + +def require_transformer_engine(test_case): + """ + Decorator marking a test that requires transformers engine installed. These tests are skipped when transformers + engine isn't installed + """ + return unittest.skipUnless(is_transformer_engine_available(), "test requires transformers engine")(test_case) + + +_atleast_one_tracker_available = ( + any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available() +) + + +def require_trackers(test_case): + """ + Decorator marking that a test requires at least one tracking library installed. These tests are skipped when none + are installed + """ + return unittest.skipUnless( + _atleast_one_tracker_available, + "test requires at least one tracker to be available and for `comet_ml` to not be installed", + )(test_case) + + +def require_torchdata_stateful_dataloader(test_case): + """ + Decorator marking a test that requires torchdata.stateful_dataloader. + + These tests are skipped when torchdata with stateful_dataloader module isn't installed. + + """ + return unittest.skipUnless( + is_torchdata_stateful_dataloader_available(), "test requires torchdata.stateful_dataloader" + )(test_case) + + +class TempDirTestCase(unittest.TestCase): + """ + A TestCase class that keeps a single `tempfile.TemporaryDirectory` open for the duration of the class, wipes its + data at the start of a test, and then destroyes it at the end of the TestCase. + + Useful for when a class or API requires a single constant folder throughout it's use, such as Weights and Biases + + The temporary directory location will be stored in `self.tmpdir` + """ + + clear_on_setup = True + + @classmethod + def setUpClass(cls): + "Creates a `tempfile.TemporaryDirectory` and stores it in `cls.tmpdir`" + cls.tmpdir = Path(tempfile.mkdtemp()) + + @classmethod + def tearDownClass(cls): + "Remove `cls.tmpdir` after test suite has finished" + if os.path.exists(cls.tmpdir): + shutil.rmtree(cls.tmpdir) + + def setUp(self): + "Destroy all contents in `self.tmpdir`, but not `self.tmpdir`" + if self.clear_on_setup: + for path in self.tmpdir.glob("**/*"): + if path.is_file(): + path.unlink() + elif path.is_dir(): + shutil.rmtree(path) + + +class AccelerateTestCase(unittest.TestCase): + """ + A TestCase class that will reset the accelerator state at the end of every test. Every test that checks or utilizes + the `AcceleratorState` class should inherit from this to avoid silent failures due to state being shared between + tests. + """ + + def tearDown(self): + super().tearDown() + # Reset the state of the AcceleratorState singleton. + AcceleratorState._reset_state() + PartialState._reset_state() + + +class MockingTestCase(unittest.TestCase): + """ + A TestCase class designed to dynamically add various mockers that should be used in every test, mimicking the + behavior of a class-wide mock when defining one normally will not do. + + Useful when a mock requires specific information available only initialized after `TestCase.setUpClass`, such as + setting an environment variable with that information. + + The `add_mocks` function should be ran at the end of a `TestCase`'s `setUp` function, after a call to + `super().setUp()` such as: + ```python + def setUp(self): + super().setUp() + mocks = mock.patch.dict(os.environ, {"SOME_ENV_VAR", "SOME_VALUE"}) + self.add_mocks(mocks) + ``` + """ + + def add_mocks(self, mocks: Union[mock.Mock, List[mock.Mock]]): + """ + Add custom mocks for tests that should be repeated on each test. Should be called during + `MockingTestCase.setUp`, after `super().setUp()`. + + Args: + mocks (`mock.Mock` or list of `mock.Mock`): + Mocks that should be added to the `TestCase` after `TestCase.setUpClass` has been run + """ + self.mocks = mocks if isinstance(mocks, (tuple, list)) else [mocks] + for m in self.mocks: + m.start() + self.addCleanup(m.stop) + + +def are_the_same_tensors(tensor): + state = AcceleratorState() + tensor = tensor[None].clone().to(state.device) + tensors = gather(tensor).cpu() + tensor = tensor[0].cpu() + for i in range(tensors.shape[0]): + if not torch.equal(tensors[i], tensor): + return False + return True + + +class _RunOutput: + def __init__(self, returncode, stdout, stderr): + self.returncode = returncode + self.stdout = stdout + self.stderr = stderr + + +async def _read_stream(stream, callback): + while True: + line = await stream.readline() + if line: + callback(line) + else: + break + + +async def _stream_subprocess(cmd, env=None, stdin=None, timeout=None, quiet=False, echo=False) -> _RunOutput: + if echo: + print("\nRunning: ", " ".join(cmd)) + + p = await asyncio.create_subprocess_exec( + cmd[0], + *cmd[1:], + stdin=stdin, + stdout=asyncio.subprocess.PIPE, + stderr=asyncio.subprocess.PIPE, + env=env, + ) + + # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe + # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait + # + # If it starts hanging, will need to switch to the following code. The problem is that no data + # will be seen until it's done and if it hangs for example there will be no debug info. + # out, err = await p.communicate() + # return _RunOutput(p.returncode, out, err) + + out = [] + err = [] + + def tee(line, sink, pipe, label=""): + line = line.decode("utf-8").rstrip() + sink.append(line) + if not quiet: + print(label, line, file=pipe) + + # XXX: the timeout doesn't seem to make any difference here + await asyncio.wait( + [ + asyncio.create_task(_read_stream(p.stdout, lambda l: tee(l, out, sys.stdout, label="stdout:"))), + asyncio.create_task(_read_stream(p.stderr, lambda l: tee(l, err, sys.stderr, label="stderr:"))), + ], + timeout=timeout, + ) + return _RunOutput(await p.wait(), out, err) + + +def execute_subprocess_async(cmd: list, env=None, stdin=None, timeout=180, quiet=False, echo=True) -> _RunOutput: + # Cast every path in `cmd` to a string + for i, c in enumerate(cmd): + if isinstance(c, Path): + cmd[i] = str(c) + loop = asyncio.get_event_loop() + result = loop.run_until_complete( + _stream_subprocess(cmd, env=env, stdin=stdin, timeout=timeout, quiet=quiet, echo=echo) + ) + + cmd_str = " ".join(cmd) + if result.returncode > 0: + stderr = "\n".join(result.stderr) + raise RuntimeError( + f"'{cmd_str}' failed with returncode {result.returncode}\n\n" + f"The combined stderr from workers follows:\n{stderr}" + ) + + return result + + +class SubprocessCallException(Exception): + pass + + +def run_command(command: List[str], return_stdout=False, env=None): + """ + Runs `command` with `subprocess.check_output` and will potentially return the `stdout`. Will also properly capture + if an error occured while running `command` + """ + # Cast every path in `command` to a string + for i, c in enumerate(command): + if isinstance(c, Path): + command[i] = str(c) + if env is None: + env = os.environ.copy() + try: + output = subprocess.check_output(command, stderr=subprocess.STDOUT, env=env) + if return_stdout: + if hasattr(output, "decode"): + output = output.decode("utf-8") + return output + except subprocess.CalledProcessError as e: + raise SubprocessCallException( + f"Command `{' '.join(command)}` failed with the following error:\n\n{e.output.decode()}" + ) from e + + +def path_in_accelerate_package(*components: str) -> Path: + """ + Get a path within the `accelerate` package's directory. + + Args: + *components: Components of the path to join after the package directory. + + Returns: + `Path`: The path to the requested file or directory. + """ + + accelerate_package_dir = Path(inspect.getfile(accelerate)).parent + return accelerate_package_dir.joinpath(*components) + + +@contextmanager +def assert_exception(exception_class: Exception, msg: str = None) -> bool: + """ + Context manager to assert that the right `Exception` class was raised. + + If `msg` is provided, will check that the message is contained in the raised exception. + """ + was_ran = False + try: + yield + was_ran = True + except Exception as e: + assert isinstance(e, exception_class), f"Expected exception of type {exception_class} but got {type(e)}" + if msg is not None: + assert msg in str(e), f"Expected message '{msg}' to be in exception but got '{str(e)}'" + if was_ran: + raise AssertionError(f"Expected exception of type {exception_class} but ran without issue.") + + +def capture_call_output(func, *args, **kwargs): + """ + Takes in a `func` with `args` and `kwargs` and returns the captured stdout as a string + """ + captured_output = io.StringIO() + original_stdout = sys.stdout + try: + sys.stdout = captured_output + func(*args, **kwargs) + except Exception as e: + raise e + finally: + sys.stdout = original_stdout + return captured_output.getvalue() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/training.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/training.py new file mode 100644 index 0000000000000000000000000000000000000000..d89cfd3c71546871d00cb9c2a5cd07494c46cbfe --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/test_utils/training.py @@ -0,0 +1,101 @@ +# 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. + +import numpy as np +import torch +from torch.utils.data import DataLoader + +from accelerate.utils.dataclasses import DistributedType + + +class RegressionDataset: + def __init__(self, a=2, b=3, length=64, seed=None): + rng = np.random.default_rng(seed) + self.length = length + self.x = rng.normal(size=(length,)).astype(np.float32) + self.y = a * self.x + b + rng.normal(scale=0.1, size=(length,)).astype(np.float32) + + def __len__(self): + return self.length + + def __getitem__(self, i): + return {"x": self.x[i], "y": self.y[i]} + + +class RegressionModel4XPU(torch.nn.Module): + def __init__(self, a=0, b=0, double_output=False): + super().__init__() + self.a = torch.nn.Parameter(torch.tensor([2, 3]).float()) + self.b = torch.nn.Parameter(torch.tensor([2, 3]).float()) + self.first_batch = True + + def forward(self, x=None): + if self.first_batch: + print(f"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}") + self.first_batch = False + return x * self.a[0] + self.b[0] + + +class RegressionModel(torch.nn.Module): + def __init__(self, a=0, b=0, double_output=False): + super().__init__() + self.a = torch.nn.Parameter(torch.tensor(a).float()) + self.b = torch.nn.Parameter(torch.tensor(b).float()) + self.first_batch = True + + def forward(self, x=None): + if self.first_batch: + print(f"Model dtype: {self.a.dtype}, {self.b.dtype}. Input dtype: {x.dtype}") + self.first_batch = False + return x * self.a + self.b + + +def mocked_dataloaders(accelerator, batch_size: int = 16): + from datasets import load_dataset + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained("bert-base-cased") + data_files = {"train": "tests/test_samples/MRPC/train.csv", "validation": "tests/test_samples/MRPC/dev.csv"} + datasets = load_dataset("csv", data_files=data_files) + label_list = datasets["train"].unique("label") + + label_to_id = {v: i for i, v in enumerate(label_list)} + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer( + examples["sentence1"], examples["sentence2"], truncation=True, max_length=None, padding="max_length" + ) + if "label" in examples: + outputs["labels"] = [label_to_id[l] for l in examples["label"]] + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["sentence1", "sentence2", "label"], + ) + + def collate_fn(examples): + # On TPU it's best to pad everything to the same length or training will be very slow. + if accelerator.distributed_type == DistributedType.XLA: + return tokenizer.pad(examples, padding="max_length", max_length=128, return_tensors="pt") + return tokenizer.pad(examples, padding="longest", return_tensors="pt") + + # Instantiate dataloaders. + train_dataloader = DataLoader(tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=2) + eval_dataloader = DataLoader(tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=1) + + return train_dataloader, eval_dataloader diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/tracking.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/tracking.py new file mode 100644 index 0000000000000000000000000000000000000000..5efba19bc6769d9c70ea8b17b8da784b908f529f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/tracking.py @@ -0,0 +1,1023 @@ +# 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. + +# Expectation: +# Provide a project dir name, then each type of logger gets stored in project/{`logging_dir`} + +import json +import os +import time +from functools import wraps +from typing import Any, Dict, List, Optional, Union + +import yaml + +from .logging import get_logger +from .state import PartialState +from .utils import ( + LoggerType, + is_aim_available, + is_clearml_available, + is_comet_ml_available, + is_dvclive_available, + is_mlflow_available, + is_tensorboard_available, + is_wandb_available, + listify, +) + + +_available_trackers = [] + +if is_tensorboard_available(): + _available_trackers.append(LoggerType.TENSORBOARD) + +if is_wandb_available(): + _available_trackers.append(LoggerType.WANDB) + +if is_comet_ml_available(): + _available_trackers.append(LoggerType.COMETML) + +if is_aim_available(): + _available_trackers.append(LoggerType.AIM) + +if is_mlflow_available(): + _available_trackers.append(LoggerType.MLFLOW) + +if is_clearml_available(): + _available_trackers.append(LoggerType.CLEARML) + +if is_dvclive_available(): + _available_trackers.append(LoggerType.DVCLIVE) + +logger = get_logger(__name__) + + +def on_main_process(function): + """ + Decorator to selectively run the decorated function on the main process only based on the `main_process_only` + attribute in a class. + + Checks at function execution rather than initialization time, not triggering the initialization of the + `PartialState`. + """ + + @wraps(function) + def execute_on_main_process(self, *args, **kwargs): + if getattr(self, "main_process_only", False): + return PartialState().on_main_process(function)(self, *args, **kwargs) + else: + return function(self, *args, **kwargs) + + return execute_on_main_process + + +def get_available_trackers(): + "Returns a list of all supported available trackers in the system" + return _available_trackers + + +class GeneralTracker: + """ + A base Tracker class to be used for all logging integration implementations. + + Each function should take in `**kwargs` that will automatically be passed in from a base dictionary provided to + [`Accelerator`]. + + Should implement `name`, `requires_logging_directory`, and `tracker` properties such that: + + `name` (`str`): String representation of the tracker class name, such as "TensorBoard" `requires_logging_directory` + (`bool`): Whether the logger requires a directory to store their logs. `tracker` (`object`): Should return internal + tracking mechanism used by a tracker class (such as the `run` for wandb) + + Implementations can also include a `main_process_only` (`bool`) attribute to toggle if relevent logging, init, and + other functions should occur on the main process or across all processes (by default will use `True`) + """ + + main_process_only = True + + def __init__(self, _blank=False): + if not _blank: + err = "" + if not hasattr(self, "name"): + err += "`name`" + if not hasattr(self, "requires_logging_directory"): + if len(err) > 0: + err += ", " + err += "`requires_logging_directory`" + + # as tracker is a @property that relies on post-init + if "tracker" not in dir(self): + if len(err) > 0: + err += ", " + err += "`tracker`" + if len(err) > 0: + raise NotImplementedError( + f"The implementation for this tracker class is missing the following " + f"required attributes. Please define them in the class definition: " + f"{err}" + ) + + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Implementations should use the experiment configuration + functionality of a tracking API. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + pass + + def log(self, values: dict, step: Optional[int], **kwargs): + """ + Logs `values` to the current run. Base `log` implementations of a tracking API should go in here, along with + special behavior for the `step parameter. + + Args: + values (Dictionary `str` to `str`, `float`, or `int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + """ + pass + + def finish(self): + """ + Should run any finalizing functions within the tracking API. If the API should not have one, just don't + overwrite that method. + """ + pass + + +class TensorBoardTracker(GeneralTracker): + """ + A `Tracker` class that supports `tensorboard`. Should be initialized at the start of your script. + + Args: + run_name (`str`): + The name of the experiment run + logging_dir (`str`, `os.PathLike`): + Location for TensorBoard logs to be stored. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `tensorboard.SummaryWriter.__init__` method. + """ + + name = "tensorboard" + requires_logging_directory = True + + @on_main_process + def __init__(self, run_name: str, logging_dir: Union[str, os.PathLike], **kwargs): + try: + from torch.utils import tensorboard + except ModuleNotFoundError: + import tensorboardX as tensorboard + super().__init__() + self.run_name = run_name + self.logging_dir = os.path.join(logging_dir, run_name) + self.writer = tensorboard.SummaryWriter(self.logging_dir, **kwargs) + logger.debug(f"Initialized TensorBoard project {self.run_name} logging to {self.logging_dir}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.writer + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the + hyperparameters in a yaml file for future use. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + self.writer.add_hparams(values, metric_dict={}) + self.writer.flush() + project_run_name = time.time() + dir_name = os.path.join(self.logging_dir, str(project_run_name)) + os.makedirs(dir_name, exist_ok=True) + with open(os.path.join(dir_name, "hparams.yml"), "w") as outfile: + try: + yaml.dump(values, outfile) + except yaml.representer.RepresenterError: + logger.error("Serialization to store hyperparameters failed") + raise + logger.debug("Stored initial configuration hyperparameters to TensorBoard and hparams yaml file") + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of + `str` to `float`/`int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to either `SummaryWriter.add_scaler`, + `SummaryWriter.add_text`, or `SummaryWriter.add_scalers` method based on the contents of `values`. + """ + values = listify(values) + for k, v in values.items(): + if isinstance(v, (int, float)): + self.writer.add_scalar(k, v, global_step=step, **kwargs) + elif isinstance(v, str): + self.writer.add_text(k, v, global_step=step, **kwargs) + elif isinstance(v, dict): + self.writer.add_scalars(k, v, global_step=step, **kwargs) + self.writer.flush() + logger.debug("Successfully logged to TensorBoard") + + @on_main_process + def log_images(self, values: dict, step: Optional[int], **kwargs): + """ + Logs `images` to the current run. + + Args: + values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`): + Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `SummaryWriter.add_image` method. + """ + for k, v in values.items(): + self.writer.add_images(k, v, global_step=step, **kwargs) + logger.debug("Successfully logged images to TensorBoard") + + @on_main_process + def finish(self): + """ + Closes `TensorBoard` writer + """ + self.writer.close() + logger.debug("TensorBoard writer closed") + + +class WandBTracker(GeneralTracker): + """ + A `Tracker` class that supports `wandb`. Should be initialized at the start of your script. + + Args: + run_name (`str`): + The name of the experiment run. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `wandb.init` method. + """ + + name = "wandb" + requires_logging_directory = False + main_process_only = False + + @on_main_process + def __init__(self, run_name: str, **kwargs): + super().__init__() + self.run_name = run_name + + import wandb + + self.run = wandb.init(project=self.run_name, **kwargs) + logger.debug(f"Initialized WandB project {self.run_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.run + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + import wandb + + wandb.config.update(values, allow_val_change=True) + logger.debug("Stored initial configuration hyperparameters to WandB") + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of + `str` to `float`/`int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `wandb.log` method. + """ + self.run.log(values, step=step, **kwargs) + logger.debug("Successfully logged to WandB") + + @on_main_process + def log_images(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `images` to the current run. + + Args: + values (Dictionary `str` to `List` of `np.ndarray` or `PIL.Image`): + Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `wandb.log` method. + """ + import wandb + + for k, v in values.items(): + self.log({k: [wandb.Image(image) for image in v]}, step=step, **kwargs) + logger.debug("Successfully logged images to WandB") + + @on_main_process + def log_table( + self, + table_name: str, + columns: List[str] = None, + data: List[List[Any]] = None, + dataframe: Any = None, + step: Optional[int] = None, + **kwargs, + ): + """ + Log a Table containing any object type (text, image, audio, video, molecule, html, etc). Can be defined either + with `columns` and `data` or with `dataframe`. + + Args: + table_name (`str`): + The name to give to the logged table on the wandb workspace + columns (list of `str`, *optional*): + The name of the columns on the table + data (List of List of Any data type, *optional*): + The data to be logged in the table + dataframe (Any data type, *optional*): + The data to be logged in the table + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + """ + import wandb + + values = {table_name: wandb.Table(columns=columns, data=data, dataframe=dataframe)} + self.log(values, step=step, **kwargs) + + @on_main_process + def finish(self): + """ + Closes `wandb` writer + """ + self.run.finish() + logger.debug("WandB run closed") + + +class CometMLTracker(GeneralTracker): + """ + A `Tracker` class that supports `comet_ml`. Should be initialized at the start of your script. + + API keys must be stored in a Comet config file. + + Args: + run_name (`str`): + The name of the experiment run. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `Experiment.__init__` method. + """ + + name = "comet_ml" + requires_logging_directory = False + + @on_main_process + def __init__(self, run_name: str, **kwargs): + super().__init__() + self.run_name = run_name + + from comet_ml import Experiment + + self.writer = Experiment(project_name=run_name, **kwargs) + logger.debug(f"Initialized CometML project {self.run_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.writer + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (Dictionary `str` to `bool`, `str`, `float` or `int`): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, `int`, or `None`. + """ + self.writer.log_parameters(values) + logger.debug("Stored initial configuration hyperparameters to CometML") + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, `int` or `dict` of `str` to `float`/`int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, `int` or `dict` of + `str` to `float`/`int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to either `Experiment.log_metric`, `Experiment.log_other`, + or `Experiment.log_metrics` method based on the contents of `values`. + """ + if step is not None: + self.writer.set_step(step) + for k, v in values.items(): + if isinstance(v, (int, float)): + self.writer.log_metric(k, v, step=step, **kwargs) + elif isinstance(v, str): + self.writer.log_other(k, v, **kwargs) + elif isinstance(v, dict): + self.writer.log_metrics(v, step=step, **kwargs) + logger.debug("Successfully logged to CometML") + + @on_main_process + def finish(self): + """ + Closes `comet-ml` writer + """ + self.writer.end() + logger.debug("CometML run closed") + + +class AimTracker(GeneralTracker): + """ + A `Tracker` class that supports `aim`. Should be initialized at the start of your script. + + Args: + run_name (`str`): + The name of the experiment run. + **kwargs (additional keyword arguments, *optional*): + Additional key word arguments passed along to the `Run.__init__` method. + """ + + name = "aim" + requires_logging_directory = True + + @on_main_process + def __init__(self, run_name: str, logging_dir: Optional[Union[str, os.PathLike]] = ".", **kwargs): + self.run_name = run_name + + from aim import Run + + self.writer = Run(repo=logging_dir, **kwargs) + self.writer.name = self.run_name + logger.debug(f"Initialized Aim project {self.run_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.writer + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (`dict`): + Values to be stored as initial hyperparameters as key-value pairs. + """ + self.writer["hparams"] = values + + @on_main_process + def log(self, values: dict, step: Optional[int], **kwargs): + """ + Logs `values` to the current run. + + Args: + values (`dict`): + Values to be logged as key-value pairs. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `Run.track` method. + """ + # Note: replace this with the dictionary support when merged + for key, value in values.items(): + self.writer.track(value, name=key, step=step, **kwargs) + + @on_main_process + def log_images(self, values: dict, step: Optional[int] = None, kwargs: Optional[Dict[str, dict]] = None): + """ + Logs `images` to the current run. + + Args: + values (`Dict[str, Union[np.ndarray, PIL.Image, Tuple[np.ndarray, str], Tuple[PIL.Image, str]]]`): + Values to be logged as key-value pairs. The values need to have type `np.ndarray` or PIL.Image. If a + tuple is provided, the first element should be the image and the second element should be the caption. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs (`Dict[str, dict]`): + Additional key word arguments passed along to the `Run.Image` and `Run.track` method specified by the + keys `aim_image` and `track`, respectively. + """ + import aim + + aim_image_kw = {} + track_kw = {} + + if kwargs is not None: + aim_image_kw = kwargs.get("aim_image", {}) + track_kw = kwargs.get("track", {}) + + for key, value in values.items(): + if isinstance(value, tuple): + img, caption = value + else: + img, caption = value, "" + aim_image = aim.Image(img, caption=caption, **aim_image_kw) + self.writer.track(aim_image, name=key, step=step, **track_kw) + + @on_main_process + def finish(self): + """ + Closes `aim` writer + """ + self.writer.close() + + +class MLflowTracker(GeneralTracker): + """ + A `Tracker` class that supports `mlflow`. Should be initialized at the start of your script. + + Args: + experiment_name (`str`, *optional*): + Name of the experiment. Environment variable MLFLOW_EXPERIMENT_NAME has priority over this argument. + logging_dir (`str` or `os.PathLike`, defaults to `"."`): + Location for mlflow logs to be stored. + run_id (`str`, *optional*): + If specified, get the run with the specified UUID and log parameters and metrics under that run. The run’s + end time is unset and its status is set to running, but the run’s other attributes (source_version, + source_type, etc.) are not changed. Environment variable MLFLOW_RUN_ID has priority over this argument. + tags (`Dict[str, str]`, *optional*): + An optional `dict` of `str` keys and values, or a `str` dump from a `dict`, to set as tags on the run. If a + run is being resumed, these tags are set on the resumed run. If a new run is being created, these tags are + set on the new run. Environment variable MLFLOW_TAGS has priority over this argument. + nested_run (`bool`, *optional*, defaults to `False`): + Controls whether run is nested in parent run. True creates a nested run. Environment variable + MLFLOW_NESTED_RUN has priority over this argument. + run_name (`str`, *optional*): + Name of new run (stored as a mlflow.runName tag). Used only when `run_id` is unspecified. + description (`str`, *optional*): + An optional string that populates the description box of the run. If a run is being resumed, the + description is set on the resumed run. If a new run is being created, the description is set on the new + run. + """ + + name = "mlflow" + requires_logging_directory = False + + @on_main_process + def __init__( + self, + experiment_name: str = None, + logging_dir: Optional[Union[str, os.PathLike]] = None, + run_id: Optional[str] = None, + tags: Optional[Union[Dict[str, Any], str]] = None, + nested_run: Optional[bool] = False, + run_name: Optional[str] = None, + description: Optional[str] = None, + ): + experiment_name = os.environ.get("MLFLOW_EXPERIMENT_NAME", experiment_name) + run_id = os.environ.get("MLFLOW_RUN_ID", run_id) + tags = os.environ.get("MLFLOW_TAGS", tags) + if isinstance(tags, str): + tags = json.loads(tags) + + nested_run = os.environ.get("MLFLOW_NESTED_RUN", nested_run) + + import mlflow + + exps = mlflow.search_experiments(filter_string=f"name = '{experiment_name}'") + if len(exps) > 0: + if len(exps) > 1: + logger.warning("Multiple experiments with the same name found. Using first one.") + experiment_id = exps[0].experiment_id + else: + experiment_id = mlflow.create_experiment( + name=experiment_name, + artifact_location=logging_dir, + tags=tags, + ) + + self.active_run = mlflow.start_run( + run_id=run_id, + experiment_id=experiment_id, + run_name=run_name, + nested=nested_run, + tags=tags, + description=description, + ) + + logger.debug(f"Initialized mlflow experiment {experiment_name}") + logger.debug( + "Make sure to log any initial configurations with `self.store_init_configuration` before training!" + ) + + @property + def tracker(self): + return self.active_run + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. + + Args: + values (`dict`): + Values to be stored as initial hyperparameters as key-value pairs. + """ + import mlflow + + for name, value in list(values.items()): + # internally, all values are converted to str in MLflow + if len(str(value)) > mlflow.utils.validation.MAX_PARAM_VAL_LENGTH: + logger.warning_once( + f'Accelerate is attempting to log a value of "{value}" for key "{name}" as a parameter. MLflow\'s' + f" log_param() only accepts values no longer than {mlflow.utils.validation.MAX_PARAM_VAL_LENGTH} characters so we dropped this attribute." + ) + del values[name] + + values_list = list(values.items()) + + # MLflow cannot log more than 100 values in one go, so we have to split it + for i in range(0, len(values_list), mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH): + mlflow.log_params(dict(values_list[i : i + mlflow.utils.validation.MAX_PARAMS_TAGS_PER_BATCH])) + + logger.debug("Stored initial configuration hyperparameters to MLflow") + + @on_main_process + def log(self, values: dict, step: Optional[int]): + """ + Logs `values` to the current run. + + Args: + values (`dict`): + Values to be logged as key-value pairs. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + """ + metrics = {} + for k, v in values.items(): + if isinstance(v, (int, float)): + metrics[k] = v + else: + logger.warning_once( + f'MLflowTracker is attempting to log a value of "{v}" of type {type(v)} for key "{k}" as a metric. ' + "MLflow's log_metric() only accepts float and int types so we dropped this attribute." + ) + import mlflow + + mlflow.log_metrics(metrics, step=step) + logger.debug("Successfully logged to mlflow") + + @on_main_process + def finish(self): + """ + End the active MLflow run. + """ + import mlflow + + mlflow.end_run() + + +class ClearMLTracker(GeneralTracker): + """ + A `Tracker` class that supports `clearml`. Should be initialized at the start of your script. + + Args: + run_name (`str`, *optional*): + Name of the experiment. Environment variables `CLEARML_PROJECT` and `CLEARML_TASK` have priority over this + argument. + **kwargs (additional keyword arguments, *optional*): + Kwargs passed along to the `Task.__init__` method. + """ + + name = "clearml" + requires_logging_directory = False + + @on_main_process + def __init__(self, run_name: str = None, **kwargs): + from clearml import Task + + current_task = Task.current_task() + self._initialized_externally = False + if current_task: + self._initialized_externally = True + self.task = current_task + return + + kwargs.setdefault("project_name", os.environ.get("CLEARML_PROJECT", run_name)) + kwargs.setdefault("task_name", os.environ.get("CLEARML_TASK", run_name)) + self.task = Task.init(**kwargs) + + @property + def tracker(self): + return self.task + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Connect configuration dictionary to the Task object. Should be run at the beginning of your experiment. + + Args: + values (`dict`): + Values to be stored as initial hyperparameters as key-value pairs. + """ + return self.task.connect_configuration(values) + + @on_main_process + def log(self, values: Dict[str, Union[int, float]], step: Optional[int] = None, **kwargs): + """ + Logs `values` dictionary to the current run. The dictionary keys must be strings. The dictionary values must be + ints or floats + + Args: + values (`Dict[str, Union[int, float]]`): + Values to be logged as key-value pairs. If the key starts with 'eval_'/'test_'/'train_', the value will + be reported under the 'eval'/'test'/'train' series and the respective prefix will be removed. + Otherwise, the value will be reported under the 'train' series, and no prefix will be removed. + step (`int`, *optional*): + If specified, the values will be reported as scalars, with the iteration number equal to `step`. + Otherwise they will be reported as single values. + kwargs: + Additional key word arguments passed along to the `clearml.Logger.report_single_value` or + `clearml.Logger.report_scalar` methods. + """ + clearml_logger = self.task.get_logger() + for k, v in values.items(): + if not isinstance(v, (int, float)): + logger.warning_once( + "Accelerator is attempting to log a value of " + f'"{v}" of type {type(v)} for key "{k}" as a scalar. ' + "This invocation of ClearML logger's report_scalar() " + "is incorrect so we dropped this attribute." + ) + continue + if step is None: + clearml_logger.report_single_value(name=k, value=v, **kwargs) + continue + title, series = ClearMLTracker._get_title_series(k) + clearml_logger.report_scalar(title=title, series=series, value=v, iteration=step, **kwargs) + + @on_main_process + def log_images(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `images` to the current run. + + Args: + values (`Dict[str, List[Union[np.ndarray, PIL.Image]]`): + Values to be logged as key-value pairs. The values need to have type `List` of `np.ndarray` or + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `clearml.Logger.report_image` method. + """ + clearml_logger = self.task.get_logger() + for k, v in values.items(): + title, series = ClearMLTracker._get_title_series(k) + clearml_logger.report_image(title=title, series=series, iteration=step, image=v, **kwargs) + + @on_main_process + def log_table( + self, + table_name: str, + columns: List[str] = None, + data: List[List[Any]] = None, + dataframe: Any = None, + step: Optional[int] = None, + **kwargs, + ): + """ + Log a Table to the task. Can be defined eitherwith `columns` and `data` or with `dataframe`. + + Args: + table_name (`str`): + The name of the table + columns (list of `str`, *optional*): + The name of the columns on the table + data (List of List of Any data type, *optional*): + The data to be logged in the table. If `columns` is not specified, then the first entry in data will be + the name of the columns of the table + dataframe (Any data type, *optional*): + The data to be logged in the table + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to the `clearml.Logger.report_table` method. + """ + to_report = dataframe + if dataframe is None: + if data is None: + raise ValueError( + "`ClearMLTracker.log_table` requires that `data` to be supplied if `dataframe` is `None`" + ) + to_report = [columns] + data if columns else data + title, series = ClearMLTracker._get_title_series(table_name) + self.task.get_logger().report_table(title=title, series=series, table_plot=to_report, iteration=step, **kwargs) + + @on_main_process + def finish(self): + """ + Close the ClearML task. If the task was initialized externally (e.g. by manually calling `Task.init`), this + function is a noop + """ + if self.task and not self._initialized_externally: + self.task.close() + + @staticmethod + def _get_title_series(name): + for prefix in ["eval", "test", "train"]: + if name.startswith(prefix + "_"): + return name[len(prefix) + 1 :], prefix + return name, "train" + + +class DVCLiveTracker(GeneralTracker): + """ + A `Tracker` class that supports `dvclive`. Should be initialized at the start of your script. + + Args: + run_name (`str`, *optional*): + Ignored for dvclive. See `kwargs` instead. + kwargs: + Additional key word arguments passed along to [`dvclive.Live()`](https://dvc.org/doc/dvclive/live). + + Example: + + ```py + from accelerate import Accelerator + + accelerator = Accelerator(log_with="dvclive") + accelerator.init_trackers(project_name="my_project", init_kwargs={"dvclive": {"dir": "my_directory"}}) + ``` + """ + + name = "dvclive" + requires_logging_directory = False + + @on_main_process + def __init__(self, run_name: Optional[str] = None, live: Optional[Any] = None, **kwargs): + from dvclive import Live + + super().__init__() + self.live = live if live is not None else Live(**kwargs) + + @property + def tracker(self): + return self.live + + @on_main_process + def store_init_configuration(self, values: dict): + """ + Logs `values` as hyperparameters for the run. Should be run at the beginning of your experiment. Stores the + hyperparameters in a yaml file for future use. + + Args: + values (Dictionary `str` to `bool`, `str`, `float`, `int`, or a List or Dict of those types): + Values to be stored as initial hyperparameters as key-value pairs. The values need to have type `bool`, + `str`, `float`, or `int`. + """ + self.live.log_params(values) + + @on_main_process + def log(self, values: dict, step: Optional[int] = None, **kwargs): + """ + Logs `values` to the current run. + + Args: + values (Dictionary `str` to `str`, `float`, or `int`): + Values to be logged as key-value pairs. The values need to have type `str`, `float`, or `int`. + step (`int`, *optional*): + The run step. If included, the log will be affiliated with this step. + kwargs: + Additional key word arguments passed along to `dvclive.Live.log_metric()`. + """ + from dvclive.plots import Metric + + if step is not None: + self.live.step = step + for k, v in values.items(): + if Metric.could_log(v): + self.live.log_metric(k, v, **kwargs) + else: + logger.warning_once( + "Accelerator attempted to log a value of " + f'"{v}" of type {type(v)} for key "{k}" as a scalar. ' + "This invocation of DVCLive's Live.log_metric() " + "is incorrect so we dropped this attribute." + ) + self.live.next_step() + + @on_main_process + def finish(self): + """ + Closes `dvclive.Live()`. + """ + self.live.end() + + +LOGGER_TYPE_TO_CLASS = { + "aim": AimTracker, + "comet_ml": CometMLTracker, + "mlflow": MLflowTracker, + "tensorboard": TensorBoardTracker, + "wandb": WandBTracker, + "clearml": ClearMLTracker, + "dvclive": DVCLiveTracker, +} + + +def filter_trackers( + log_with: List[Union[str, LoggerType, GeneralTracker]], + logging_dir: Union[str, os.PathLike] = None, +): + """ + Takes in a list of potential tracker types and checks that: + - The tracker wanted is available in that environment + - Filters out repeats of tracker types + - If `all` is in `log_with`, will return all trackers in the environment + - If a tracker requires a `logging_dir`, ensures that `logging_dir` is not `None` + + Args: + log_with (list of `str`, [`~utils.LoggerType`] or [`~tracking.GeneralTracker`], *optional*): + A list of loggers to be setup for experiment tracking. Should be one or several of: + + - `"all"` + - `"tensorboard"` + - `"wandb"` + - `"comet_ml"` + - `"mlflow"` + - `"dvclive"` + If `"all"` is selected, will pick up all available trackers in the environment and initialize them. Can + also accept implementations of `GeneralTracker` for custom trackers, and can be combined with `"all"`. + logging_dir (`str`, `os.PathLike`, *optional*): + A path to a directory for storing logs of locally-compatible loggers. + """ + loggers = [] + if log_with is not None: + if not isinstance(log_with, (list, tuple)): + log_with = [log_with] + if "all" in log_with or LoggerType.ALL in log_with: + loggers = [o for o in log_with if issubclass(type(o), GeneralTracker)] + get_available_trackers() + else: + for log_type in log_with: + if log_type not in LoggerType and not issubclass(type(log_type), GeneralTracker): + raise ValueError(f"Unsupported logging capability: {log_type}. Choose between {LoggerType.list()}") + if issubclass(type(log_type), GeneralTracker): + loggers.append(log_type) + else: + log_type = LoggerType(log_type) + if log_type not in loggers: + if log_type in get_available_trackers(): + tracker_init = LOGGER_TYPE_TO_CLASS[str(log_type)] + if tracker_init.requires_logging_directory: + if logging_dir is None: + raise ValueError( + f"Logging with `{log_type}` requires a `logging_dir` to be passed in." + ) + loggers.append(log_type) + else: + logger.debug(f"Tried adding logger {log_type}, but package is unavailable in the system.") + + return loggers diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/__init__.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ed6c77d8de6d58bfd55651113fb09461b9c9c41a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/__init__.py @@ -0,0 +1,261 @@ +# 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. +from .constants import ( + MODEL_NAME, + OPTIMIZER_NAME, + PROFILE_PATTERN_NAME, + RNG_STATE_NAME, + SAFE_MODEL_NAME, + SAFE_WEIGHTS_INDEX_NAME, + SAFE_WEIGHTS_NAME, + SAFE_WEIGHTS_PATTERN_NAME, + SAMPLER_NAME, + SCALER_NAME, + SCHEDULER_NAME, + TORCH_DISTRIBUTED_OPERATION_TYPES, + TORCH_LAUNCH_PARAMS, + WEIGHTS_INDEX_NAME, + WEIGHTS_NAME, + WEIGHTS_PATTERN_NAME, +) +from .dataclasses import ( + AutocastKwargs, + BnbQuantizationConfig, + ComputeEnvironment, + CustomDtype, + DataLoaderConfiguration, + DDPCommunicationHookType, + DeepSpeedPlugin, + DistributedDataParallelKwargs, + DistributedType, + DynamoBackend, + FP8RecipeKwargs, + FullyShardedDataParallelPlugin, + GradientAccumulationPlugin, + GradScalerKwargs, + InitProcessGroupKwargs, + KwargsHandler, + LoggerType, + MegatronLMPlugin, + PrecisionType, + ProfileKwargs, + ProjectConfiguration, + RNGType, + SageMakerDistributedType, + TensorInformation, + TorchDynamoPlugin, + add_model_config_to_megatron_parser, +) +from .environment import ( + are_libraries_initialized, + check_cuda_p2p_ib_support, + check_fp8_capability, + convert_dict_to_env_variables, + get_cpu_distributed_information, + get_gpu_info, + get_int_from_env, + parse_choice_from_env, + parse_flag_from_env, + set_numa_affinity, + str_to_bool, +) +from .imports import ( + get_ccl_version, + is_4bit_bnb_available, + is_8bit_bnb_available, + is_aim_available, + is_bf16_available, + is_bnb_available, + is_boto3_available, + is_ccl_available, + is_clearml_available, + is_comet_ml_available, + is_cuda_available, + is_datasets_available, + is_deepspeed_available, + is_dvclive_available, + is_fp8_available, + is_import_timer_available, + is_ipex_available, + is_lomo_available, + is_megatron_lm_available, + is_mlflow_available, + is_mlu_available, + is_mps_available, + is_msamp_available, + is_musa_available, + is_npu_available, + is_pandas_available, + is_peft_available, + is_pippy_available, + is_pynvml_available, + is_pytest_available, + is_rich_available, + is_sagemaker_available, + is_schedulefree_available, + is_tensorboard_available, + is_timm_available, + is_torch_xla_available, + is_torchdata_available, + is_torchdata_stateful_dataloader_available, + is_torchvision_available, + is_transformer_engine_available, + is_transformers_available, + is_triton_available, + is_wandb_available, + is_xpu_available, +) +from .modeling import ( + calculate_maximum_sizes, + check_device_map, + check_tied_parameters_in_config, + check_tied_parameters_on_same_device, + compute_module_sizes, + convert_file_size_to_int, + dtype_byte_size, + find_tied_parameters, + get_balanced_memory, + get_max_layer_size, + get_max_memory, + get_mixed_precision_context_manager, + id_tensor_storage, + infer_auto_device_map, + is_peft_model, + load_checkpoint_in_model, + load_offloaded_weights, + load_state_dict, + named_module_tensors, + retie_parameters, + set_module_tensor_to_device, + shard_checkpoint, +) +from .offload import ( + OffloadedWeightsLoader, + PrefixedDataset, + extract_submodules_state_dict, + load_offloaded_weight, + offload_state_dict, + offload_weight, + save_offload_index, +) +from .operations import ( + CannotPadNestedTensorWarning, + GatheredParameters, + broadcast, + broadcast_object_list, + concatenate, + convert_outputs_to_fp32, + convert_to_fp32, + copy_tensor_to_devices, + find_batch_size, + find_device, + gather, + gather_object, + get_data_structure, + honor_type, + ignorant_find_batch_size, + initialize_tensors, + is_namedtuple, + is_tensor_information, + is_torch_tensor, + listify, + pad_across_processes, + pad_input_tensors, + recursively_apply, + reduce, + send_to_device, + slice_tensors, +) +from .versions import compare_versions, is_torch_version + + +if is_deepspeed_available(): + from .deepspeed import ( + DeepSpeedEngineWrapper, + DeepSpeedOptimizerWrapper, + DeepSpeedSchedulerWrapper, + DummyOptim, + DummyScheduler, + HfDeepSpeedConfig, + ) + +from .bnb import has_4bit_bnb_layers, load_and_quantize_model +from .fsdp_utils import ( + disable_fsdp_ram_efficient_loading, + enable_fsdp_ram_efficient_loading, + load_fsdp_model, + load_fsdp_optimizer, + merge_fsdp_weights, + save_fsdp_model, + save_fsdp_optimizer, +) +from .launch import ( + PrepareForLaunch, + _filter_args, + prepare_deepspeed_cmd_env, + prepare_multi_gpu_env, + prepare_sagemager_args_inputs, + prepare_simple_launcher_cmd_env, + prepare_tpu, +) + +# For docs +from .megatron_lm import ( + AbstractTrainStep, + BertTrainStep, + GPTTrainStep, + MegatronLMDummyDataLoader, + MegatronLMDummyScheduler, + T5TrainStep, + avg_losses_across_data_parallel_group, +) + + +if is_megatron_lm_available(): + from .megatron_lm import ( + MegatronEngine, + MegatronLMOptimizerWrapper, + MegatronLMSchedulerWrapper, + gather_across_data_parallel_groups, + ) + from .megatron_lm import initialize as megatron_lm_initialize + from .megatron_lm import prepare_data_loader as megatron_lm_prepare_data_loader + from .megatron_lm import prepare_model_optimizer_scheduler as megatron_lm_prepare_model_optimizer_scheduler + from .megatron_lm import prepare_optimizer as megatron_lm_prepare_optimizer + from .megatron_lm import prepare_scheduler as megatron_lm_prepare_scheduler +from .memory import find_executable_batch_size, release_memory +from .other import ( + check_os_kernel, + clean_state_dict_for_safetensors, + clear_environment, + convert_bytes, + extract_model_from_parallel, + get_pretty_name, + is_port_in_use, + merge_dicts, + patch_environment, + recursive_getattr, + save, + wait_for_everyone, + write_basic_config, +) +from .random import set_seed, synchronize_rng_state, synchronize_rng_states +from .torch_xla import install_xla +from .tqdm import tqdm +from .transformer_engine import ( + apply_fp8_autowrap, + contextual_fp8_autocast, + convert_model, + has_transformer_engine_layers, +) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/bnb.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..284ee5df6e89171948745255dd33a3b2b91123a2 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/bnb.py @@ -0,0 +1,467 @@ +# 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. + + +import logging +import os +from copy import deepcopy +from typing import Dict, List, Optional, Union + +import torch +import torch.nn as nn + +from accelerate.utils.imports import ( + is_4bit_bnb_available, + is_8bit_bnb_available, +) + +from ..big_modeling import dispatch_model, init_empty_weights +from .dataclasses import BnbQuantizationConfig +from .modeling import ( + find_tied_parameters, + get_balanced_memory, + infer_auto_device_map, + load_checkpoint_in_model, + offload_weight, + set_module_tensor_to_device, +) + + +logger = logging.getLogger(__name__) + + +def load_and_quantize_model( + model: torch.nn.Module, + bnb_quantization_config: BnbQuantizationConfig, + weights_location: Union[str, os.PathLike] = None, + device_map: Optional[Dict[str, Union[int, str, torch.device]]] = None, + no_split_module_classes: Optional[List[str]] = None, + max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None, + offload_folder: Optional[Union[str, os.PathLike]] = None, + offload_state_dict: bool = False, +): + """ + This function will quantize the input model with the associated config passed in `bnb_quantization_config`. If the + model is in the meta device, we will load and dispatch the weights according to the `device_map` passed. If the + model is already loaded, we will quantize the model and put the model on the GPU, + + Args: + model (`torch.nn.Module`): + Input model. The model can be already loaded or on the meta device + bnb_quantization_config (`BnbQuantizationConfig`): + The bitsandbytes quantization parameters + weights_location (`str` or `os.PathLike`): + The folder weights_location to load. It can be: + - a path to a file containing a whole model state dict + - a path to a `.json` file containing the index to a sharded checkpoint + - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint. + - a path to a folder containing a unique pytorch_model.bin file. + device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): + A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer + name, once a given module name is inside, every submodule of it will be sent to the same device. + no_split_module_classes (`List[str]`, *optional*): + A list of layer class names that should never be split across device (for instance any layer that has a + residual connection). + max_memory (`Dict`, *optional*): + A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset. + offload_folder (`str` or `os.PathLike`, *optional*): + If the `device_map` contains any value `"disk"`, the folder where we will offload weights. + offload_state_dict (`bool`, *optional*, defaults to `False`): + If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if + the weight of the CPU state dict + the biggest shard does not fit. + + Returns: + `torch.nn.Module`: The quantized model + """ + + load_in_4bit = bnb_quantization_config.load_in_4bit + load_in_8bit = bnb_quantization_config.load_in_8bit + + if load_in_8bit and not is_8bit_bnb_available(): + raise ImportError( + "You have a version of `bitsandbytes` that is not compatible with 8bit quantization," + " make sure you have the latest version of `bitsandbytes` installed." + ) + if load_in_4bit and not is_4bit_bnb_available(): + raise ValueError( + "You have a version of `bitsandbytes` that is not compatible with 4bit quantization," + "make sure you have the latest version of `bitsandbytes` installed." + ) + + modules_on_cpu = [] + # custom device map + if isinstance(device_map, dict) and len(device_map.keys()) > 1: + modules_on_cpu = [key for key, value in device_map.items() if value in ["disk", "cpu"]] + + # We keep some modules such as the lm_head in their original dtype for numerical stability reasons + if bnb_quantization_config.skip_modules is None: + bnb_quantization_config.skip_modules = get_keys_to_not_convert(model) + + # add cpu modules to skip modules only for 4-bit modules + if load_in_4bit: + bnb_quantization_config.skip_modules.extend(modules_on_cpu) + modules_to_not_convert = bnb_quantization_config.skip_modules + + # We add the modules we want to keep in full precision + if bnb_quantization_config.keep_in_fp32_modules is None: + bnb_quantization_config.keep_in_fp32_modules = [] + keep_in_fp32_modules = bnb_quantization_config.keep_in_fp32_modules + modules_to_not_convert.extend(keep_in_fp32_modules) + + # compatibility with peft + model.is_loaded_in_4bit = load_in_4bit + model.is_loaded_in_8bit = load_in_8bit + + model_device = get_parameter_device(model) + if model_device.type != "meta": + # quantization of an already loaded model + logger.warning( + "It is not recommended to quantize a loaded model. " + "The model should be instantiated under the `init_empty_weights` context manager." + ) + model = replace_with_bnb_layers(model, bnb_quantization_config, modules_to_not_convert=modules_to_not_convert) + # convert param to the right dtype + dtype = bnb_quantization_config.torch_dtype + for name, param in model.state_dict().items(): + if any(module_to_keep_in_fp32 in name for module_to_keep_in_fp32 in keep_in_fp32_modules): + param.to(torch.float32) + if param.dtype != torch.float32: + name = name.replace(".weight", "").replace(".bias", "") + param = getattr(model, name, None) + if param is not None: + param.to(torch.float32) + elif torch.is_floating_point(param): + param.to(dtype) + if model_device.type == "cuda": + # move everything to cpu in the first place because we can't do quantization if the weights are already on cuda + model.cuda(torch.cuda.current_device()) + torch.cuda.empty_cache() + elif torch.cuda.is_available(): + model.to(torch.cuda.current_device()) + else: + raise RuntimeError("No GPU found. A GPU is needed for quantization.") + logger.info( + f"The model device type is {model_device.type}. However, cuda is needed for quantization." + "We move the model to cuda." + ) + return model + + elif weights_location is None: + raise RuntimeError( + f"`weights_location` needs to be the folder path containing the weights of the model, but we found {weights_location} " + ) + + else: + with init_empty_weights(): + model = replace_with_bnb_layers( + model, bnb_quantization_config, modules_to_not_convert=modules_to_not_convert + ) + + device_map = get_quantized_model_device_map( + model, + bnb_quantization_config, + device_map, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + ) + if offload_state_dict is None and device_map is not None and "disk" in device_map.values(): + offload_state_dict = True + + offload = any(x in list(device_map.values()) for x in ["cpu", "disk"]) + + load_checkpoint_in_model( + model, + weights_location, + device_map, + dtype=bnb_quantization_config.torch_dtype, + offload_folder=offload_folder, + offload_state_dict=offload_state_dict, + keep_in_fp32_modules=bnb_quantization_config.keep_in_fp32_modules, + offload_8bit_bnb=load_in_8bit and offload, + ) + return dispatch_model(model, device_map=device_map, offload_dir=offload_folder) + + +def get_quantized_model_device_map( + model, bnb_quantization_config, device_map=None, max_memory=None, no_split_module_classes=None +): + if device_map is None: + if torch.cuda.is_available(): + device_map = {"": torch.cuda.current_device()} + else: + raise RuntimeError("No GPU found. A GPU is needed for quantization.") + logger.info("The device_map was not initialized." "Setting device_map to `{'':torch.cuda.current_device()}`.") + + if isinstance(device_map, str): + if device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]: + raise ValueError( + "If passing a string for `device_map`, please choose 'auto', 'balanced', 'balanced_low_0' or " + "'sequential'." + ) + + special_dtypes = {} + special_dtypes.update( + { + name: bnb_quantization_config.torch_dtype + for name, _ in model.named_parameters() + if any(m in name for m in bnb_quantization_config.skip_modules) + } + ) + special_dtypes.update( + { + name: torch.float32 + for name, _ in model.named_parameters() + if any(m in name for m in bnb_quantization_config.keep_in_fp32_modules) + } + ) + + kwargs = {} + kwargs["special_dtypes"] = special_dtypes + kwargs["no_split_module_classes"] = no_split_module_classes + kwargs["dtype"] = bnb_quantization_config.target_dtype + + # get max_memory for each device. + if device_map != "sequential": + max_memory = get_balanced_memory( + model, + low_zero=(device_map == "balanced_low_0"), + max_memory=max_memory, + **kwargs, + ) + + kwargs["max_memory"] = max_memory + device_map = infer_auto_device_map(model, **kwargs) + + if isinstance(device_map, dict): + # check if don't have any quantized module on the cpu + modules_not_to_convert = bnb_quantization_config.skip_modules + bnb_quantization_config.keep_in_fp32_modules + + device_map_without_some_modules = { + key: device_map[key] for key in device_map.keys() if key not in modules_not_to_convert + } + for device in ["cpu", "disk"]: + if device in device_map_without_some_modules.values(): + if bnb_quantization_config.load_in_4bit: + raise ValueError( + """ + Some modules are dispatched on the CPU or the disk. Make sure you have enough GPU RAM to fit + the quantized model. If you want to dispatch the model on the CPU or the disk while keeping + these modules in `torch_dtype`, you need to pass a custom `device_map` to + `load_and_quantize_model`. Check + https://huggingface.co/docs/accelerate/main/en/usage_guides/quantization#offload-modules-to-cpu-and-disk + for more details. + """ + ) + else: + logger.info( + "Some modules are are offloaded to the CPU or the disk. Note that these modules will be converted to 8-bit" + ) + del device_map_without_some_modules + return device_map + + +def replace_with_bnb_layers(model, bnb_quantization_config, modules_to_not_convert=None, current_key_name=None): + """ + A helper function to replace all `torch.nn.Linear` modules by `bnb.nn.Linear8bit` modules or by `bnb.nn.Linear4bit` + modules from the `bitsandbytes`library. The function will be run recursively and replace `torch.nn.Linear` modules. + + Parameters: + model (`torch.nn.Module`): + Input model or `torch.nn.Module` as the function is run recursively. + modules_to_not_convert (`List[str]`): + Names of the modules to not quantize convert. In practice we keep the `lm_head` in full precision for + numerical stability reasons. + current_key_name (`List[str]`, *optional*): + An array to track the current key of the recursion. This is used to check whether the current key (part of + it) is not in the list of modules to not convert. + """ + + if modules_to_not_convert is None: + modules_to_not_convert = [] + + model, has_been_replaced = _replace_with_bnb_layers( + model, bnb_quantization_config, modules_to_not_convert, current_key_name + ) + if not has_been_replaced: + logger.warning( + "You are loading your model in 8bit or 4bit but no linear modules were found in your model." + " this can happen for some architectures such as gpt2 that uses Conv1D instead of Linear layers." + " Please double check your model architecture, or submit an issue on github if you think this is" + " a bug." + ) + return model + + +def _replace_with_bnb_layers( + model, + bnb_quantization_config, + modules_to_not_convert=None, + current_key_name=None, +): + """ + Private method that wraps the recursion for module replacement. + + Returns the converted model and a boolean that indicates if the conversion has been successfull or not. + """ + # bitsandbytes will initialize CUDA on import, so it needs to be imported lazily + import bitsandbytes as bnb + + has_been_replaced = False + for name, module in model.named_children(): + if current_key_name is None: + current_key_name = [] + current_key_name.append(name) + if isinstance(module, nn.Linear) and name not in modules_to_not_convert: + # Check if the current key is not in the `modules_to_not_convert` + current_key_name_str = ".".join(current_key_name) + proceed = True + for key in modules_to_not_convert: + if ( + (key in current_key_name_str) and (key + "." in current_key_name_str) + ) or key == current_key_name_str: + proceed = False + break + if proceed: + # Load bnb module with empty weight and replace ``nn.Linear` module + if bnb_quantization_config.load_in_8bit: + bnb_module = bnb.nn.Linear8bitLt( + module.in_features, + module.out_features, + module.bias is not None, + has_fp16_weights=False, + threshold=bnb_quantization_config.llm_int8_threshold, + ) + elif bnb_quantization_config.load_in_4bit: + bnb_module = bnb.nn.Linear4bit( + module.in_features, + module.out_features, + module.bias is not None, + bnb_quantization_config.bnb_4bit_compute_dtype, + compress_statistics=bnb_quantization_config.bnb_4bit_use_double_quant, + quant_type=bnb_quantization_config.bnb_4bit_quant_type, + ) + else: + raise ValueError("load_in_8bit and load_in_4bit can't be both False") + bnb_module.weight.data = module.weight.data + if module.bias is not None: + bnb_module.bias.data = module.bias.data + bnb_module.requires_grad_(False) + setattr(model, name, bnb_module) + has_been_replaced = True + if len(list(module.children())) > 0: + _, _has_been_replaced = _replace_with_bnb_layers( + module, bnb_quantization_config, modules_to_not_convert, current_key_name + ) + has_been_replaced = has_been_replaced | _has_been_replaced + # Remove the last key for recursion + current_key_name.pop(-1) + return model, has_been_replaced + + +def get_keys_to_not_convert(model): + r""" + An utility function to get the key of the module to keep in full precision if any For example for CausalLM modules + we may want to keep the lm_head in full precision for numerical stability reasons. For other architectures, we want + to keep the tied weights of the model. The function will return a list of the keys of the modules to not convert in + int8. + + Parameters: + model (`torch.nn.Module`): + Input model + """ + # Create a copy of the model + with init_empty_weights(): + tied_model = deepcopy(model) # this has 0 cost since it is done inside `init_empty_weights` context manager` + + tied_params = find_tied_parameters(tied_model) + # For compatibility with Accelerate < 0.18 + if isinstance(tied_params, dict): + tied_keys = sum(list(tied_params.values()), []) + list(tied_params.keys()) + else: + tied_keys = sum(tied_params, []) + has_tied_params = len(tied_keys) > 0 + + # Check if it is a base model + is_base_model = False + if hasattr(model, "base_model_prefix"): + is_base_model = not hasattr(model, model.base_model_prefix) + + # Ignore this for base models (BertModel, GPT2Model, etc.) + if (not has_tied_params) and is_base_model: + return [] + + # otherwise they have an attached head + list_modules = list(model.named_children()) + list_last_module = [list_modules[-1][0]] + + # add last module together with tied weights + intersection = set(list_last_module) - set(tied_keys) + list_untouched = list(set(tied_keys)) + list(intersection) + + # remove ".weight" from the keys + names_to_remove = [".weight", ".bias"] + filtered_module_names = [] + for name in list_untouched: + for name_to_remove in names_to_remove: + if name_to_remove in name: + name = name.replace(name_to_remove, "") + filtered_module_names.append(name) + + return filtered_module_names + + +def has_4bit_bnb_layers(model): + """Check if we have `bnb.nn.Linear4bit` or `bnb.nn.Linear8bitLt` layers inside our model""" + # bitsandbytes will initialize CUDA on import, so it needs to be imported lazily + import bitsandbytes as bnb + + for m in model.modules(): + if isinstance(m, bnb.nn.Linear4bit): + return True + return False + + +def get_parameter_device(parameter: nn.Module): + return next(parameter.parameters()).device + + +def quantize_and_offload_8bit(model, param, param_name, new_dtype, offload_folder, offload_index, fp16_statistics): + # if it is not quantized, we quantize and offload the quantized weights and the SCB stats + if fp16_statistics is None: + set_module_tensor_to_device(model, param_name, 0, dtype=new_dtype, value=param) + tensor_name = param_name + module = model + if "." in tensor_name: + splits = tensor_name.split(".") + for split in splits[:-1]: + new_module = getattr(module, split) + if new_module is None: + raise ValueError(f"{module} has no attribute {split}.") + module = new_module + tensor_name = splits[-1] + # offload weights + module._parameters[tensor_name].requires_grad = False + offload_weight(module._parameters[tensor_name], param_name, offload_folder, index=offload_index) + if hasattr(module._parameters[tensor_name], "SCB"): + offload_weight( + module._parameters[tensor_name].SCB, + param_name.replace("weight", "SCB"), + offload_folder, + index=offload_index, + ) + else: + offload_weight(param, param_name, offload_folder, index=offload_index) + offload_weight(fp16_statistics, param_name.replace("weight", "SCB"), offload_folder, index=offload_index) + + set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype, value=torch.empty(*param.size())) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/constants.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..a5f33279a41bd148b0af2907be22eb462a3324b6 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/constants.py @@ -0,0 +1,84 @@ +# 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. + +import operator as op + + +SCALER_NAME = "scaler.pt" +MODEL_NAME = "pytorch_model" +SAFE_MODEL_NAME = "model" +RNG_STATE_NAME = "random_states" +OPTIMIZER_NAME = "optimizer" +SCHEDULER_NAME = "scheduler" +SAMPLER_NAME = "sampler" +PROFILE_PATTERN_NAME = "profile_{suffix}.json" +WEIGHTS_NAME = f"{MODEL_NAME}.bin" +WEIGHTS_PATTERN_NAME = "pytorch_model{suffix}.bin" +WEIGHTS_INDEX_NAME = f"{WEIGHTS_NAME}.index.json" +SAFE_WEIGHTS_NAME = f"{SAFE_MODEL_NAME}.safetensors" +SAFE_WEIGHTS_PATTERN_NAME = "model{suffix}.safetensors" +SAFE_WEIGHTS_INDEX_NAME = f"{SAFE_WEIGHTS_NAME}.index.json" +SAGEMAKER_PYTORCH_VERSION = "1.10.2" +SAGEMAKER_PYTHON_VERSION = "py38" +SAGEMAKER_TRANSFORMERS_VERSION = "4.17.0" +SAGEMAKER_PARALLEL_EC2_INSTANCES = ["ml.p3.16xlarge", "ml.p3dn.24xlarge", "ml.p4dn.24xlarge"] +FSDP_SHARDING_STRATEGY = ["FULL_SHARD", "SHARD_GRAD_OP", "NO_SHARD", "HYBRID_SHARD", "HYBRID_SHARD_ZERO2"] +FSDP_AUTO_WRAP_POLICY = ["TRANSFORMER_BASED_WRAP", "SIZE_BASED_WRAP", "NO_WRAP"] +FSDP_BACKWARD_PREFETCH = ["BACKWARD_PRE", "BACKWARD_POST", "NO_PREFETCH"] +FSDP_STATE_DICT_TYPE = ["FULL_STATE_DICT", "LOCAL_STATE_DICT", "SHARDED_STATE_DICT"] +FSDP_PYTORCH_VERSION = ( + "2.1.0.a0+32f93b1" # Technically should be 2.1.0, but MS-AMP uses this specific prerelease in their Docker image. +) +FSDP_MODEL_NAME = "pytorch_model_fsdp" +DEEPSPEED_MULTINODE_LAUNCHERS = ["pdsh", "standard", "openmpi", "mvapich", "mpich"] +TORCH_DYNAMO_MODES = ["default", "reduce-overhead", "max-autotune"] +ELASTIC_LOG_LINE_PREFIX_TEMPLATE_PYTORCH_VERSION = "2.2.0" + +STR_OPERATION_TO_FUNC = {">": op.gt, ">=": op.ge, "==": op.eq, "!=": op.ne, "<=": op.le, "<": op.lt} + +# These are the args for `torch.distributed.launch` for pytorch < 1.9 +TORCH_LAUNCH_PARAMS = [ + "nnodes", + "nproc_per_node", + "rdzv_backend", + "rdzv_endpoint", + "rdzv_id", + "rdzv_conf", + "standalone", + "max_restarts", + "monitor_interval", + "start_method", + "role", + "module", + "m", + "no_python", + "run_path", + "log_dir", + "r", + "redirects", + "t", + "tee", + "node_rank", + "master_addr", + "master_port", +] + +CUDA_DISTRIBUTED_TYPES = ["DEEPSPEED", "MULTI_GPU", "FSDP", "MEGATRON_LM"] +TORCH_DISTRIBUTED_OPERATION_TYPES = CUDA_DISTRIBUTED_TYPES + [ + "MULTI_NPU", + "MULTI_MLU", + "MULTI_MUSA", + "MULTI_XPU", + "MULTI_CPU", +] diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/dataclasses.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/dataclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..7fa7810878e942d2569e8f00c195f7ae8dfce933 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/dataclasses.py @@ -0,0 +1,2219 @@ +# 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. + +""" +General namespace and dataclass related classes +""" + +import argparse +import copy +import enum +import functools +import os +import warnings +from contextlib import contextmanager +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any, Callable, Dict, Iterable, List, Literal, Optional, Tuple, Union, get_args + +import torch + +from .constants import FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY +from .environment import parse_flag_from_env, str_to_bool +from .imports import ( + is_cuda_available, + is_mlu_available, + is_msamp_available, + is_npu_available, + is_transformer_engine_available, + is_xpu_available, +) +from .versions import compare_versions + + +class KwargsHandler: + """ + Internal mixin that implements a `to_kwargs()` method for a dataclass. + """ + + def to_dict(self): + return copy.deepcopy(self.__dict__) + + def to_kwargs(self): + """ + Returns a dictionary containing the attributes with values different from the default of this class. + """ + # import clear_environment here to avoid circular import problem + from .other import clear_environment + + with clear_environment(): + default_dict = self.__class__().to_dict() + this_dict = self.to_dict() + return {k: v for k, v in this_dict.items() if default_dict[k] != v} + + +class EnumWithContains(enum.EnumMeta): + "A metaclass that adds the ability to check if `self` contains an item with the `in` operator" + + def __contains__(cls, item): + try: + cls(item) + except ValueError: + return False + return True + + +class BaseEnum(enum.Enum, metaclass=EnumWithContains): + "An enum class that can get the value of an item with `str(Enum.key)`" + + def __str__(self): + return self.value + + @classmethod + def list(cls): + "Method to list all the possible items in `cls`" + return list(map(str, cls)) + + +@dataclass +class AutocastKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize how `torch.autocast` behaves. Please refer to the + documentation of this [context manager](https://pytorch.org/docs/stable/amp.html#torch.autocast) for more + information on each argument. + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import AutocastKwargs + + kwargs = AutocastKwargs(cache_enabled=True) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + enabled: bool = True + cache_enabled: bool = None + + +class DDPCommunicationHookType(BaseEnum): + """ + Represents a type of communication hook used in DDP. + + Values: + + - **NO** -- no communication hook + - **FP16** -- DDP communication hook to compress the gradients in FP16 + - **BF16** -- DDP communication hook to compress the gradients in BF16 + - **POWER_SGD** -- DDP communication hook to use PowerSGD + - **BATCHED_POWER_SGD** -- DDP communication hook to use batched PowerSGD + """ + + NO = "no" + FP16 = "fp16" + BF16 = "bf16" + POWER_SGD = "power_sgd" + BATCHED_POWER_SGD = "batched_power_sgd" + + +@dataclass +class DistributedDataParallelKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize how your model is wrapped in a + `torch.nn.parallel.DistributedDataParallel`. Please refer to the documentation of this + [wrapper](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) for more + information on each argument. + + + + `gradient_as_bucket_view` is only available in PyTorch 1.7.0 and later versions. + + `static_graph` is only available in PyTorch 1.11.0 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import DistributedDataParallelKwargs + + kwargs = DistributedDataParallelKwargs(find_unused_parameters=True) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + dim: int = 0 + broadcast_buffers: bool = True + bucket_cap_mb: int = 25 + find_unused_parameters: bool = False + check_reduction: bool = False + gradient_as_bucket_view: bool = False + static_graph: bool = False + + comm_hook: DDPCommunicationHookType = DDPCommunicationHookType.NO + comm_wrapper: Literal[ + DDPCommunicationHookType.NO, DDPCommunicationHookType.FP16, DDPCommunicationHookType.BF16 + ] = DDPCommunicationHookType.NO + comm_state_option: dict = field(default_factory=dict) + + def to_dict(self, ignore_keys=("comm_hook", "comm_wrapper", "comm_state_option")): + return {k: v for k, v in super().to_dict().items() if k not in ignore_keys} + + def register_comm_hook(self, model): + from torch.distributed.algorithms.ddp_comm_hooks import default_hooks, powerSGD_hook + + hook_map: Dict[DDPCommunicationHookType, Callable] = { + DDPCommunicationHookType.FP16: default_hooks.fp16_compress_hook, + DDPCommunicationHookType.BF16: default_hooks.bf16_compress_hook, + DDPCommunicationHookType.POWER_SGD: powerSGD_hook.powerSGD_hook, + DDPCommunicationHookType.BATCHED_POWER_SGD: powerSGD_hook.batched_powerSGD_hook, + } + + wrapper_map: Dict[DDPCommunicationHookType, Callable] = { + DDPCommunicationHookType.FP16: default_hooks.fp16_compress_wrapper, + DDPCommunicationHookType.BF16: default_hooks.bf16_compress_wrapper, + } + + hook: Optional[Callable] = hook_map.get(self.comm_hook) + wrapper: Optional[Callable] = wrapper_map.get(self.comm_wrapper) + + if hook and wrapper: + hook = wrapper(hook) + + if hook: + state = ( + powerSGD_hook.PowerSGDState(None, **self.comm_state_option) + if self.comm_hook in (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.BATCHED_POWER_SGD) + else None + ) + model.register_comm_hook( + state=state, + hook=hook, + ) + + +@dataclass +class GradScalerKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the behavior of mixed precision, specifically how the + `torch.cuda.amp.GradScaler` used is created. Please refer to the documentation of this + [scaler](https://pytorch.org/docs/stable/amp.html?highlight=gradscaler) for more information on each argument. + + + + `GradScaler` is only available in PyTorch 1.5.0 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import GradScalerKwargs + + kwargs = GradScalerKwargs(backoff_filter=0.25) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + init_scale: float = 65536.0 + growth_factor: float = 2.0 + backoff_factor: float = 0.5 + growth_interval: int = 2000 + enabled: bool = True + + +@dataclass +class InitProcessGroupKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the distributed processes. Please refer + to the documentation of this + [method](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more + information on each argument. + + Note: If `timeout` is set to `None`, the default will be based upon how `backend` is set. + + ```python + from datetime import timedelta + from accelerate import Accelerator + from accelerate.utils import InitProcessGroupKwargs + + kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=800)) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + backend: Optional[str] = "nccl" + init_method: Optional[str] = None + timeout: Optional[timedelta] = None + + def __post_init__(self): + if self.timeout is None: + seconds = 1800 if self.backend != "nccl" else 600 + self.timeout = timedelta(seconds=seconds) + + +# Literals +Backend = Literal["MSAMP", "TE"] +OptLevel = Literal["O1", "O2"] +FP8Format = Literal["E4M3", "HYBRID"] +AmaxComputeAlgorithm = Literal["max", "most_recent"] + + +@dataclass +class FP8RecipeKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision + training with `transformer-engine` or `ms-amp`. + + + + For more information on `transformer-engine` args, please refer to the API + [documentation](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html). + + For more information on the `ms-amp` args, please refer to the Optimization Level + [documentation](https://azure.github.io/MS-AMP/docs/user-tutorial/optimization-level). + + + + ```python + from accelerate import Accelerator + from accelerate.utils import FP8RecipeKwargs + + kwargs = FP8RecipeKwargs(backend="te", fp8_format="HYBRID") + accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[kwargs]) + ``` + + To use MS-AMP as an engine, pass `backend="msamp"` and the `optimization_level`: + + ```python + kwargs = FP8RecipeKwargs(backend="msamp", optimization_level="02") + ``` + + Args: + backend (`str`, *optional*): + Which FP8 engine to use. Must be one of `"msamp"` (MS-AMP) or `"te"` (TransformerEngine). If not passed, + will use whichever is available in the environment, prioritizing MS-AMP. + use_autocast_during_eval (`bool`, *optional*, default to `False`): + Whether to use FP8 autocast during eval mode. Generally better metrics are found when this is `False`. + margin (`int`, *optional*, default to 0): + The margin to use for the gradient scaling. + interval (`int`, *optional*, default to 1): + The interval to use for how often the scaling factor is recomputed. + fp8_format (`str`, *optional*, default to "HYBRID"): + The format to use for the FP8 recipe. Must be one of `HYBRID` or `E4M3`. (Generally `HYBRID` for training, + `E4M3` for evaluation) + amax_history_len (`int`, *optional*, default to 1024): + The length of the history to use for the scaling factor computation + amax_compute_algo (`str`, *optional*, default to "most_recent"): + The algorithm to use for the scaling factor computation. Must be one of `max` or `most_recent`. + override_linear_precision (`tuple` of three `bool`, *optional*, default to `(False, False, False)`): + Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. + optimization_level (`str`), one of `O1`, `O2`. (default is `O2`): + What level of 8-bit collective communication should be used with MS-AMP. In general: + * O1: Weight gradients and `all_reduce` communications are done in fp8, reducing GPU + memory usage and communication bandwidth + * O2: First-order optimizer states are in 8-bit, and second order states are in FP16. + Only available when using Adam or AdamW. This maintains accuracy and can potentially save the + highest memory. + * 03: Specifically for DeepSpeed, implements capabilities so weights and master weights of models + are stored in FP8. If `fp8` is selected and deepspeed is enabled, will be used by default. (Not + available currently). + """ + + backend: Backend = None + use_autocast_during_eval: bool = None + opt_level: OptLevel = None + margin: int = None + interval: int = None + fp8_format: FP8Format = None + amax_history_len: int = None + amax_compute_algo: AmaxComputeAlgorithm = None + override_linear_precision: Tuple[bool, bool, bool] = None + + def __post_init__(self): + env_prefix = "ACCELERATE_FP8_" + default_backend = "msamp" if is_msamp_available() else "te" + if self.backend is None: + self.backend = os.environ.get(env_prefix + "BACKEND", default_backend) + self.backend = self.backend.upper() + if self.backend not in get_args(Backend): + raise ValueError("`backend` must be 'MSAMP' or 'TE' (TransformerEngine).") + # Check TE args + if self.backend == "TE": + if not is_transformer_engine_available(): + raise ValueError( + "TransformerEngine is not available. Please either install it, or use the 'MSAMP' backend (if installed)." + ) + if self.use_autocast_during_eval is None: + self.use_autocast_during_eval = parse_flag_from_env(env_prefix + "USE_AUTOCAST_DURING_EVAL") + if self.margin is None: + self.margin = int(os.environ.get(env_prefix + "MARGIN", 0)) + if self.interval is None: + self.interval = int(os.environ.get(env_prefix + "INTERVAL", 1)) + if self.fp8_format is None: + self.fp8_format = os.environ.get(env_prefix + "FORMAT", "HYBRID") + self.fp8_format = self.fp8_format.upper() + if self.fp8_format not in get_args(FP8Format): + raise ValueError(f"`fp8_format` must be one of {' or '.join(get_args(FP8Format))}.") + if self.amax_compute_algo is None: + self.amax_compute_algo = os.environ.get(env_prefix + "AMAX_COMPUTE_ALGO", "most_recent") + self.amax_compute_algo = self.amax_compute_algo.lower() + if self.amax_compute_algo not in get_args(AmaxComputeAlgorithm): + raise ValueError(f"`amax_compute_algo` must be one of {' or '.join(get_args(AmaxComputeAlgorithm))}") + if self.amax_history_len is None: + self.amax_history_len = int(os.environ.get(env_prefix + "AMAX_HISTORY_LEN", 1024)) + if self.override_linear_precision is None: + fprop = parse_flag_from_env(env_prefix + "OVERRIDE_FPROP") + dgrad = parse_flag_from_env(env_prefix + "OVERRIDE_DGRAD") + wgrad = parse_flag_from_env(env_prefix + "OVERRIDE_WGRAD") + self.override_linear_precision = (fprop, dgrad, wgrad) + elif self.backend == "MSAMP": + if not is_msamp_available(): + raise ValueError( + "MS-AMP is not available. Please either install it, or use the 'TE' backend (if installed)." + ) + if self.opt_level is None: + self.opt_level = os.environ.get(env_prefix + "OPT_LEVEL", "O2") + if self.opt_level not in get_args(OptLevel): + raise ValueError(f"`optimization_level` must be one of {' or '.join(get_args(OptLevel))}") + + +# Literal +ProfilerActivity = Literal["cpu", "xpu", "mtia", "cuda"] + + +@dataclass +class ProfileKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the profiler. Please refer to the + documentation of this [context manager](https://pytorch.org/docs/stable/profiler.html#torch.profiler.profile) for + more information on each argument. + + + + `torch.profiler` is only available in PyTorch 1.8.1 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import ProfileKwargs + + kwargs = ProfileKwargs(activities=["cpu", "cuda"]) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + + Args: + activities (`List[str]`, *optional*, default to `None`): + The list of activity groups to use in profiling. Must be one of `"cpu"`, `"xpu"`, `"mtia"`, or `"cuda"`. + schedule_option (`Dict[str, int]`, *optional*, default to `None`): + The schedule option to use for the profiler. Available keys are `wait`, `warmup`, `active`, `repeat` and + `skip_first`. The profiler will skip the first `skip_first` steps, then wait for `wait` steps, then do the + warmup for the next `warmup` steps, then do the active recording for the next `active` steps and then + repeat the cycle starting with `wait` steps. The optional number of cycles is specified with the `repeat` + parameter, the zero value means that the cycles will continue until the profiling is finished. + on_trace_ready (`Callable`, *optional*, default to `None`): + Callable that is called at each step when schedule returns `ProfilerAction.RECORD_AND_SAVE` during the + profiling. + record_shapes (`bool`, *optional*, default to `False`): + Save information about operator’s input shapes. + profile_memory (`bool`, *optional*, default to `False`): + Track tensor memory allocation/deallocation + with_stack (`bool`, *optional*, default to `False`): + Record source information (file and line number) for the ops. + with_flops (`bool`, *optional*, default to `False`): + Use formula to estimate the FLOPS of specific operators + with_modules (`bool`, *optional*, default to `False`): + Record module hierarchy (including function names) corresponding to the callstack of the op. + output_trace_dir (`str`, *optional*, default to `None`): + Exports the collected trace in Chrome JSON format. Chrome use 'chrome://tracing' view json file. Defaults + to None, which means profiling does not store json files. + """ + + activities: Optional[List[ProfilerActivity]] = None + schedule_option: Optional[Dict[str, int]] = None + on_trace_ready: Optional[Callable] = None + record_shapes: bool = False + profile_memory: bool = False + with_stack: bool = False + with_flops: bool = False + with_modules: bool = False + output_trace_dir: Optional[str] = None + + def _get_profiler_activity(self, activity: ProfilerActivity) -> torch.profiler.ProfilerActivity: + """Get the profiler activity from the string. + + Args: + activity (str): The profiler activity name. + + Returns: + torch.profiler.ProfilerActivity: The profiler activity. + """ + + profiler_activity_map: dict[str, torch.profiler.ProfilerActivity] = { + "cpu": torch.profiler.ProfilerActivity.CPU, + "xpu": torch.profiler.ProfilerActivity.XPU, + "mita": torch.profiler.ProfilerActivity.MTIA, + "cuda": torch.profiler.ProfilerActivity.CUDA, + } + + if activity not in profiler_activity_map: + raise ValueError(f"Invalid profiler activity: {activity}. Must be one of {list(profiler_activity_map)}.") + return profiler_activity_map[activity] + + def build(self) -> torch.profiler.profile: + """ + Build a profiler object with the current configuration. + + Returns: + torch.profiler.profile: The profiler object. + """ + activities: Optional[List[ProfilerActivity]] = None + if self.activities is not None: + activities = [self._get_profiler_activity(activity) for activity in self.activities] + schedule: Optional[torch.profiler.schedule] = None + if self.schedule_option is not None: + schedule = torch.profiler.schedule(**self.schedule_option) + + return torch.profiler.profile( + activities=activities, + schedule=schedule, + on_trace_ready=self.on_trace_ready, + record_shapes=self.record_shapes, + profile_memory=self.profile_memory, + with_stack=self.with_stack, + with_flops=self.with_flops, + with_modules=self.with_modules, + ) + + +class DeprecatedFieldDescriptor: + """ + Descriptor for deprecated fields in an enum class. + + Args: + field_name (`str`): + The name of the deprecated field. + replaced_with (`str`): + The name of the field that replaces the deprecated one. + """ + + def __init__(self, field_name, replaced_with): + self.field_name = field_name + self.replaced_with = replaced_with + + def __get__(self, instance, owner): + warnings.warn( + f"The `{self.field_name}` of `{owner}` is deprecated and will be removed in v1.0.0. " + f"Please use the `{self.replaced_with}` instead.", + FutureWarning, + ) + return getattr(owner, self.replaced_with) + + +class DistributedType(str, enum.Enum): + """ + Represents a type of distributed environment. + + Values: + + - **NO** -- Not a distributed environment, just a single process. + - **MULTI_CPU** -- Distributed on multiple CPU nodes. + - **MULTI_GPU** -- Distributed on multiple GPUs. + - **MULTI_MLU** -- Distributed on multiple MLUs. + - **MULTI_MUSA** -- Distributed on multiple MUSAs. + - **MULTI_NPU** -- Distributed on multiple NPUs. + - **MULTI_XPU** -- Distributed on multiple XPUs. + - **DEEPSPEED** -- Using DeepSpeed. + - **XLA** -- Using TorchXLA. + - **TPU** -- This field will be deprecated in v0.27.0. Use XLA instead. + """ + + # Subclassing str as well as Enum allows the `DistributedType` to be JSON-serializable out of the box. + NO = "NO" + MULTI_CPU = "MULTI_CPU" + MULTI_GPU = "MULTI_GPU" + MULTI_NPU = "MULTI_NPU" + MULTI_MLU = "MULTI_MLU" + MULTI_MUSA = "MULTI_MUSA" + MULTI_XPU = "MULTI_XPU" + DEEPSPEED = "DEEPSPEED" + FSDP = "FSDP" + XLA = "XLA" + MEGATRON_LM = "MEGATRON_LM" + TPU = DeprecatedFieldDescriptor("TPU", "XLA") + + +class SageMakerDistributedType(str, enum.Enum): + """ + Represents a type of distributed environment. + + Values: + + - **NO** -- Not a distributed environment, just a single process. + - **DATA_PARALLEL** -- using sagemaker distributed data parallelism. + - **MODEL_PARALLEL** -- using sagemaker distributed model parallelism. + """ + + # Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box. + NO = "NO" + DATA_PARALLEL = "DATA_PARALLEL" + MODEL_PARALLEL = "MODEL_PARALLEL" + + +class FP8BackendType(str, enum.Enum): + """ + Represents the backend used for FP8. + + Values: + + - **TE** -- using TransformerEngine. + - **MSAMP** -- using msamp. + """ + + # Subclassing str as well as Enum allows the `FP8BackendType` to be JSON-serializable out of the box. + TE = "TE" + MSAMP = "MSAMP" + + +class ComputeEnvironment(str, enum.Enum): + """ + Represents a type of the compute environment. + + Values: + + - **LOCAL_MACHINE** -- private/custom cluster hardware. + - **AMAZON_SAGEMAKER** -- Amazon SageMaker as compute environment. + """ + + # Subclassing str as well as Enum allows the `ComputeEnvironment` to be JSON-serializable out of the box. + LOCAL_MACHINE = "LOCAL_MACHINE" + AMAZON_SAGEMAKER = "AMAZON_SAGEMAKER" + + +class DynamoBackend(str, BaseEnum): + """ + Represents a dynamo backend (see https://pytorch.org/docs/stable/torch.compiler.html). + + Values: + + - **NO** -- Do not use torch dynamo. + - **EAGER** -- Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo + issues. + - **AOT_EAGER** -- Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd's + extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups. + - **INDUCTOR** -- Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton + kernels. [Read + more](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747) + - **AOT_TS_NVFUSER** -- nvFuser with AotAutograd/TorchScript. [Read + more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593) + - **NVPRIMS_NVFUSER** -- nvFuser with PrimTorch. [Read + more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593) + - **CUDAGRAPHS** -- cudagraphs with AotAutograd. [Read more](https://github.com/pytorch/torchdynamo/pull/757) + - **OFI** -- Uses Torchscript optimize_for_inference. Inference only. [Read + more](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html) + - **FX2TRT** -- Uses Nvidia TensorRT for inference optimizations. Inference only. [Read + more](https://github.com/pytorch/TensorRT/blob/master/docsrc/tutorials/getting_started_with_fx_path.rst) + - **ONNXRT** -- Uses ONNXRT for inference on CPU/GPU. Inference only. [Read more](https://onnxruntime.ai/) + - **TENSORRT** -- Uses ONNXRT to run TensorRT for inference optimizations. [Read + more](https://github.com/onnx/onnx-tensorrt) + - **AOT_TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for training. [Read + more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md) + - **TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for inference. [Read + more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md) + - **IPEX** -- Uses IPEX for inference on CPU. Inference only. [Read + more](https://github.com/intel/intel-extension-for-pytorch). + - **TVM** -- Uses Apach TVM for inference optimizations. [Read more](https://tvm.apache.org/) + + """ + + # Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box. + NO = "NO" + EAGER = "EAGER" + AOT_EAGER = "AOT_EAGER" + INDUCTOR = "INDUCTOR" + AOT_TS_NVFUSER = "AOT_TS_NVFUSER" + NVPRIMS_NVFUSER = "NVPRIMS_NVFUSER" + CUDAGRAPHS = "CUDAGRAPHS" + OFI = "OFI" + FX2TRT = "FX2TRT" + ONNXRT = "ONNXRT" + TENSORRT = "TENSORRT" + AOT_TORCHXLA_TRACE_ONCE = "AOT_TORCHXLA_TRACE_ONCE" + TORCHXLA_TRACE_ONCE = "TORCHXLA_TRACE_ONCE" + IPEX = "IPEX" + TVM = "TVM" + + +class LoggerType(BaseEnum): + """Represents a type of supported experiment tracker + + Values: + + - **ALL** -- all available trackers in the environment that are supported + - **TENSORBOARD** -- TensorBoard as an experiment tracker + - **WANDB** -- wandb as an experiment tracker + - **COMETML** -- comet_ml as an experiment tracker + - **DVCLIVE** -- dvclive as an experiment tracker + """ + + ALL = "all" + AIM = "aim" + TENSORBOARD = "tensorboard" + WANDB = "wandb" + COMETML = "comet_ml" + MLFLOW = "mlflow" + CLEARML = "clearml" + DVCLIVE = "dvclive" + + +class PrecisionType(str, BaseEnum): + """Represents a type of precision used on floating point values + + Values: + + - **NO** -- using full precision (FP32) + - **FP16** -- using half precision + - **BF16** -- using brain floating point precision + """ + + NO = "no" + FP8 = "fp8" + FP16 = "fp16" + BF16 = "bf16" + + +class RNGType(BaseEnum): + TORCH = "torch" + CUDA = "cuda" + MLU = "mlu" + MUSA = "musa" + NPU = "npu" + XLA = "xla" + XPU = "xpu" + GENERATOR = "generator" + + +class CustomDtype(enum.Enum): + r""" + An enum that contains multiple custom dtypes that can be used for `infer_auto_device_map`. + """ + + FP8 = "fp8" + INT4 = "int4" + INT2 = "int2" + + +# data classes + + +@dataclass +class TensorInformation: + shape: torch.Size + dtype: torch.dtype + + +@dataclass +class DataLoaderConfiguration: + """ + Configuration for dataloader-related items when calling `accelerator.prepare`. + """ + + split_batches: bool = field( + default=False, + metadata={ + "help": "Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If" + " `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a" + " round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set" + " in your script multiplied by the number of processes." + }, + ) + dispatch_batches: bool = field( + default=None, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process" + " and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose" + " underlying dataset is an `IterableDataset`, `False` otherwise." + }, + ) + even_batches: bool = field( + default=True, + metadata={ + "help": "If set to `True`, in cases where the total batch size across all processes does not exactly divide the" + " dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among" + " all workers." + }, + ) + use_seedable_sampler: bool = field( + default=False, + metadata={ + "help": "Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`])." + "Ensures training results are fully reproducable using a different sampling technique. " + "While seed-to-seed results may differ, on average the differences are neglible when using" + "multiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results." + }, + ) + non_blocking: bool = field( + default=False, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device" + " transfers, allowing for better overlap between dataloader communication and computation. Recommended that the" + " prepared dataloader has `pin_memory` set to `True` to work properly." + }, + ) + use_stateful_dataloader: bool = field( + default=False, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator will be backed by " + "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed." + }, + ) + + +@dataclass +class ProjectConfiguration: + """ + Configuration for the Accelerator object based on inner-project needs. + """ + + project_dir: str = field(default=None, metadata={"help": "A path to a directory for storing data."}) + logging_dir: str = field( + default=None, + metadata={ + "help": "A path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`." + }, + ) + automatic_checkpoint_naming: bool = field( + default=False, + metadata={"help": "Whether saved states should be automatically iteratively named."}, + ) + + total_limit: int = field( + default=None, + metadata={"help": "The maximum number of total saved states to keep."}, + ) + + iteration: int = field( + default=0, + metadata={"help": "The current save iteration."}, + ) + + save_on_each_node: bool = field( + default=False, + metadata={ + "help": ( + "When doing multi-node distributed training, whether to save models and checkpoints on each node, or" + " only on the main one" + ) + }, + ) + + def set_directories(self, project_dir: str = None): + "Sets `self.project_dir` and `self.logging_dir` to the appropriate values." + self.project_dir = project_dir + if self.logging_dir is None: + self.logging_dir = project_dir + + def __post_init__(self): + self.set_directories(self.project_dir) + + +@dataclass +class GradientAccumulationPlugin(KwargsHandler): + """ + A plugin to configure gradient accumulation behavior. You can only pass one of `gradient_accumulation_plugin` or + `gradient_accumulation_steps` to [`Accelerator`]. Passing both raises an error. + + Parameters: + num_steps (`int`): + The number of steps to accumulate gradients for. + adjust_scheduler (`bool`, *optional*, defaults to `True`): + Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be + `True` if the used scheduler was not adjusted for gradient accumulation. + sync_with_dataloader (`bool`, *optional*, defaults to `True`): + Whether to synchronize setting the gradients when at the end of the dataloader. + sync_each_batch (`bool`, *optional*): + Whether to synchronize setting the gradients at each data batch. Seting to `True` may reduce memory + requirements when using gradient accumulation with distributed training, at expense of speed. + + Example: + + ```python + from accelerate.utils import GradientAccumulationPlugin + + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2) + accelerator = Accelerator(gradient_accumulation_plugin=gradient_accumulation_plugin) + ``` + """ + + num_steps: int = field(default=None, metadata={"help": "The number of steps to accumulate gradients for."}) + adjust_scheduler: bool = field( + default=True, + metadata={ + "help": "Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be `True` if the used scheduler was not adjusted for gradient accumulation." + }, + ) + sync_with_dataloader: bool = field( + default=True, + metadata={ + "help": "Whether to synchronize setting the gradients when at the end of the dataloader. Should only be set to `False` if you know what you're doing." + }, + ) + sync_each_batch: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize setting the gradients at each data batch. Setting to `True` may reduce memory requirements when using gradient accumulation with distributed training, at expense of speed." + }, + ) + + +@dataclass +class TorchDynamoPlugin(KwargsHandler): + """ + This plugin is used to compile a model with PyTorch 2.0 + """ + + backend: DynamoBackend = field( + default=None, + metadata={"help": f"Possible options are {[b.value.lower() for b in DynamoBackend]}"}, + ) + mode: str = field( + default=None, metadata={"help": "Possible options are 'default', 'reduce-overhead' or 'max-autotune'"} + ) + fullgraph: bool = field(default=None, metadata={"help": "Whether it is ok to break model into several subgraphs"}) + dynamic: bool = field(default=None, metadata={"help": "Whether to use dynamic shape for tracing"}) + options: Any = field(default=None, metadata={"help": "A dictionary of options to pass to the backend."}) + disable: bool = field(default=False, metadata={"help": "Turn torch.compile() into a no-op for testing"}) + + def __post_init__(self): + prefix = "ACCELERATE_DYNAMO_" + if self.backend is None: + self.backend = os.environ.get(prefix + "BACKEND", "no") + self.backend = DynamoBackend(self.backend.upper()) + if self.mode is None: + self.mode = os.environ.get(prefix + "MODE", "default") + if self.fullgraph is None: + self.fullgraph = str_to_bool(os.environ.get(prefix + "USE_FULLGRAPH", "False")) == 1 + if self.dynamic is None: + self.dynamic = str_to_bool(os.environ.get(prefix + "USE_DYNAMIC", "False")) == 1 + + def to_dict(self): + dynamo_config = copy.deepcopy(self.__dict__) + dynamo_config["backend"] = dynamo_config["backend"].value.lower() + return dynamo_config + + +@dataclass +class DeepSpeedPlugin: + """ + This plugin is used to integrate DeepSpeed. + """ + + hf_ds_config: Any = field( + default=None, + metadata={ + "help": "path to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`." + }, + ) + gradient_accumulation_steps: int = field( + default=None, + metadata={ + "help": "Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value from the `Accelerator` directly." + }, + ) + gradient_clipping: float = field(default=None, metadata={"help": "Enable gradient clipping with value"}) + zero_stage: int = field( + default=None, + metadata={"help": "Possible options are 0,1,2,3; Default will be taken from environment variable"}, + ) + is_train_batch_min: bool = field( + default=True, + metadata={"help": "If both train & eval dataloaders are specified, this will decide the train_batch_size"}, + ) + offload_optimizer_device: str = field( + default=None, + metadata={"help": "Possible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3."}, + ) + offload_param_device: str = field( + default=None, + metadata={"help": "Possible options are none|cpu|nvme. Only applicable with ZeRO Stage 3."}, + ) + offload_optimizer_nvme_path: str = field( + default=None, + metadata={"help": "Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3."}, + ) + offload_param_nvme_path: str = field( + default=None, + metadata={"help": "Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3."}, + ) + zero3_init_flag: bool = field( + default=None, + metadata={ + "help": "Flag to indicate whether to enable `deepspeed.zero.Init` for constructing massive models." + "Only applicable with ZeRO Stage-3." + }, + ) + zero3_save_16bit_model: bool = field( + default=None, + metadata={"help": "Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3."}, + ) + transformer_moe_cls_names: str = field( + default=None, + metadata={ + "help": "comma-separated list of transformers MoE layer class names (case-sensitive), e.g : " + " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..." + }, + ) + + def __post_init__(self): + from .deepspeed import HfDeepSpeedConfig + + if self.gradient_accumulation_steps is None: + gas = os.environ.get("ACCELERATE_GRADIENT_ACCUMULATION_STEPS", "auto") + self.gradient_accumulation_steps = int(gas) if gas.isdigit() else gas + + if self.gradient_clipping is None: + gradient_clipping = os.environ.get("ACCELERATE_GRADIENT_CLIPPING", "auto") + self.gradient_clipping = gradient_clipping if gradient_clipping == "auto" else float(gradient_clipping) + + if self.zero_stage is None: + self.zero_stage = int(os.environ.get("ACCELERATE_DEEPSPEED_ZERO_STAGE", 2)) + + if self.offload_optimizer_device is None: + self.offload_optimizer_device = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE", "none") + + if self.offload_param_device is None: + self.offload_param_device = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE", "none") + + if self.offload_optimizer_nvme_path is None: + self.offload_optimizer_nvme_path = os.environ.get( + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH", "none" + ) + + if self.offload_param_nvme_path is None: + self.offload_param_nvme_path = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH", "none") + + if self.zero3_save_16bit_model is None: + self.zero3_save_16bit_model = ( + os.environ.get("ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL", "false") == "true" + ) + + if self.hf_ds_config is None: + self.hf_ds_config = os.environ.get("ACCELERATE_DEEPSPEED_CONFIG_FILE", "none") + if ( + isinstance(self.hf_ds_config, dict) + or (isinstance(self.hf_ds_config, str) and self.hf_ds_config != "none") + or isinstance(self.hf_ds_config, HfDeepSpeedConfig) + ): + if not isinstance(self.hf_ds_config, HfDeepSpeedConfig): + self.hf_ds_config = HfDeepSpeedConfig(self.hf_ds_config) + if "gradient_accumulation_steps" not in self.hf_ds_config.config: + self.hf_ds_config.config["gradient_accumulation_steps"] = 1 + if "zero_optimization" not in self.hf_ds_config.config: + raise ValueError("Please specify the ZeRO optimization config in the DeepSpeed config.") + + self._deepspeed_config_checks() + plugin_to_config_mapping = { + "gradient_accumulation_steps": "gradient_accumulation_steps", + "gradient_clipping": "gradient_clipping", + "zero_stage": "zero_optimization.stage", + "offload_optimizer_device": "zero_optimization.offload_optimizer.device", + "offload_param_device": "zero_optimization.offload_param.device", + "offload_param_nvme_path": "zero_optimization.offload_param.nvme_path", + "offload_optimizer_nvme_path": "zero_optimization.offload_optimizer.nvme_path", + "zero3_save_16bit_model": "zero_optimization.stage3_gather_16bit_weights_on_model_save", + } + kwargs = {v: getattr(self, k) for k, v in plugin_to_config_mapping.items() if getattr(self, k) is not None} + for key in kwargs.keys(): + self.fill_match(key, **kwargs, must_match=False) + self.hf_ds_config.set_stage_and_offload() + + # filling the missing values in the class attributes from the DeepSpeed config + # when using the DeepSpeed config file. + for key, value in plugin_to_config_mapping.items(): + config_value = self.hf_ds_config.get_value(value) + if config_value is not None and config_value != "auto": + setattr(self, key, config_value) + else: + config = { + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "gradient_accumulation_steps": self.gradient_accumulation_steps, + "zero_optimization": { + "stage": self.zero_stage, + "offload_optimizer": { + "device": self.offload_optimizer_device, + "nvme_path": self.offload_optimizer_nvme_path + if self.offload_optimizer_device == "nvme" + else None, + }, + "offload_param": { + "device": self.offload_param_device, + "nvme_path": self.offload_param_nvme_path if self.offload_param_device == "nvme" else None, + }, + "stage3_gather_16bit_weights_on_model_save": self.zero3_save_16bit_model, + }, + } + if self.gradient_clipping: + config["gradient_clipping"] = self.gradient_clipping + self.hf_ds_config = HfDeepSpeedConfig(config) + + self.deepspeed_config = self.hf_ds_config.config + self.deepspeed_config["steps_per_print"] = float("inf") # this will stop deepspeed from logging @ stdout + if self.zero3_init_flag is None: + self.zero3_init_flag = ( + str_to_bool(os.environ.get("ACCELERATE_DEEPSPEED_ZERO3_INIT", str(self.hf_ds_config.is_zero3()))) == 1 + ) + if self.zero3_init_flag and not self.hf_ds_config.is_zero3(): + warnings.warn("DeepSpeed Zero3 Init flag is only applicable for ZeRO Stage 3. Setting it to False.") + self.zero3_init_flag = False + + def fill_match(self, ds_key_long, mismatches=None, must_match=True, **kwargs): + mismatches = [] if mismatches is None else mismatches + config, ds_key = self.hf_ds_config.find_config_node(ds_key_long) + if config is None: + return + + if config.get(ds_key) == "auto": + if ds_key_long in kwargs: + config[ds_key] = kwargs[ds_key_long] + return + else: + raise ValueError( + f"`{ds_key_long}` not found in kwargs. " + f"Please specify `{ds_key_long}` without `auto` (set to correct value) in the DeepSpeed config file or " + "pass it in kwargs." + ) + + if not must_match: + return + + ds_val = config.get(ds_key) + if ds_val is not None and ds_key_long in kwargs: + if ds_val != kwargs[ds_key_long]: + mismatches.append(f"- ds {ds_key_long}={ds_val} vs arg {ds_key_long}={kwargs[ds_key_long]}") + + def is_auto(self, ds_key_long): + val = self.hf_ds_config.get_value(ds_key_long) + if val is None: + return False + else: + return val == "auto" + + def get_value(self, ds_key_long, default=None): + return self.hf_ds_config.get_value(ds_key_long, default) + + def deepspeed_config_process(self, prefix="", mismatches=None, config=None, must_match=True, **kwargs): + """Process the DeepSpeed config with the values from the kwargs.""" + mismatches = [] if mismatches is None else mismatches + if config is None: + config = self.deepspeed_config + for key, value in config.items(): + if isinstance(value, dict): + self.deepspeed_config_process( + prefix=prefix + key + ".", mismatches=mismatches, config=value, must_match=must_match, **kwargs + ) + else: + self.fill_match(prefix + key, mismatches, must_match=must_match, **kwargs) + if len(mismatches) > 0 and prefix == "": + mismatches_msg = "\n".join(mismatches) + raise ValueError( + "Please correct the following DeepSpeed config values that mismatch kwargs " + f" values:\n{mismatches_msg}\nThe easiest method is to set these DeepSpeed config values to 'auto'." + ) + + def set_mixed_precision(self, mixed_precision): + ds_config = self.deepspeed_config + kwargs = { + "fp16.enabled": mixed_precision == "fp16", + # When training in fp8, we still rely on bf16 autocast for the core mixed precision + "bf16.enabled": mixed_precision in ("bf16", "fp8"), + } + if mixed_precision == "fp16": + if "fp16" not in ds_config: + ds_config["fp16"] = {"enabled": True, "auto_cast": True} + elif mixed_precision in ("bf16", "fp8"): + if "bf16" not in ds_config: + ds_config["bf16"] = {"enabled": True} + + if mixed_precision != "no": + diff_dtype = "bf16" if mixed_precision == "fp16" else "fp16" + if str(ds_config.get(diff_dtype, {}).get("enabled", "False")).lower() == "true": + raise ValueError( + f"`--mixed_precision` arg cannot be set to `{mixed_precision}` when `{diff_dtype}` is set in the DeepSpeed config file." + ) + for dtype in ["fp16", "bf16"]: + if dtype not in ds_config: + ds_config[dtype] = {"enabled": False} + self.fill_match("fp16.enabled", must_match=False, **kwargs) + self.fill_match("bf16.enabled", must_match=False, **kwargs) + + def set_deepspeed_weakref(self): + from .imports import is_transformers_available + + if self.zero3_init_flag: + if not is_transformers_available(): + raise Exception( + "When `zero3_init_flag` is set, it requires Transformers to be installed. " + "Please run `pip install transformers`." + ) + ds_config = copy.deepcopy(self.deepspeed_config) + if "gradient_accumulation_steps" not in ds_config or ds_config["gradient_accumulation_steps"] == "auto": + ds_config["gradient_accumulation_steps"] = 1 + if ( + "train_micro_batch_size_per_gpu" not in ds_config + or ds_config["train_micro_batch_size_per_gpu"] == "auto" + ): + ds_config["train_micro_batch_size_per_gpu"] = 1 + if ds_config.get("train_batch_size", None) == "auto": + del ds_config["train_batch_size"] + + if compare_versions("transformers", "<", "4.33"): + from transformers.deepspeed import HfDeepSpeedConfig + else: + from transformers.integrations import HfDeepSpeedConfig + + self.dschf = HfDeepSpeedConfig(ds_config) # keep this object alive # noqa + + def is_zero3_init_enabled(self): + return self.zero3_init_flag + + @contextmanager + def zero3_init_context_manager(self, enable=False): + old = self.zero3_init_flag + if old == enable: + yield + else: + self.zero3_init_flag = enable + self.dschf = None + self.set_deepspeed_weakref() + yield + self.zero3_init_flag = old + self.dschf = None + self.set_deepspeed_weakref() + + def _deepspeed_config_checks(self): + env_variable_names_to_ignore = [ + "ACCELERATE_GRADIENT_ACCUMULATION_STEPS", + "ACCELERATE_GRADIENT_CLIPPING", + "ACCELERATE_DEEPSPEED_ZERO_STAGE", + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE", + "ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE", + "ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH", + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH", + "ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL", + "ACCELERATE_MIXED_PRECISION", + ] + env_variable_names_to_ignore = [ + name.replace("ACCELERATE_", "").replace("DEEPSPEED_", "").lower() for name in env_variable_names_to_ignore + ] + + deepspeed_fields_from_accelerate_config = os.environ.get("ACCELERATE_CONFIG_DS_FIELDS", "").split(",") + + if any(name in env_variable_names_to_ignore for name in deepspeed_fields_from_accelerate_config): + raise ValueError( + f"When using `deepspeed_config_file`, the following accelerate config variables will be ignored: {env_variable_names_to_ignore}.\n" + "Please specify them appropriately in the DeepSpeed config file.\n" + "If you are using an accelerate config file, remove others config variables mentioned in the above specified list.\n" + "The easiest method is to create a new config following the questionnaire via `accelerate config`.\n" + "It will only ask for the necessary config variables when using `deepspeed_config_file`." + ) + + def set_moe_leaf_modules(self, model): + if self.transformer_moe_cls_names is None: + self.transformer_moe_cls_names = os.environ.get("ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMES", None) + if self.transformer_moe_cls_names is not None: + if compare_versions("deepspeed", "<", "0.14.0"): + raise ImportError("DeepSpeed version must be >= 0.14.0 to use MOE support. Please update DeepSpeed.") + from deepspeed.utils import set_z3_leaf_modules + + class_names = self.transformer_moe_cls_names.split(",") + transformer_moe_cls = [] + for layer_class in class_names: + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise Exception( + f"Could not find a transformer layer class called '{layer_class}' to wrap in the model." + ) + else: + transformer_moe_cls.append(transformer_cls) + set_z3_leaf_modules(model, transformer_moe_cls) # z3_leaf + + +@dataclass +class FullyShardedDataParallelPlugin: + """ + This plugin is used to enable fully sharded data parallelism. + """ + + sharding_strategy: Union[str, "torch.distributed.fsdp.ShardingStrategy"] = field( + default=None, + metadata={ + "help": "Sharding strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'" + }, + ) + backward_prefetch: Union[str, "torch.distributed.fsdp.BackwardPrefetch"] = field( + default=None, + metadata={ + "help": "Backward prefetch strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`. Defaults to 'NO_PREFETCH'" + }, + ) + mixed_precision_policy: Optional[Union[dict, "torch.distributed.fsdp.MixedPrecision"]] = field( + default=None, + metadata={ + "help": "A config to enable mixed precision training with FullyShardedDataParallel. " + "If passing in a `dict`, it should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`." + }, + ) + auto_wrap_policy: Optional[ + Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]] + ] = field( + default=None, + metadata={ + "help": "A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. " + "Defaults to `NO_WRAP`. See `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like" + }, + ) + cpu_offload: Union[bool, "torch.distributed.fsdp.CPUOffload"] = field( + default=None, + metadata={ + "help": "Whether to offload parameters to CPU. Should be either a `bool` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload`. Defaults to `False`" + }, + ) + ignored_modules: Optional[Iterable[torch.nn.Module]] = field( + default=None, + metadata={"help": "A list of modules to ignore when wrapping with FSDP."}, + ) + + state_dict_type: Union[str, "torch.distributed.fsdp.StateDictType"] = field( + default=None, + metadata={ + "help": "State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or `sharded_state_dict`. Defaults to `FULL_STATE_DICT`" + }, + ) + state_dict_config: Optional[ + Union[ + "torch.distributed.fsdp.FullStateDictConfig", + "torch.distributed.fsdp.ShardedStateDictConfig", + ] + ] = field( + default=None, + metadata={"help": "State dict config to use. Is determined based on the `state_dict_type` if not passed in."}, + ) + optim_state_dict_config: Optional[ + Union["torch.distributed.fsdp.FullOptimStateDictConfig", "torch.distributed.fsdp.ShardedOptimStateDictConfig"] + ] = field( + default=None, + metadata={ + "help": "Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in." + }, + ) + limit_all_gathers: bool = field( + default=True, + metadata={ + "help": "Whether to have FSDP explicitly synchronizes the CPU thread to prevent " + "too many in-flight all-gathers. This bool only affects the sharded strategies that schedule all-gathers. " + "Enabling this can help lower the number of CUDA malloc retries." + }, + ) + use_orig_params: bool = field( + default=None, + metadata={"help": "Whether to use the original parameters for the optimizer. Defaults to `False`"}, + ) + param_init_fn: Optional[Callable[[torch.nn.Module], None]] = field( + default=None, + metadata={ + "help": "A Callable[torch.nn.Module] -> None that specifies how modules " + "that are currently on the meta device should be initialized onto an actual device. " + "Only applicable when `sync_module_states` is `True`. By default is a `lambda` which calls `to_empty` on the module." + }, + ) + sync_module_states: bool = field( + default=None, + metadata={ + "help": "Whether each individually wrapped FSDP unit should broadcast module parameters from rank 0 " + "to ensure they are the same across all ranks after initialization. Defaults to `False` unless " + "`cpu_ram_efficient_loading` is `True`, then will be forcibly enabled." + }, + ) + forward_prefetch: bool = field( + default=None, + metadata={ + "help": "Whether to have FSDP explicitly prefetches the next upcoming " + "all-gather while executing in the forward pass. only use with Static graphs. Defaults to `False`" + }, + ) + activation_checkpointing: bool = field( + default=None, + metadata={ + "help": "A technique to reduce memory usage by clearing activations of " + "certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time " + "for reduced memory usage. Defaults to `False`" + }, + ) + cpu_ram_efficient_loading: bool = field( + default=None, + metadata={ + "help": "If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. " + "Only applicable for 🤗 Transformers. When using this, `sync_module_states` needs to be `True`. Defaults to `False`." + }, + ) + transformer_cls_names_to_wrap: Optional[List[str]] = field( + default=None, + metadata={ + "help": "A list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is `transformer_based_wrap`." + }, + ) + min_num_params: Optional[int] = field( + default=None, + metadata={ + "help": "The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy` is `size_based_wrap`." + }, + ) + + def __post_init__(self): + from torch.distributed.fsdp import ( + BackwardPrefetch, + CPUOffload, + ShardingStrategy, + ) + + env_prefix = "FSDP_" + # Strategy: By default we should always assume that values are passed in, else we check the environment variables + if self.sharding_strategy is None: + self.sharding_strategy = os.environ.get(env_prefix + "SHARDING_STRATEGY", "FULL_SHARD") + if isinstance(self.sharding_strategy, str): + # We need to remap based on custom enum values for user readability + if self.sharding_strategy.upper() in FSDP_SHARDING_STRATEGY: + self.sharding_strategy = FSDP_SHARDING_STRATEGY.index(self.sharding_strategy.upper()) + 1 + if isinstance(self.sharding_strategy, int) or self.sharding_strategy.isdigit(): + self.sharding_strategy = ShardingStrategy(int(self.sharding_strategy)) + else: + self.sharding_strategy = ShardingStrategy[self.sharding_strategy.upper()] + + if self.cpu_offload is None: + self.cpu_offload = str_to_bool(os.environ.get(env_prefix + "OFFLOAD_PARAMS", "False")) == 1 + if isinstance(self.cpu_offload, bool): + self.cpu_offload = CPUOffload(offload_params=self.cpu_offload) + + if self.backward_prefetch is None: + self.backward_prefetch = os.environ.get(env_prefix + "BACKWARD_PREFETCH", None) + if isinstance(self.backward_prefetch, str) and self.backward_prefetch.upper() == "NO_PREFETCH": + self.backward_prefetch = None + if self.backward_prefetch is not None and not isinstance(self.backward_prefetch, BackwardPrefetch): + if isinstance(self.backward_prefetch, str) and self.backward_prefetch.upper() in FSDP_BACKWARD_PREFETCH: + self.backward_prefetch = FSDP_BACKWARD_PREFETCH.index(self.backward_prefetch.upper()) + 1 + if isinstance(self.backward_prefetch, int) or self.backward_prefetch.isdigit(): + self.backward_prefetch = BackwardPrefetch(int(self.backward_prefetch)) + else: + self.backward_prefetch = BackwardPrefetch[self.backward_prefetch.upper()] + + self.set_state_dict_type() + + if self.auto_wrap_policy is None: + self.auto_wrap_policy = os.environ.get(env_prefix + "AUTO_WRAP_POLICY", "NO_WRAP") + if isinstance(self.auto_wrap_policy, str): + if self.auto_wrap_policy.upper() not in FSDP_AUTO_WRAP_POLICY: + raise ValueError( + f"Invalid auto wrap policy: {self.auto_wrap_policy}. Must be one of {list(FSDP_AUTO_WRAP_POLICY.keys())}" + ) + from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy, transformer_auto_wrap_policy + + if self.auto_wrap_policy.upper() == "TRANSFORMER_BASED_WRAP": + self.auto_wrap_policy = transformer_auto_wrap_policy + if self.transformer_cls_names_to_wrap is None: + self.transformer_cls_names_to_wrap = os.environ.get(env_prefix + "TRANSFORMER_CLS_TO_WRAP", None) + if isinstance(self.transformer_cls_names_to_wrap, str): + self.transformer_cls_names_to_wrap = self.transformer_cls_names_to_wrap.split(",") + elif self.auto_wrap_policy.upper() == "SIZE_BASED_WRAP": + self.auto_wrap_policy = size_based_auto_wrap_policy + if self.min_num_params is None: + self.min_num_params = int(os.environ.get(env_prefix + "MIN_NUM_PARAMS", 0)) + elif not isinstance(self.min_num_params, int): + raise ValueError( + f"`min_num_params` must be an integer. Got {self.min_num_params} of type {type(self.min_num_params)}" + ) + elif self.auto_wrap_policy.upper() == "NO_WRAP": + self.auto_wrap_policy = None + + if self.use_orig_params is None: + self.use_orig_params = str_to_bool(os.environ.get(env_prefix + "USE_ORIG_PARAMS", "False")) == 1 + + if self.sync_module_states is None: + self.sync_module_states = str_to_bool(os.environ.get(env_prefix + "SYNC_MODULE_STATES", "False")) == 1 + + if self.forward_prefetch is None: + self.forward_prefetch = str_to_bool(os.environ.get(env_prefix + "FORWARD_PREFETCH", "False")) == 1 + + if self.activation_checkpointing is None: + self.activation_checkpointing = ( + str_to_bool(os.environ.get(env_prefix + "ACTIVATION_CHECKPOINTING", "False")) == 1 + ) + + if self.cpu_ram_efficient_loading is None: + self.cpu_ram_efficient_loading = ( + str_to_bool(os.environ.get(env_prefix + "CPU_RAM_EFFICIENT_LOADING", "False")) == 1 + ) + + if self.cpu_ram_efficient_loading and not self.sync_module_states: + warnings.warn( + "sync_module_states cannot be False since efficient cpu ram loading enabled. " + "Setting sync_module_states to True." + ) + self.sync_module_states = True + + if isinstance(self.mixed_precision_policy, dict): + self.set_mixed_precision(self.mixed_precision_policy) + + if self.sync_module_states: + if is_npu_available(): + device = torch.npu.current_device() + elif is_mlu_available(): + device = torch.mlu.current_device() + elif is_cuda_available(): + device = torch.cuda.current_device() + elif is_xpu_available(): + device = torch.xpu.current_device() + else: + raise RuntimeError( + "There are currently no available devices found, must be one of 'XPU', 'CUDA', or 'NPU'." + ) + # Create a function that will be used to initialize the parameters of the model + # when using `sync_module_states` + self.param_init_fn = lambda x: x.to_empty(device=device, recurse=False) + + def set_state_dict_type(self): + """ + Set the state dict config based on the `StateDictType. + """ + from torch.distributed.fsdp.fully_sharded_data_parallel import ( + FullOptimStateDictConfig, + FullStateDictConfig, + ShardedOptimStateDictConfig, + ShardedStateDictConfig, + StateDictType, + ) + + if self.state_dict_type is None: + self.state_dict_type = os.environ.get("FSDP_STATE_DICT_TYPE", "FULL_STATE_DICT") + if isinstance(self.state_dict_type, str): + if self.state_dict_type.isdigit(): + self.state_dict_type = StateDictType(int(self.state_dict_type)) + else: + self.state_dict_type = StateDictType[self.state_dict_type.upper()] + + if self.state_dict_type == StateDictType.FULL_STATE_DICT: + if self.state_dict_config is None: + self.state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + if self.optim_state_dict_config is None: + self.optim_state_dict_config = FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=True) + elif self.state_dict_type == StateDictType.SHARDED_STATE_DICT: + if self.state_dict_config is None: + self.state_dict_config = ShardedStateDictConfig(offload_to_cpu=True) + if self.optim_state_dict_config is None: + self.optim_state_dict_config = ShardedOptimStateDictConfig(offload_to_cpu=True) + + def set_auto_wrap_policy(self, model): + """ + Given `model`, creates an `auto_wrap_policy` baesd on the passed in policy and if we can use the + `transformer_cls_to_wrap` + """ + from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy, transformer_auto_wrap_policy + + # First base off of `_no_split_modules` + no_split_modules = getattr(model, "_no_split_modules", None) + default_transformer_cls_names_to_wrap = ( + ",".join(model._no_split_modules) if no_split_modules is not None else "" + ) + if self.auto_wrap_policy == transformer_auto_wrap_policy: + if self.transformer_cls_names_to_wrap is None: + self.transformer_cls_names_to_wrap = default_transformer_cls_names_to_wrap + transformer_cls_to_wrap = set() + for layer_class in self.transformer_cls_names_to_wrap: + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise ValueError(f"Could not find the transformer layer class {layer_class} in the model.") + transformer_cls_to_wrap.add(transformer_cls) + # Finally we set the auto_wrap_policy to a callable + self.auto_wrap_policy = functools.partial( + self.auto_wrap_policy, transformer_layer_cls=transformer_cls_to_wrap + ) + + elif self.auto_wrap_policy == size_based_auto_wrap_policy: + # If zero, we silently ignore it. + if self.min_num_params > 0: + self.auto_wrap_policy = functools.partial(self.auto_wrap_policy, min_num_params=self.min_num_params) + else: + self.auto_wrap_policy = None + + def set_mixed_precision(self, mixed_precision, buffer_autocast=False, override=False): + "Sets the mixed precision policy for FSDP" + mixed_precision_mapping = { + "fp8": torch.bfloat16, + "fp16": torch.float16, + "bf16": torch.bfloat16, + "fp32": torch.float32, + } + dtype = mixed_precision + if isinstance(mixed_precision, str): + dtype = mixed_precision_mapping.get(mixed_precision, None) + if dtype is None: + raise ValueError( + f"Invalid mixed precision: {mixed_precision}. Must be one of {list(mixed_precision_mapping.keys())}" + ) + elif isinstance(mixed_precision, torch.dtype) and mixed_precision not in mixed_precision_mapping.values(): + raise ValueError( + f"Invalid mixed precision: {mixed_precision}. Must be one of {list(mixed_precision_mapping.values())}" + ) + + buffer_type = torch.float32 if buffer_autocast else dtype + + from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision + + if override or self.mixed_precision_policy is None: + self.mixed_precision_policy = MixedPrecision( + param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=buffer_type + ) + elif isinstance(self.mixed_precision_policy, dict): + # Check for incompatible types + missing_keys = [ + k for k in ["param_dtype", "reduce_dtype", "buffer_dtype"] if k not in self.mixed_precision_policy + ] + invalid_values = [ + k for k, v in self.mixed_precision_policy.items() if v not in mixed_precision_mapping.values() + ] + if missing_keys or invalid_values: + raise ValueError( + f"Invalid mixed precision policy: {self.mixed_precision_policy}. " + f"Must be a `dict` with keys `param_dtype`, `reduce_dtype`, and `buffer_dtype`. " + f"Values must be one of {list(mixed_precision_mapping.values())}" + ) + self.mixed_precision_policy = MixedPrecision(**self.mixed_precision_policy) + + +@dataclass +class MegatronLMPlugin: + """ + Plugin for Megatron-LM to enable tensor, pipeline, sequence and data parallelism. Also to enable selective + activation recomputation and optimized fused kernels. + """ + + tp_degree: int = field(default=None, metadata={"help": "tensor parallelism degree."}) + pp_degree: int = field(default=None, metadata={"help": "pipeline parallelism degree."}) + num_micro_batches: int = field(default=None, metadata={"help": "number of micro-batches."}) + gradient_clipping: float = field( + default=None, metadata={"help": "gradient clipping value based on global L2 Norm (0 to disable)"} + ) + sequence_parallelism: bool = field( + default=None, + metadata={"help": "enable sequence parallelism"}, + ) + recompute_activations: bool = field( + default=None, + metadata={"help": "enable selective activation recomputation"}, + ) + use_distributed_optimizer: bool = field( + default=None, + metadata={"help": "enable distributed optimizer"}, + ) + pipeline_model_parallel_split_rank: int = field( + default=None, metadata={"help": "Rank where encoder and decoder should be split."} + ) + num_layers_per_virtual_pipeline_stage: int = field( + default=None, metadata={"help": "Number of layers per virtual pipeline stage."} + ) + is_train_batch_min: str = field( + default=True, + metadata={"help": "If both train & eval dataloaders are specified, this will decide the micro_batch_size"}, + ) + train_iters: int = field( + default=None, + metadata={ + "help": "Total number of iterations to train over all training runs. " + "Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`" + }, + ) + train_samples: int = field( + default=None, + metadata={ + "help": "Total number of samples to train over all training runs. " + "Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`" + }, + ) + weight_decay_incr_style: str = field( + default="constant", + metadata={"help": 'Weight decay increment function. choices=["constant", "linear", "cosine"]. '}, + ) + start_weight_decay: float = field( + default=None, + metadata={"help": "Initial weight decay coefficient for L2 regularization."}, + ) + end_weight_decay: float = field( + default=None, + metadata={"help": "End of run weight decay coefficient for L2 regularization."}, + ) + lr_decay_style: str = field( + default="linear", + metadata={"help": "Learning rate decay function. choices=['constant', 'linear', 'cosine']."}, + ) + lr_decay_iters: int = field( + default=None, + metadata={"help": "Number of iterations for learning rate decay. If None defaults to `train_iters`."}, + ) + lr_decay_samples: int = field( + default=None, + metadata={"help": "Number of samples for learning rate decay. If None defaults to `train_samples`."}, + ) + lr_warmup_iters: int = field( + default=None, + metadata={"help": "number of iterations to linearly warmup learning rate over."}, + ) + lr_warmup_samples: int = field( + default=None, + metadata={"help": "number of samples to linearly warmup learning rate over."}, + ) + lr_warmup_fraction: float = field( + default=None, + metadata={"help": "fraction of lr-warmup-(iters/samples) to linearly warmup learning rate over."}, + ) + min_lr: float = field( + default=0, + metadata={"help": "Minumum value for learning rate. The scheduler clip values below this threshold."}, + ) + consumed_samples: List[int] = field( + default=None, + metadata={ + "help": "Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call." + }, + ) + no_wd_decay_cond: Optional[Callable] = field(default=None, metadata={"help": "Condition to disable weight decay."}) + scale_lr_cond: Optional[Callable] = field(default=None, metadata={"help": "Condition to scale learning rate."}) + lr_mult: float = field(default=1.0, metadata={"help": "Learning rate multiplier."}) + megatron_dataset_flag: bool = field( + default=False, + metadata={"help": "Whether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format."}, + ) + seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process."}, + ) + encoder_seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process for the encoder."}, + ) + decoder_seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process for the decoder."}, + ) + tensorboard_dir: str = field( + default=None, + metadata={"help": "Path to save tensorboard logs."}, + ) + set_all_logging_options: bool = field( + default=False, + metadata={"help": "Whether to set all logging options."}, + ) + eval_iters: int = field( + default=100, metadata={"help": "Number of iterations to run for evaluation validation/test for."} + ) + eval_interval: int = field( + default=1000, metadata={"help": "Interval between running evaluation on validation set."} + ) + return_logits: bool = field( + default=False, + metadata={"help": "Whether to return logits from the model."}, + ) + + # custom train step args + custom_train_step_class: Optional[Any] = field( + default=None, + metadata={"help": "Custom train step class."}, + ) + custom_train_step_kwargs: Optional[Dict[str, Any]] = field( + default=None, + metadata={"help": "Custom train step kwargs."}, + ) + + # custom model args + custom_model_provider_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom model provider function."}, + ) + custom_prepare_model_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom prepare model function."}, + ) + custom_megatron_datasets_provider_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom megatron train_valid_test datasets provider function."}, + ) + custom_get_batch_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom get batch function."}, + ) + custom_loss_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom loss function."}, + ) + + # remaining args such as enabling Alibi/ROPE positional embeddings, + # wandb logging, Multi-Query Attention, etc. + other_megatron_args: Optional[Dict[str, Any]] = field( + default=None, + metadata={"help": "Other Megatron-LM arguments. Please refer Megatron-LM"}, + ) + + def __post_init__(self): + prefix = "MEGATRON_LM_" + if self.tp_degree is None: + self.tp_degree = int(os.environ.get(prefix + "TP_DEGREE", 1)) + if self.pp_degree is None: + self.pp_degree = int(os.environ.get(prefix + "PP_DEGREE", 1)) + if self.num_micro_batches is None: + self.num_micro_batches = int(os.environ.get(prefix + "NUM_MICRO_BATCHES", 1)) + if self.gradient_clipping is None: + self.gradient_clipping = float(os.environ.get(prefix + "GRADIENT_CLIPPING", 1.0)) + if self.recompute_activations is None: + self.recompute_activations = str_to_bool(os.environ.get(prefix + "RECOMPUTE_ACTIVATIONS", "False")) == 1 + if self.use_distributed_optimizer is None: + self.use_distributed_optimizer = ( + str_to_bool(os.environ.get(prefix + "USE_DISTRIBUTED_OPTIMIZER", "False")) == 1 + ) + if self.sequence_parallelism is None: + self.sequence_parallelism = str_to_bool(os.environ.get(prefix + "SEQUENCE_PARALLELISM", "False")) == 1 + + if self.pp_degree > 1 or self.use_distributed_optimizer: + self.DDP_impl = "local" + else: + self.DDP_impl = "torch" + + if self.consumed_samples is not None: + if len(self.consumed_samples) == 1: + self.consumed_samples.extend([0, 0]) + elif len(self.consumed_samples) == 2: + self.consumed_samples.append(0) + + self.megatron_lm_default_args = { + "tensor_model_parallel_size": self.tp_degree, + "pipeline_model_parallel_size": self.pp_degree, + "pipeline_model_parallel_split_rank": self.pipeline_model_parallel_split_rank, + "num_layers_per_virtual_pipeline_stage": self.num_layers_per_virtual_pipeline_stage, + "DDP_impl": self.DDP_impl, + "use_distributed_optimizer": self.use_distributed_optimizer, + "sequence_parallel": self.sequence_parallelism, + "clip_grad": self.gradient_clipping, + "num_micro_batches": self.num_micro_batches, + "consumed_samples": self.consumed_samples, + "no_wd_decay_cond": self.no_wd_decay_cond, + "scale_lr_cond": self.scale_lr_cond, + "lr_mult": self.lr_mult, + "megatron_dataset_flag": self.megatron_dataset_flag, + "eval_iters": self.eval_iters, + "eval_interval": self.eval_interval, + } + if self.recompute_activations: + self.megatron_lm_default_args["recompute_granularity"] = "selective" + if self.tensorboard_dir is not None: + self.megatron_lm_default_args["tensorboard_dir"] = self.tensorboard_dir + if self.set_all_logging_options: + self.set_tensorboard_logging_options() + if self.other_megatron_args is not None: + self.megatron_lm_default_args.update(self.other_megatron_args) + + def set_network_size_args(self, model, batch_data=None): + model_config_type = model.config.model_type.lower() + for model_type in MODEL_CONFIGS_TO_MEGATRON_PARSERS.keys(): + if model_type in model_config_type: + MODEL_CONFIGS_TO_MEGATRON_PARSERS[model_type](self, model, batch_data) + return + raise ValueError( + f"Accelerate Megatron-LM integration not supports {model_config_type} model. " + "You can add your own model config parser." + ) + + def set_mixed_precision(self, mixed_precision): + if mixed_precision == "fp16": + self.megatron_lm_default_args["fp16"] = True + elif mixed_precision == "bf16": + self.megatron_lm_default_args["bf16"] = True + self.DDP_impl = "local" + self.megatron_lm_default_args["DDP_impl"] = self.DDP_impl + + def set_training_args(self, micro_batch_size, dp_degree): + self.data_parallel_size = dp_degree + self.micro_batch_size = micro_batch_size + self.global_batch_size = dp_degree * micro_batch_size * self.num_micro_batches + self.megatron_lm_default_args["data_parallel_size"] = self.data_parallel_size + self.megatron_lm_default_args["micro_batch_size"] = self.micro_batch_size + self.megatron_lm_default_args["global_batch_size"] = self.global_batch_size + + def set_optimizer_type(self, optimizer): + optimizer_name = optimizer.__class__.__name__.lower() + if "adam" in optimizer_name: + self.megatron_lm_default_args["optimizer"] = "adam" + self.megatron_lm_default_args["adam_beta1"] = optimizer.defaults["betas"][0] + self.megatron_lm_default_args["adam_beta2"] = optimizer.defaults["betas"][1] + self.megatron_lm_default_args["adam_eps"] = optimizer.defaults["eps"] + elif "sgd" in optimizer_name: + self.megatron_lm_default_args["optimizer"] = "sgd" + self.megatron_lm_default_args["sgd_momentum"] = optimizer.defaults["momentum"] + else: + raise ValueError(f"Optimizer {optimizer_name} is not supported by Megatron-LM") + + self.megatron_lm_default_args["lr"] = optimizer.defaults["lr"] + self.megatron_lm_default_args["weight_decay"] = optimizer.defaults["weight_decay"] + + def set_scheduler_args(self, scheduler): + if self.train_iters is None: + self.train_iters = scheduler.total_num_steps // self.megatron_lm_default_args["data_parallel_size"] + if self.train_samples is not None: + self.train_samples = None + warnings.warn( + "Ignoring `train_samples` as `train_iters` based on scheduler is being used for training." + ) + if self.lr_warmup_iters is None: + self.lr_warmup_iters = scheduler.warmup_num_steps // self.megatron_lm_default_args["data_parallel_size"] + if self.lr_warmup_samples is not None: + warnings.warn( + "Ignoring `lr_warmup_samples` as `lr_warmup_iters` based on scheduler is being used for training." + ) + self.lr_warmup_samples = 0 + + self.megatron_lm_default_args["train_iters"] = self.train_iters + self.megatron_lm_default_args["lr_warmup_iters"] = self.lr_warmup_iters + self.megatron_lm_default_args["train_samples"] = self.train_samples + self.megatron_lm_default_args["lr_warmup_samples"] = self.lr_warmup_samples + self.megatron_lm_default_args["lr_decay_iters"] = self.lr_decay_iters + self.megatron_lm_default_args["lr_decay_samples"] = self.lr_decay_samples + self.megatron_lm_default_args["lr_warmup_fraction"] = self.lr_warmup_fraction + self.megatron_lm_default_args["lr_decay_style"] = self.lr_decay_style + self.megatron_lm_default_args["weight_decay_incr_style"] = self.weight_decay_incr_style + self.megatron_lm_default_args["start_weight_decay"] = self.start_weight_decay + self.megatron_lm_default_args["end_weight_decay"] = self.end_weight_decay + self.megatron_lm_default_args["min_lr"] = self.min_lr + + def set_tensorboard_logging_options(self): + from megatron.arguments import _add_logging_args + + parser = argparse.ArgumentParser() + parser = _add_logging_args(parser) + logging_args = parser.parse_known_args() + self.dataset_args = vars(logging_args[0]) + for key, value in self.dataset_args.items(): + if key.startswith("log_"): + self.megatron_lm_default_args[key] = True + elif key.startswith("no_log_"): + self.megatron_lm_default_args[key.replace("no_", "")] = True + + +MODEL_CONFIGS_TO_MEGATRON_PARSERS = {} + + +def add_model_config_to_megatron_parser(model_type: str): + def add_model_config_parser_helper(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + + MODEL_CONFIGS_TO_MEGATRON_PARSERS[model_type] = func + return wrapper + + return add_model_config_parser_helper + + +@add_model_config_to_megatron_parser("megatron-bert") +def parse_bert_config(megatron_lm_plugin, model, batch_data): + model_type_name = "bert" + num_layers = model.config.num_hidden_layers + hidden_size = model.config.hidden_size + num_attention_heads = model.config.num_attention_heads + max_position_embeddings = model.config.max_position_embeddings + num_labels = model.config.num_labels + orig_vocab_size = model.config.vocab_size + pretraining_flag = False + if "maskedlm" in model.__class__.__name__.lower(): + pretraining_flag = True + if megatron_lm_plugin.seq_length is not None: + if megatron_lm_plugin.encoder_seq_length is not None: + warnings.warn("Both `seq_length` and `encoder_seq_length` are set. Using `encoder_seq_length`.") + megatron_lm_plugin.seq_length = megatron_lm_plugin.encoder_seq_length + elif megatron_lm_plugin.encoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.encoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + megatron_lm_plugin.megatron_lm_default_args["num_labels"] = num_labels + + +@add_model_config_to_megatron_parser("gpt2") +def parse_gpt2_config(megatron_lm_plugin, model, batch_data): + model_type_name = "gpt" + num_layers = model.config.n_layer + hidden_size = model.config.n_embd + num_attention_heads = model.config.n_head + max_position_embeddings = model.config.n_positions + orig_vocab_size = model.config.vocab_size + pretraining_flag = True + if megatron_lm_plugin.seq_length is not None: + if megatron_lm_plugin.decoder_seq_length is not None: + warnings.warn("Both `seq_length` and `decoder_seq_length` are set. Using `decoder_seq_length`.") + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif megatron_lm_plugin.decoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["return_logits"] = megatron_lm_plugin.return_logits + megatron_lm_plugin.megatron_lm_default_args["tokenizer_type"] = "GPT2BPETokenizer" + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@add_model_config_to_megatron_parser("t5") +def parse_t5_config(megatron_lm_plugin, model, batch_data): + model_type_name = "t5" + num_layers = model.config.num_layers + hidden_size = model.config.d_model + num_attention_heads = model.config.num_heads + max_position_embeddings = model.config.n_positions if hasattr(model.config, "n_positions") else 1024 + orig_vocab_size = model.config.vocab_size + pretraining_flag = True + if megatron_lm_plugin.encoder_seq_length is None: + if batch_data is not None: + megatron_lm_plugin.encoder_seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.encoder_seq_length = max_position_embeddings + if megatron_lm_plugin.decoder_seq_length is None: + if batch_data is not None: + megatron_lm_plugin.decoder_seq_length = batch_data["labels"].shape[1] + else: + megatron_lm_plugin.decoder_seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["encoder_seq_length"] = megatron_lm_plugin.encoder_seq_length + megatron_lm_plugin.megatron_lm_default_args["decoder_seq_length"] = megatron_lm_plugin.decoder_seq_length + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@add_model_config_to_megatron_parser("llama") +def parse_llama_config(megatron_lm_plugin, model, batch_data): + model_type_name = "gpt" + num_layers = model.config.num_hidden_layers + pretraining_flag = True + hidden_size = model.config.hidden_size + num_attention_heads = model.config.num_attention_heads + orig_vocab_size = model.config.vocab_size + + max_position_embeddings = model.config.max_position_embeddings + seq_length = getattr(model.config, "max_sequence_length", None) + if megatron_lm_plugin.seq_length is None: + if seq_length is not None: + megatron_lm_plugin.seq_length = seq_length + elif megatron_lm_plugin.decoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + + megatron_lm_plugin.megatron_lm_default_args["return_logits"] = megatron_lm_plugin.return_logits + megatron_lm_plugin.megatron_lm_default_args["tokenizer_type"] = "Llama2Tokenizer" + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@dataclass +class BnbQuantizationConfig: + """ + A plugin to enable BitsAndBytes 4bit and 8bit quantization + """ + + load_in_8bit: bool = field(default=False, metadata={"help": "enable 8bit quantization."}) + + llm_int8_threshold: float = field( + default=6.0, metadata={"help": "value of the outliner threshold. only relevant when load_in_8bit=True"} + ) + + load_in_4bit: bool = field(default=False, metadata={"help": "enable 4bit quantization."}) + + bnb_4bit_quant_type: str = field( + default="fp4", + metadata={ + "help": "set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','np4'}." + }, + ) + + bnb_4bit_use_double_quant: bool = field( + default=False, + metadata={ + "help": "enable nested quantization where the quantization constants from the first quantization are quantized again." + }, + ) + + bnb_4bit_compute_dtype: bool = field( + default="fp16", + metadata={ + "help": "This sets the computational type which might be different than the input time. For example, inputs might be " + "fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}." + }, + ) + + torch_dtype: torch.dtype = field( + default=None, + metadata={ + "help": "this sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the value" + "to `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model " + }, + ) + + skip_modules: List[str] = field( + default=None, + metadata={ + "help": "an explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`." + }, + ) + + keep_in_fp32_modules: List[str] = field( + default=None, + metadata={"help": "an explicit list of the modules that we don't quantize. We keep them in `torch.float32`."}, + ) + + def __post_init__(self): + """ + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + if not isinstance(self.load_in_8bit, bool): + raise ValueError("load_in_8bit must be a boolean") + + if not isinstance(self.load_in_4bit, bool): + raise ValueError("load_in_4bit must be a boolean") + + if self.load_in_4bit and self.load_in_8bit: + raise ValueError("load_in_4bit and load_in_8 can't be both True") + + if not self.load_in_4bit and not self.load_in_8bit: + raise ValueError("load_in_4bit and load_in_8 can't be both False") + + if not isinstance(self.llm_int8_threshold, (int, float)): + raise ValueError("llm_int8_threshold must be a float or an int") + + if not isinstance(self.bnb_4bit_quant_type, str): + raise ValueError("bnb_4bit_quant_type must be a string") + elif self.bnb_4bit_quant_type not in ["fp4", "nf4"]: + raise ValueError(f"bnb_4bit_quant_type must be in ['fp4','nf4'] but found {self.bnb_4bit_quant_type}") + + if not isinstance(self.bnb_4bit_use_double_quant, bool): + raise ValueError("bnb_4bit_use_double_quant must be a boolean") + + if isinstance(self.bnb_4bit_compute_dtype, str): + if self.bnb_4bit_compute_dtype == "fp32": + self.bnb_4bit_compute_dtype = torch.float32 + elif self.bnb_4bit_compute_dtype == "fp16": + self.bnb_4bit_compute_dtype = torch.float16 + elif self.bnb_4bit_compute_dtype == "bf16": + self.bnb_4bit_compute_dtype = torch.bfloat16 + else: + raise ValueError( + f"bnb_4bit_compute_dtype must be in ['fp32','fp16','bf16'] but found {self.bnb_4bit_compute_dtype}" + ) + elif not isinstance(self.bnb_4bit_compute_dtype, torch.dtype): + raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype") + + if self.skip_modules is not None and not isinstance(self.skip_modules, list): + raise ValueError("skip_modules must be a list of strings") + + if self.keep_in_fp32_modules is not None and not isinstance(self.keep_in_fp32_modules, list): + raise ValueError("keep_in_fp_32_modules must be a list of strings") + + if self.load_in_4bit: + self.target_dtype = CustomDtype.INT4 + + if self.load_in_8bit: + self.target_dtype = torch.int8 + + if self.load_in_4bit and self.llm_int8_threshold != 6.0: + warnings.warn("llm_int8_threshold can only be used for model loaded in 8bit") + + if isinstance(self.torch_dtype, str): + if self.torch_dtype == "fp32": + self.torch_dtype = torch.float32 + elif self.torch_dtype == "fp16": + self.torch_dtype = torch.float16 + elif self.torch_dtype == "bf16": + self.torch_dtype = torch.bfloat16 + else: + raise ValueError(f"torch_dtype must be in ['fp32','fp16','bf16'] but found {self.torch_dtype}") + if self.load_in_8bit and self.torch_dtype is None: + self.torch_dtype = torch.float16 + + if self.load_in_4bit and self.torch_dtype is None: + self.torch_dtype = self.bnb_4bit_compute_dtype + + if not isinstance(self.torch_dtype, torch.dtype): + raise ValueError("torch_dtype must be a torch.dtype") + + +def get_module_class_from_name(module, name): + """ + Gets a class from a module by its name. + + Args: + module (`torch.nn.Module`): The module to get the class from. + name (`str`): The name of the class. + """ + modules_children = list(module.children()) + if module.__class__.__name__ == name: + return module.__class__ + elif len(modules_children) == 0: + return + else: + for child_module in modules_children: + module_class = get_module_class_from_name(child_module, name) + if module_class is not None: + return module_class diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/deepspeed.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/deepspeed.py new file mode 100644 index 0000000000000000000000000000000000000000..fe5a63fc7314d42f68baae41cf56f9abc94237a0 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/deepspeed.py @@ -0,0 +1,271 @@ +# 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. + +import base64 +import json +import os +from copy import deepcopy + +from ..optimizer import AcceleratedOptimizer +from ..scheduler import AcceleratedScheduler + + +class HfDeepSpeedConfig: + """ + This object contains a DeepSpeed configuration dictionary and can be quickly queried for things like zero stage. + + A `weakref` of this object is stored in the module's globals to be able to access the config from areas where + things like the Trainer object is not available (e.g. `from_pretrained` and `_get_resized_embeddings`). Therefore + it's important that this object remains alive while the program is still running. + + [`Trainer`] uses the `HfTrainerDeepSpeedConfig` subclass instead. That subclass has logic to sync the configuration + with values of [`TrainingArguments`] by replacing special placeholder values: `"auto"`. Without this special logic + the DeepSpeed configuration is not modified in any way. + + Args: + config_file_or_dict (`Union[str, Dict]`): path to DeepSpeed config file or dict. + + """ + + def __init__(self, config_file_or_dict): + if isinstance(config_file_or_dict, dict): + # Don't modify user's data should they want to reuse it (e.g. in tests), because once we + # modified it, it will not be accepted here again, since `auto` values would have been overridden + config = deepcopy(config_file_or_dict) + elif os.path.exists(config_file_or_dict): + with open(config_file_or_dict, encoding="utf-8") as f: + config = json.load(f) + else: + try: + config_decoded = base64.urlsafe_b64decode(config_file_or_dict).decode("utf-8") + config = json.loads(config_decoded) + except (UnicodeDecodeError, AttributeError, ValueError): + raise ValueError( + f"Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}" + ) + + self.config = config + + self.set_stage_and_offload() + + def set_stage_and_offload(self): + # zero stage - this is done as early as possible, before model is created, to allow + # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object + # during ``zero.Init()`` which needs to know the dtype, and some other hparams. + self._stage = self.get_value("zero_optimization.stage", -1) + + # offload + self._offload = False + if self.is_zero2() or self.is_zero3(): + offload_devices_valid = set(["cpu", "nvme"]) + offload_devices = set( + [ + self.get_value("zero_optimization.offload_optimizer.device"), + self.get_value("zero_optimization.offload_param.device"), + ] + ) + if len(offload_devices & offload_devices_valid) > 0: + self._offload = True + + def find_config_node(self, ds_key_long): + config = self.config + + # find the config node of interest if it exists + nodes = ds_key_long.split(".") + ds_key = nodes.pop() + for node in nodes: + config = config.get(node) + if config is None: + return None, ds_key + + return config, ds_key + + def get_value(self, ds_key_long, default=None): + """ + Returns the set value or `default` if no value is set + """ + config, ds_key = self.find_config_node(ds_key_long) + if config is None: + return default + return config.get(ds_key, default) + + def del_config_sub_tree(self, ds_key_long, must_exist=False): + """ + Deletes a sub-section of the config file if it's found. + + Unless `must_exist` is `True` the section doesn't have to exist. + """ + config = self.config + + # find the config node of interest if it exists + nodes = ds_key_long.split(".") + for node in nodes: + parent_config = config + config = config.get(node) + if config is None: + if must_exist: + raise ValueError(f"Can't find {ds_key_long} entry in the config: {self.config}") + else: + return + + # if found remove it + if parent_config is not None: + parent_config.pop(node) + + def is_true(self, ds_key_long): + """ + Returns `True`/``False` only if the value is set, always `False` otherwise. So use this method to ask the very + specific question of whether the value is set to `True` (and it's not set to `False`` or isn't set). + + """ + value = self.get_value(ds_key_long) + return False if value is None else bool(value) + + def is_false(self, ds_key_long): + """ + Returns `True`/``False` only if the value is set, always `False` otherwise. So use this method to ask the very + specific question of whether the value is set to `False` (and it's not set to `True`` or isn't set). + """ + value = self.get_value(ds_key_long) + return False if value is None else not bool(value) + + def is_zero2(self): + return self._stage == 2 + + def is_zero3(self): + return self._stage == 3 + + def is_offload(self): + return self._offload + + +class DeepSpeedEngineWrapper: + """ + Internal wrapper for deepspeed.runtime.engine.DeepSpeedEngine. This is used to follow conventional training loop. + + Args: + engine (deepspeed.runtime.engine.DeepSpeedEngine): deepspeed engine to wrap + """ + + def __init__(self, engine): + self.engine = engine + + def backward(self, loss, **kwargs): + # runs backpropagation and handles mixed precision + self.engine.backward(loss, **kwargs) + + # Deepspeed's `engine.step` performs the following operations: + # - gradient accumulation check + # - gradient clipping + # - optimizer step + # - zero grad + # - checking overflow + # - lr_scheduler step (only if engine.lr_scheduler is not None) + self.engine.step() + # and this plugin overrides the above calls with no-ops when Accelerate runs under + # Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple + # training loop that works transparently under many training regimes. + + +class DeepSpeedOptimizerWrapper(AcceleratedOptimizer): + """ + Internal wrapper around a deepspeed optimizer. + + Args: + optimizer (`torch.optim.optimizer.Optimizer`): + The optimizer to wrap. + """ + + def __init__(self, optimizer): + super().__init__(optimizer, device_placement=False, scaler=None) + self.__has_overflow__ = hasattr(self.optimizer, "overflow") + + def zero_grad(self, set_to_none=None): + pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed + + def step(self): + pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed + + @property + def step_was_skipped(self): + """Whether or not the optimizer step was done, or skipped because of gradient overflow.""" + if self.__has_overflow__: + return self.optimizer.overflow + return False + + +class DeepSpeedSchedulerWrapper(AcceleratedScheduler): + """ + Internal wrapper around a deepspeed scheduler. + + Args: + scheduler (`torch.optim.lr_scheduler.LambdaLR`): + The scheduler to wrap. + optimizers (one or a list of `torch.optim.Optimizer`): + """ + + def __init__(self, scheduler, optimizers): + super().__init__(scheduler, optimizers) + + def step(self): + pass # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed + + +class DummyOptim: + """ + Dummy optimizer presents model parameters or param groups, this is primarily used to follow conventional training + loop when optimizer config is specified in the deepspeed config file. + + Args: + lr (float): + Learning rate. + params (iterable): iterable of parameters to optimize or dicts defining + parameter groups + weight_decay (float): + Weight decay. + **kwargs (additional keyword arguments, *optional*): + Other arguments. + """ + + def __init__(self, params, lr=0.001, weight_decay=0, **kwargs): + self.params = params + self.lr = lr + self.weight_decay = weight_decay + self.kwargs = kwargs + + +class DummyScheduler: + """ + Dummy scheduler presents model parameters or param groups, this is primarily used to follow conventional training + loop when scheduler config is specified in the deepspeed config file. + + Args: + optimizer (`torch.optim.optimizer.Optimizer`): + The optimizer to wrap. + total_num_steps (int, *optional*): + Total number of steps. + warmup_num_steps (int, *optional*): + Number of steps for warmup. + lr_scheduler_callable (callable, *optional*): + A callable function that creates an LR Scheduler. It accepts only one argument `optimizer`. + **kwargs (additional keyword arguments, *optional*): + Other arguments. + """ + + def __init__(self, optimizer, total_num_steps=None, warmup_num_steps=0, lr_scheduler_callable=None, **kwargs): + self.optimizer = optimizer + self.total_num_steps = total_num_steps + self.warmup_num_steps = warmup_num_steps + self.lr_scheduler_callable = lr_scheduler_callable + self.kwargs = kwargs diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/environment.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/environment.py new file mode 100644 index 0000000000000000000000000000000000000000..9fdbd323632769146188cac1e91d08ab1e2ba617 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/environment.py @@ -0,0 +1,274 @@ +# 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. + +import logging +import math +import os +import platform +import subprocess +import sys +from dataclasses import dataclass, field +from functools import lru_cache +from shutil import which +from typing import List, Optional + +import torch +from packaging.version import parse + + +logger = logging.getLogger(__name__) + + +def convert_dict_to_env_variables(current_env: dict): + """ + Verifies that all keys and values in `current_env` do not contain illegal keys or values, and returns a list of + strings as the result. + + Example: + ```python + >>> from accelerate.utils.environment import verify_env + + >>> env = {"ACCELERATE_DEBUG_MODE": "1", "BAD_ENV_NAME": ">> valid_env_items = verify_env(env) + >>> print(valid_env_items) + ["ACCELERATE_DEBUG_MODE=1\n", "OTHER_ENV=2\n"] + ``` + """ + forbidden_chars = [";", "\n", "<", ">", " "] + valid_env_items = [] + for key, value in current_env.items(): + if all(char not in (key + value) for char in forbidden_chars) and len(key) >= 1 and len(value) >= 1: + valid_env_items.append(f"{key}={value}\n") + else: + logger.warning(f"WARNING: Skipping {key}={value} as it contains forbidden characters or missing values.") + return valid_env_items + + +def str_to_bool(value) -> int: + """ + Converts a string representation of truth to `True` (1) or `False` (0). + + True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`; + """ + value = value.lower() + if value in ("y", "yes", "t", "true", "on", "1"): + return 1 + elif value in ("n", "no", "f", "false", "off", "0"): + return 0 + else: + raise ValueError(f"invalid truth value {value}") + + +def get_int_from_env(env_keys, default): + """Returns the first positive env value found in the `env_keys` list or the default.""" + for e in env_keys: + val = int(os.environ.get(e, -1)) + if val >= 0: + return val + return default + + +def parse_flag_from_env(key, default=False): + """Returns truthy value for `key` from the env if available else the default.""" + value = os.environ.get(key, str(default)) + return str_to_bool(value) == 1 # As its name indicates `str_to_bool` actually returns an int... + + +def parse_choice_from_env(key, default="no"): + value = os.environ.get(key, str(default)) + return value + + +def are_libraries_initialized(*library_names: str) -> List[str]: + """ + Checks if any of `library_names` are imported in the environment. Will return any names that are. + """ + return [lib_name for lib_name in library_names if lib_name in sys.modules.keys()] + + +def _nvidia_smi(): + """ + Returns the right nvidia-smi command based on the system. + """ + if platform.system() == "Windows": + # If platform is Windows and nvidia-smi can't be found in path + # try from systemd drive with default installation path + command = which("nvidia-smi") + if command is None: + command = "%s\\Program Files\\NVIDIA Corporation\\NVSMI\\nvidia-smi.exe" % os.environ["systemdrive"] + else: + command = "nvidia-smi" + return command + + +def get_gpu_info(): + """ + Gets GPU count and names using `nvidia-smi` instead of torch to not initialize CUDA. + + Largely based on the `gputil` library. + """ + # Returns as list of `n` GPUs and their names + output = subprocess.check_output( + [_nvidia_smi(), "--query-gpu=count,name", "--format=csv,noheader"], universal_newlines=True + ) + output = output.strip() + gpus = output.split(os.linesep) + # Get names from output + gpu_count = len(gpus) + gpu_names = [gpu.split(",")[1].strip() for gpu in gpus] + return gpu_names, gpu_count + + +def get_driver_version(): + """ + Returns the driver version + + In the case of multiple GPUs, will return the first. + """ + output = subprocess.check_output( + [_nvidia_smi(), "--query-gpu=driver_version", "--format=csv,noheader"], universal_newlines=True + ) + output = output.strip() + return output.split(os.linesep)[0] + + +def check_cuda_p2p_ib_support(): + """ + Checks if the devices being used have issues with P2P and IB communications, namely any consumer GPU hardware after + the 3090. + + Noteably uses `nvidia-smi` instead of torch to not initialize CUDA. + """ + try: + device_names, device_count = get_gpu_info() + # As new consumer GPUs get released, add them to `unsupported_devices`` + unsupported_devices = {"RTX 40"} + if device_count > 1: + if any( + unsupported_device in device_name + for device_name in device_names + for unsupported_device in unsupported_devices + ): + # Check if they have the right driver version + acceptable_driver_version = "550.40.07" + current_driver_version = get_driver_version() + if parse(current_driver_version) < parse(acceptable_driver_version): + return False + return True + except Exception: + pass + return True + + +def check_fp8_capability(): + """ + Checks if all the current GPUs available support FP8. + + Notably must initialize `torch.cuda` to check. + """ + cuda_device_capacity = torch.cuda.get_device_capability() + return cuda_device_capacity >= (8, 9) + + +@dataclass +class CPUInformation: + """ + Stores information about the CPU in a distributed environment. It contains the following attributes: + - rank: The rank of the current process. + - world_size: The total number of processes in the world. + - local_rank: The rank of the current process on the local node. + - local_world_size: The total number of processes on the local node. + """ + + rank: int = field(default=0, metadata={"help": "The rank of the current process."}) + world_size: int = field(default=1, metadata={"help": "The total number of processes in the world."}) + local_rank: int = field(default=0, metadata={"help": "The rank of the current process on the local node."}) + local_world_size: int = field(default=1, metadata={"help": "The total number of processes on the local node."}) + + +def get_cpu_distributed_information() -> CPUInformation: + """ + Returns various information about the environment in relation to CPU distributed training as a `CPUInformation` + dataclass. + """ + information = {} + information["rank"] = get_int_from_env(["RANK", "PMI_RANK", "OMPI_COMM_WORLD_RANK", "MV2_COMM_WORLD_RANK"], 0) + information["world_size"] = get_int_from_env( + ["WORLD_SIZE", "PMI_SIZE", "OMPI_COMM_WORLD_SIZE", "MV2_COMM_WORLD_SIZE"], 1 + ) + information["local_rank"] = get_int_from_env( + ["LOCAL_RANK", "MPI_LOCALRANKID", "OMPI_COMM_WORLD_LOCAL_RANK", "MV2_COMM_WORLD_LOCAL_RANK"], 0 + ) + information["local_world_size"] = get_int_from_env( + ["LOCAL_WORLD_SIZE", "MPI_LOCALNRANKS", "OMPI_COMM_WORLD_LOCAL_SIZE", "MV2_COMM_WORLD_LOCAL_SIZE"], + 1, + ) + return CPUInformation(**information) + + +def override_numa_affinity(local_process_index: int, verbose: Optional[bool] = None) -> None: + """ + Overrides whatever NUMA affinity is set for the current process. This is very taxing and requires recalculating the + affinity to set, ideally you should use `utils.environment.set_numa_affinity` instead. + + Args: + local_process_index (int): + The index of the current process on the current server. + verbose (bool, *optional*): + Whether to log out the assignment of each CPU. If `ACCELERATE_DEBUG_MODE` is enabled, will default to True. + """ + if verbose is None: + verbose = parse_flag_from_env("ACCELERATE_DEBUG_MODE", False) + if torch.cuda.is_available(): + from accelerate.utils import is_pynvml_available + + if not is_pynvml_available(): + raise ImportError( + "To set CPU affinity on CUDA GPUs the `pynvml` package must be available. (`pip install pynvml`)" + ) + import pynvml as nvml + + # The below code is based on https://github.com/NVIDIA/DeepLearningExamples/blob/master/TensorFlow2/LanguageModeling/BERT/gpu_affinity.py + nvml.nvmlInit() + num_elements = math.ceil(os.cpu_count() / 64) + handle = nvml.nvmlDeviceGetHandleByIndex(local_process_index) + affinity_string = "" + for j in nvml.nvmlDeviceGetCpuAffinity(handle, num_elements): + # assume nvml returns list of 64 bit ints + affinity_string = f"{j:064b}{affinity_string}" + affinity_list = [int(x) for x in affinity_string] + affinity_list.reverse() # so core 0 is the 0th element + affinity_to_set = [i for i, e in enumerate(affinity_list) if e != 0] + os.sched_setaffinity(0, affinity_to_set) + if verbose: + cpu_cores = os.sched_getaffinity(0) + logger.info(f"Assigning {len(cpu_cores)} cpu cores to process {local_process_index}: {cpu_cores}") + + +@lru_cache +def set_numa_affinity(local_process_index: int, verbose: Optional[bool] = None) -> None: + """ + Assigns the current process to a specific NUMA node. Ideally most efficient when having at least 2 cpus per node. + + This result is cached between calls. If you want to override it, please use + `accelerate.utils.environment.override_numa_afifnity`. + + Args: + local_process_index (int): + The index of the current process on the current server. + verbose (bool, *optional*): + Whether to print the new cpu cores assignment for each process. If `ACCELERATE_DEBUG_MODE` is enabled, will + default to True. + """ + override_numa_affinity(local_process_index=local_process_index, verbose=verbose) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/fsdp_utils.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/fsdp_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cdf76cbc99c15bea7e6d2b1c4f4a285b4af355ba --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/fsdp_utils.py @@ -0,0 +1,326 @@ +# 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. +import os +import shutil +from pathlib import Path + +import torch + +from ..logging import get_logger +from .constants import FSDP_MODEL_NAME, OPTIMIZER_NAME, SAFE_WEIGHTS_NAME, WEIGHTS_NAME +from .modeling import is_peft_model +from .other import save +from .versions import is_torch_version + + +logger = get_logger(__name__) + + +def enable_fsdp_ram_efficient_loading(): + """ + Enables RAM efficient loading of Hugging Face models for FSDP in the environment. + """ + # Sets values for `transformers.modeling_utils.is_fsdp_enabled` + if "ACCELERATE_USE_FSDP" not in os.environ: + os.environ["ACCELERATE_USE_FSDP"] = "True" + os.environ["FSDP_CPU_RAM_EFFICIENT_LOADING"] = "True" + + +def disable_fsdp_ram_efficient_loading(): + """ + Disables RAM efficient loading of Hugging Face models for FSDP in the environment. + """ + os.environ["FSDP_CPU_RAM_EFFICIENT_LOADING"] = "False" + + +def _get_model_state_dict(model, adapter_only=False): + if adapter_only and is_peft_model(model): + from peft import get_peft_model_state_dict + + return get_peft_model_state_dict(model, adapter_name=model.active_adapter) + else: + return model.state_dict() + + +def _set_model_state_dict(model, state_dict, adapter_only=False): + if adapter_only and is_peft_model(model): + from peft import set_peft_model_state_dict + + return set_peft_model_state_dict(model, state_dict, adapter_name=model.active_adapter) + else: + return model.load_state_dict(state_dict) + + +def save_fsdp_model(fsdp_plugin, accelerator, model, output_dir, model_index=0, adapter_only=False): + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + from torch.distributed.checkpoint.default_planner import DefaultSavePlanner + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + os.makedirs(output_dir, exist_ok=True) + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + # FSDP raises error when single GPU is used with `offload_to_cpu=True` for FULL_STATE_DICT + # so, only enable it when num_processes>1 + is_multi_process = accelerator.num_processes > 1 + fsdp_plugin.state_dict_config.offload_to_cpu = is_multi_process + fsdp_plugin.state_dict_config.rank0_only = is_multi_process + + with FSDP.state_dict_type( + model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config + ): + state_dict = _get_model_state_dict(model, adapter_only=adapter_only) + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + weights_name = f"{FSDP_MODEL_NAME}.bin" if model_index == 0 else f"{FSDP_MODEL_NAME}_{model_index}.bin" + output_model_file = os.path.join(output_dir, weights_name) + if accelerator.process_index == 0: + logger.info(f"Saving model to {output_model_file}") + torch.save(state_dict, output_model_file) + logger.info(f"Model saved to {output_model_file}") + elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: + weights_name = ( + f"{FSDP_MODEL_NAME}_rank{accelerator.process_index}.bin" + if model_index == 0 + else f"{FSDP_MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin" + ) + output_model_file = os.path.join(output_dir, weights_name) + logger.info(f"Saving model to {output_model_file}") + torch.save(state_dict, output_model_file) + logger.info(f"Model saved to {output_model_file}") + elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: + ckpt_dir = os.path.join(output_dir, f"{FSDP_MODEL_NAME}_{model_index}") + os.makedirs(ckpt_dir, exist_ok=True) + logger.info(f"Saving model to {ckpt_dir}") + state_dict = {"model": state_dict} + + dist_cp.save_state_dict( + state_dict=state_dict, + storage_writer=dist_cp.FileSystemWriter(ckpt_dir), + planner=DefaultSavePlanner(), + ) + logger.info(f"Model saved to {ckpt_dir}") + + +def load_fsdp_model(fsdp_plugin, accelerator, model, input_dir, model_index=0, adapter_only=False): + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + from torch.distributed.checkpoint.default_planner import DefaultLoadPlanner + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + accelerator.wait_for_everyone() + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + # FSDP raises error when single GPU is used with `offload_to_cpu=True` for FULL_STATE_DICT + # so, only enable it when num_processes>1 + is_multi_process = accelerator.num_processes > 1 + fsdp_plugin.state_dict_config.offload_to_cpu = is_multi_process + fsdp_plugin.state_dict_config.rank0_only = is_multi_process + with FSDP.state_dict_type( + model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config + ): + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + if type(model) != FSDP and accelerator.process_index != 0: + if not fsdp_plugin.sync_module_states: + raise ValueError( + "Set the `sync_module_states` flag to `True` so that model states are synced across processes when " + "initializing FSDP object" + ) + return + weights_name = f"{FSDP_MODEL_NAME}.bin" if model_index == 0 else f"{FSDP_MODEL_NAME}_{model_index}.bin" + input_model_file = os.path.join(input_dir, weights_name) + logger.info(f"Loading model from {input_model_file}") + state_dict = torch.load(input_model_file) + logger.info(f"Model loaded from {input_model_file}") + elif fsdp_plugin.state_dict_type == StateDictType.LOCAL_STATE_DICT: + weights_name = ( + f"{FSDP_MODEL_NAME}_rank{accelerator.process_index}.bin" + if model_index == 0 + else f"{FSDP_MODEL_NAME}_{model_index}_rank{accelerator.process_index}.bin" + ) + input_model_file = os.path.join(input_dir, weights_name) + logger.info(f"Loading model from {input_model_file}") + state_dict = torch.load(input_model_file) + logger.info(f"Model loaded from {input_model_file}") + elif fsdp_plugin.state_dict_type == StateDictType.SHARDED_STATE_DICT: + ckpt_dir = ( + os.path.join(input_dir, f"{FSDP_MODEL_NAME}_{model_index}") + if f"{FSDP_MODEL_NAME}" not in input_dir + else input_dir + ) + logger.info(f"Loading model from {ckpt_dir}") + state_dict = {"model": _get_model_state_dict(model, adapter_only=adapter_only)} + dist_cp.load_state_dict( + state_dict=state_dict, + storage_reader=dist_cp.FileSystemReader(ckpt_dir), + planner=DefaultLoadPlanner(), + ) + state_dict = state_dict["model"] + logger.info(f"Model loaded from {ckpt_dir}") + load_result = _set_model_state_dict(model, state_dict, adapter_only=adapter_only) + return load_result + + +def save_fsdp_optimizer(fsdp_plugin, accelerator, optimizer, model, output_dir, optimizer_index=0): + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + from torch.distributed.checkpoint.default_planner import DefaultSavePlanner + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + os.makedirs(output_dir, exist_ok=True) + with FSDP.state_dict_type( + model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config + ): + optim_state = FSDP.optim_state_dict(model, optimizer) + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + if accelerator.process_index == 0: + optim_state_name = ( + f"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else f"{OPTIMIZER_NAME}_{optimizer_index}.bin" + ) + output_optimizer_file = os.path.join(output_dir, optim_state_name) + logger.info(f"Saving Optimizer state to {output_optimizer_file}") + torch.save(optim_state, output_optimizer_file) + logger.info(f"Optimizer state saved in {output_optimizer_file}") + else: + ckpt_dir = os.path.join(output_dir, f"{OPTIMIZER_NAME}_{optimizer_index}") + os.makedirs(ckpt_dir, exist_ok=True) + logger.info(f"Saving Optimizer state to {ckpt_dir}") + dist_cp.save_state_dict( + state_dict={"optimizer": optim_state}, + storage_writer=dist_cp.FileSystemWriter(ckpt_dir), + planner=DefaultSavePlanner(), + ) + logger.info(f"Optimizer state saved in {ckpt_dir}") + + +def load_fsdp_optimizer(fsdp_plugin, accelerator, optimizer, model, input_dir, optimizer_index=0, adapter_only=False): + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + from torch.distributed.checkpoint.optimizer import load_sharded_optimizer_state_dict + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + from torch.distributed.fsdp.fully_sharded_data_parallel import StateDictType + + accelerator.wait_for_everyone() + with FSDP.state_dict_type( + model, fsdp_plugin.state_dict_type, fsdp_plugin.state_dict_config, fsdp_plugin.optim_state_dict_config + ): + if fsdp_plugin.state_dict_type == StateDictType.FULL_STATE_DICT: + optim_state = None + if accelerator.process_index == 0 or not fsdp_plugin.optim_state_dict_config.rank0_only: + optimizer_name = ( + f"{OPTIMIZER_NAME}.bin" if optimizer_index == 0 else f"{OPTIMIZER_NAME}_{optimizer_index}.bin" + ) + input_optimizer_file = os.path.join(input_dir, optimizer_name) + logger.info(f"Loading Optimizer state from {input_optimizer_file}") + optim_state = torch.load(input_optimizer_file) + logger.info(f"Optimizer state loaded from {input_optimizer_file}") + else: + ckpt_dir = ( + os.path.join(input_dir, f"{OPTIMIZER_NAME}_{optimizer_index}") + if f"{OPTIMIZER_NAME}" not in input_dir + else input_dir + ) + logger.info(f"Loading Optimizer from {ckpt_dir}") + optim_state = load_sharded_optimizer_state_dict( + model_state_dict=_get_model_state_dict(model, adapter_only=adapter_only), + optimizer_key="optimizer", + storage_reader=dist_cp.FileSystemReader(ckpt_dir), + ) + optim_state = optim_state["optimizer"] + logger.info(f"Optimizer loaded from {ckpt_dir}") + flattened_osd = FSDP.optim_state_dict_to_load(model=model, optim=optimizer, optim_state_dict=optim_state) + optimizer.load_state_dict(flattened_osd) + + +def _distributed_checkpoint_to_merged_weights(checkpoint_dir: str, save_path: str, safe_serialization: bool = True): + """ + Passthrough to `torch.distributed.checkpoint.format_utils.dcp_to_torch_save` + + Will save under `save_path` as either `model.safetensors` or `pytorch_model.bin`. + """ + # Note: We import here to reduce import time from general modules, and isolate outside dependencies + import torch.distributed.checkpoint as dist_cp + import torch.distributed.checkpoint.format_utils as dist_cp_format_utils + + state_dict = {} + save_path = Path(save_path) + save_path.mkdir(exist_ok=True) + dist_cp_format_utils._load_state_dict( + state_dict, + storage_reader=dist_cp.FileSystemReader(checkpoint_dir), + planner=dist_cp_format_utils._EmptyStateDictLoadPlanner(), + no_dist=True, + ) + save_path = save_path / SAFE_WEIGHTS_NAME if safe_serialization else save_path / WEIGHTS_NAME + + # To handle if state is a dict like {model: {...}} + if len(state_dict.keys()) == 1: + state_dict = state_dict[list(state_dict)[0]] + save(state_dict, save_path, safe_serialization=safe_serialization) + return save_path + + +def merge_fsdp_weights( + checkpoint_dir: str, output_path: str, safe_serialization: bool = True, remove_checkpoint_dir: bool = False +): + """ + Merge the weights from sharded FSDP model checkpoints into a single combined checkpoint. Should be used if + `SHARDED_STATE_DICT` was used for the model. Weights will be saved to `{output_path}/model.safetensors` if + `safe_serialization` else `pytorch_model.bin`. + + Note: this is a CPU-bound process. + + Args: + checkpoint_dir (`str`): + The directory containing the FSDP checkpoints (can be either the model or optimizer). + output_path (`str`): + The path to save the merged checkpoint. + safe_serialization (`bool`, *optional*, defaults to `True`): + Whether to save the merged weights with safetensors (recommended). + remove_checkpoint_dir (`bool`, *optional*, defaults to `False`): + Whether to remove the checkpoint directory after merging. + """ + checkpoint_dir = Path(checkpoint_dir) + from accelerate.state import PartialState + + if not is_torch_version(">=", "2.3.0"): + raise ValueError("`merge_fsdp_weights` requires PyTorch >= 2.3.0`") + + # Verify that the checkpoint directory exists + if not checkpoint_dir.exists(): + model_path_exists = (checkpoint_dir / "pytorch_model_fsdp_0").exists() + optimizer_path_exists = (checkpoint_dir / "optimizer_0").exists() + err = f"Tried to load from {checkpoint_dir} but couldn't find a valid metadata file." + if model_path_exists and optimizer_path_exists: + err += " However, potential model and optimizer checkpoint directories exist." + err += f"Please pass in either {checkpoint_dir}/pytorch_model_fsdp_0 or {checkpoint_dir}/optimizer_0" + err += "instead." + elif model_path_exists: + err += " However, a potential model checkpoint directory exists." + err += f"Please try passing in {checkpoint_dir}/pytorch_model_fsdp_0 instead." + elif optimizer_path_exists: + err += " However, a potential optimizer checkpoint directory exists." + err += f"Please try passing in {checkpoint_dir}/optimizer_0 instead." + raise ValueError(err) + + # To setup `save` to work + state = PartialState() + if state.is_main_process: + logger.info(f"Merging FSDP weights from {checkpoint_dir}") + save_path = _distributed_checkpoint_to_merged_weights(checkpoint_dir, output_path, safe_serialization) + logger.info(f"Successfully merged FSDP weights and saved to {save_path}") + if remove_checkpoint_dir: + logger.info(f"Removing old checkpoint directory {checkpoint_dir}") + shutil.rmtree(checkpoint_dir) + state.wait_for_everyone() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/imports.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/imports.py new file mode 100644 index 0000000000000000000000000000000000000000..15f802e59264fa1332e0a465cfcea1c14e11e24b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/imports.py @@ -0,0 +1,442 @@ +# 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. + +import importlib +import importlib.metadata +import os +import warnings +from functools import lru_cache + +import torch +from packaging import version +from packaging.version import parse + +from .environment import parse_flag_from_env, str_to_bool +from .versions import compare_versions, is_torch_version + + +# Try to run Torch native job in an environment with TorchXLA installed by setting this value to 0. +USE_TORCH_XLA = parse_flag_from_env("USE_TORCH_XLA", default=True) + +_torch_xla_available = False +if USE_TORCH_XLA: + try: + import torch_xla.core.xla_model as xm # noqa: F401 + import torch_xla.runtime + + _torch_xla_available = True + except ImportError: + pass + +# Keep it for is_tpu_available. It will be removed along with is_tpu_available. +_tpu_available = _torch_xla_available + +# Cache this result has it's a C FFI call which can be pretty time-consuming +_torch_distributed_available = torch.distributed.is_available() + + +def _is_package_available(pkg_name, metadata_name=None): + # Check we're not importing a "pkg_name" directory somewhere but the actual library by trying to grab the version + package_exists = importlib.util.find_spec(pkg_name) is not None + if package_exists: + try: + # Some libraries have different names in the metadata + _ = importlib.metadata.metadata(pkg_name if metadata_name is None else metadata_name) + return True + except importlib.metadata.PackageNotFoundError: + return False + + +def is_torch_distributed_available() -> bool: + return _torch_distributed_available + + +def is_ccl_available(): + try: + pass + except ImportError: + print( + "Intel(R) oneCCL Bindings for PyTorch* is required to run DDP on Intel(R) GPUs, but it is not" + " detected. If you see \"ValueError: Invalid backend: 'ccl'\" error, please install Intel(R) oneCCL" + " Bindings for PyTorch*." + ) + return ( + importlib.util.find_spec("torch_ccl") is not None + or importlib.util.find_spec("oneccl_bindings_for_pytorch") is not None + ) + + +def get_ccl_version(): + return importlib.metadata.version("oneccl_bind_pt") + + +def is_import_timer_available(): + return _is_package_available("import_timer") + + +def is_pynvml_available(): + return _is_package_available("pynvml") or _is_package_available("pynvml", "nvidia-ml-py") + + +def is_pytest_available(): + return _is_package_available("pytest") + + +def is_msamp_available(): + return _is_package_available("msamp", "ms-amp") + + +def is_schedulefree_available(): + return _is_package_available("schedulefree") + + +def is_transformer_engine_available(): + return _is_package_available("transformer_engine", "transformer-engine") + + +def is_lomo_available(): + return _is_package_available("lomo_optim") + + +def is_fp8_available(): + return is_msamp_available() or is_transformer_engine_available() + + +def is_cuda_available(): + """ + Checks if `cuda` is available via an `nvml-based` check which won't trigger the drivers and leave cuda + uninitialized. + """ + pytorch_nvml_based_cuda_check_previous_value = os.environ.get("PYTORCH_NVML_BASED_CUDA_CHECK") + try: + os.environ["PYTORCH_NVML_BASED_CUDA_CHECK"] = str(1) + available = torch.cuda.is_available() + finally: + if pytorch_nvml_based_cuda_check_previous_value: + os.environ["PYTORCH_NVML_BASED_CUDA_CHECK"] = pytorch_nvml_based_cuda_check_previous_value + else: + os.environ.pop("PYTORCH_NVML_BASED_CUDA_CHECK", None) + + return available + + +@lru_cache +def is_tpu_available(check_device=True): + "Checks if `torch_xla` is installed and potentially if a TPU is in the environment" + warnings.warn( + "`is_tpu_available` is deprecated and will be removed in v0.27.0. " + "Please use the `is_torch_xla_available` instead.", + FutureWarning, + ) + # Due to bugs on the amp series GPUs, we disable torch-xla on them + if is_cuda_available(): + return False + if check_device: + if _tpu_available: + try: + # Will raise a RuntimeError if no XLA configuration is found + _ = xm.xla_device() + return True + except RuntimeError: + return False + return _tpu_available + + +@lru_cache +def is_torch_xla_available(check_is_tpu=False, check_is_gpu=False): + """ + Check if `torch_xla` is available. To train a native pytorch job in an environment with torch xla installed, set + the USE_TORCH_XLA to false. + """ + assert not (check_is_tpu and check_is_gpu), "The check_is_tpu and check_is_gpu cannot both be true." + + if not _torch_xla_available: + return False + elif check_is_gpu: + return torch_xla.runtime.device_type() in ["GPU", "CUDA"] + elif check_is_tpu: + return torch_xla.runtime.device_type() == "TPU" + + return True + + +def is_deepspeed_available(): + if is_mlu_available(): + return _is_package_available("deepspeed", metadata_name="deepspeed-mlu") + return _is_package_available("deepspeed") + + +def is_pippy_available(): + return is_torch_version(">=", "2.4.0") + + +def is_bf16_available(ignore_tpu=False): + "Checks if bf16 is supported, optionally ignoring the TPU" + if is_torch_xla_available(check_is_tpu=True): + return not ignore_tpu + if is_cuda_available(): + return torch.cuda.is_bf16_supported() + if is_mps_available(): + return False + return True + + +def is_4bit_bnb_available(): + package_exists = _is_package_available("bitsandbytes") + if package_exists: + bnb_version = version.parse(importlib.metadata.version("bitsandbytes")) + return compare_versions(bnb_version, ">=", "0.39.0") + return False + + +def is_8bit_bnb_available(): + package_exists = _is_package_available("bitsandbytes") + if package_exists: + bnb_version = version.parse(importlib.metadata.version("bitsandbytes")) + return compare_versions(bnb_version, ">=", "0.37.2") + return False + + +def is_bnb_available(): + return _is_package_available("bitsandbytes") + + +def is_torchvision_available(): + return _is_package_available("torchvision") + + +def is_megatron_lm_available(): + if str_to_bool(os.environ.get("ACCELERATE_USE_MEGATRON_LM", "False")) == 1: + if importlib.util.find_spec("megatron") is not None: + try: + megatron_version = parse(importlib.metadata.version("megatron-core")) + if compare_versions(megatron_version, "==", "0.5.0"): + return importlib.util.find_spec(".data", "megatron") + except Exception as e: + warnings.warn(f"Parse Megatron version failed. Exception:{e}") + return False + + +def is_transformers_available(): + return _is_package_available("transformers") + + +def is_datasets_available(): + return _is_package_available("datasets") + + +def is_peft_available(): + return _is_package_available("peft") + + +def is_timm_available(): + return _is_package_available("timm") + + +def is_triton_available(): + return _is_package_available("triton") + + +def is_aim_available(): + package_exists = _is_package_available("aim") + if package_exists: + aim_version = version.parse(importlib.metadata.version("aim")) + return compare_versions(aim_version, "<", "4.0.0") + return False + + +def is_tensorboard_available(): + return _is_package_available("tensorboard") or _is_package_available("tensorboardX") + + +def is_wandb_available(): + return _is_package_available("wandb") + + +def is_comet_ml_available(): + return _is_package_available("comet_ml") + + +def is_boto3_available(): + return _is_package_available("boto3") + + +def is_rich_available(): + if _is_package_available("rich"): + if "ACCELERATE_DISABLE_RICH" in os.environ: + warnings.warn( + "`ACCELERATE_DISABLE_RICH` is deprecated and will be removed in v0.22.0 and deactivated by default. Please use `ACCELERATE_ENABLE_RICH` if you wish to use `rich`." + ) + return not parse_flag_from_env("ACCELERATE_DISABLE_RICH", False) + return parse_flag_from_env("ACCELERATE_ENABLE_RICH", False) + return False + + +def is_sagemaker_available(): + return _is_package_available("sagemaker") + + +def is_tqdm_available(): + return _is_package_available("tqdm") + + +def is_clearml_available(): + return _is_package_available("clearml") + + +def is_pandas_available(): + return _is_package_available("pandas") + + +def is_mlflow_available(): + if _is_package_available("mlflow"): + return True + + if importlib.util.find_spec("mlflow") is not None: + try: + _ = importlib.metadata.metadata("mlflow-skinny") + return True + except importlib.metadata.PackageNotFoundError: + return False + return False + + +def is_mps_available(min_version="1.12"): + # With torch 1.12, you can use torch.backends.mps + # With torch 2.0.0, you can use torch.mps + return is_torch_version(">=", min_version) and torch.backends.mps.is_available() and torch.backends.mps.is_built() + + +def is_ipex_available(): + def get_major_and_minor_from_version(full_version): + return str(version.parse(full_version).major) + "." + str(version.parse(full_version).minor) + + _torch_version = importlib.metadata.version("torch") + if importlib.util.find_spec("intel_extension_for_pytorch") is None: + return False + _ipex_version = "N/A" + try: + _ipex_version = importlib.metadata.version("intel_extension_for_pytorch") + except importlib.metadata.PackageNotFoundError: + return False + torch_major_and_minor = get_major_and_minor_from_version(_torch_version) + ipex_major_and_minor = get_major_and_minor_from_version(_ipex_version) + if torch_major_and_minor != ipex_major_and_minor: + warnings.warn( + f"Intel Extension for PyTorch {ipex_major_and_minor} needs to work with PyTorch {ipex_major_and_minor}.*," + f" but PyTorch {_torch_version} is found. Please switch to the matching version and run again." + ) + return False + return True + + +@lru_cache +def is_mlu_available(check_device=False): + "Checks if `torch_mlu` is installed and potentially if a MLU is in the environment" + if importlib.util.find_spec("torch_mlu") is None: + return False + + import torch_mlu # noqa: F401 + + if check_device: + try: + # Will raise a RuntimeError if no MLU is found + _ = torch.mlu.device_count() + return torch.mlu.is_available() + except RuntimeError: + return False + return hasattr(torch, "mlu") and torch.mlu.is_available() + + +@lru_cache +def is_musa_available(check_device=False): + "Checks if `torch_musa` is installed and potentially if a MUSA is in the environment" + if importlib.util.find_spec("torch_musa") is None: + return False + + import torch_musa # noqa: F401 + + if check_device: + try: + # Will raise a RuntimeError if no MUSA is found + _ = torch.musa.device_count() + return torch.musa.is_available() + except RuntimeError: + return False + return hasattr(torch, "musa") and torch.musa.is_available() + + +@lru_cache +def is_npu_available(check_device=False): + "Checks if `torch_npu` is installed and potentially if a NPU is in the environment" + if importlib.util.find_spec("torch_npu") is None: + return False + + import torch_npu # noqa: F401 + + if check_device: + try: + # Will raise a RuntimeError if no NPU is found + _ = torch.npu.device_count() + return torch.npu.is_available() + except RuntimeError: + return False + return hasattr(torch, "npu") and torch.npu.is_available() + + +@lru_cache +def is_xpu_available(check_device=False): + """ + Checks if XPU acceleration is available either via `intel_extension_for_pytorch` or via stock PyTorch (>=2.4) and + potentially if a XPU is in the environment + """ + + "check if user disables it explicitly" + if not parse_flag_from_env("ACCELERATE_USE_XPU", default=True): + return False + + if is_ipex_available(): + if is_torch_version("<=", "1.12"): + return False + + import intel_extension_for_pytorch # noqa: F401 + else: + if is_torch_version("<=", "2.3"): + return False + + if check_device: + try: + # Will raise a RuntimeError if no XPU is found + _ = torch.xpu.device_count() + return torch.xpu.is_available() + except RuntimeError: + return False + return hasattr(torch, "xpu") and torch.xpu.is_available() + + +def is_dvclive_available(): + return _is_package_available("dvclive") + + +def is_torchdata_available(): + return _is_package_available("torchdata") + + +# TODO: Remove this function once stateful_dataloader is a stable feature in torchdata. +def is_torchdata_stateful_dataloader_available(): + package_exists = _is_package_available("torchdata") + if package_exists: + torchdata_version = version.parse(importlib.metadata.version("torchdata")) + return compare_versions(torchdata_version, ">=", "0.8.0") + return False diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/launch.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/launch.py new file mode 100644 index 0000000000000000000000000000000000000000..56cf1a729b42ab8fc4a4ba7dbe44277e83fc81b1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/launch.py @@ -0,0 +1,682 @@ +# 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. + +import argparse +import os +import subprocess +import sys +import warnings +from ast import literal_eval +from shutil import which +from typing import Any, Dict, List, Tuple + +import torch + +from ..commands.config.config_args import SageMakerConfig +from ..utils import ( + DynamoBackend, + PrecisionType, + is_fp8_available, + is_ipex_available, + is_mlu_available, + is_musa_available, + is_npu_available, + is_torch_xla_available, + is_xpu_available, +) +from ..utils.constants import DEEPSPEED_MULTINODE_LAUNCHERS +from ..utils.other import is_port_in_use, merge_dicts +from .dataclasses import DistributedType, SageMakerDistributedType + + +def _filter_args(args, parser, default_args=[]): + """ + Filters out all `accelerate` specific args + """ + new_args, _ = parser.parse_known_args(default_args) + for key, value in vars(args).items(): + if key in vars(new_args).keys(): + setattr(new_args, key, value) + return new_args + + +def _get_mpirun_args(): + """ + Determines the executable and argument names for mpirun, based on the type of install. The supported MPI programs + are: OpenMPI, Intel MPI, or MVAPICH. + + Returns: Program name and arg names for hostfile, num processes, and processes per node + """ + # Find the MPI program name + mpi_apps = [x for x in ["mpirun", "mpiexec"] if which(x)] + + if len(mpi_apps) == 0: + raise OSError("mpirun or mpiexec were not found. Ensure that Intel MPI, Open MPI, or MVAPICH are installed.") + + # Call the app with the --version flag to determine which MPI app is installed + mpi_app = mpi_apps[0] + mpirun_version = subprocess.check_output([mpi_app, "--version"]) + + if b"Open MPI" in mpirun_version: + return mpi_app, "--hostfile", "-n", "--npernode", "--bind-to" + else: + # Intel MPI and MVAPICH both use the same arg names + return mpi_app, "-f", "-n", "-ppn", "" + + +def setup_fp8_env(args: argparse.Namespace, current_env: Dict[str, str]): + """ + Setup the FP8 environment variables. + """ + prefix = "ACCELERATE_" + for arg in vars(args): + if arg.startswith("fp8_"): + value = getattr(args, arg) + if value is not None: + current_env[f"{prefix}{arg.upper()}"] = str(getattr(args, arg)) + return current_env + + +def prepare_simple_launcher_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]: + """ + Prepares and returns the command list and an environment with the correct simple launcher environment variables. + """ + cmd = [] + if args.no_python and args.module: + raise ValueError("--module and --no_python cannot be used together") + + if args.mpirun_hostfile is not None: + mpi_app_name, hostfile_arg, num_proc_arg, proc_per_node_arg, bind_to_arg = _get_mpirun_args() + mpirun_ccl = getattr(args, "mpirun_ccl", None) + bind_to = getattr(args, "bind-to", "socket") + num_machines = args.num_machines + num_processes = getattr(args, "num_processes", None) + nproc_per_node = str(num_processes // num_machines) if num_processes and num_machines else "1" + cmd += [ + mpi_app_name, + hostfile_arg, + args.mpirun_hostfile, + proc_per_node_arg, + nproc_per_node, + ] + if num_processes: + cmd += [num_proc_arg, str(num_processes)] + if bind_to_arg: + cmd += [bind_to_arg, bind_to] + if not args.no_python: + cmd.append(sys.executable) + if args.module: + cmd.append("-m") + cmd.append(args.training_script) + cmd.extend(args.training_script_args) + + current_env = os.environ.copy() + current_env["ACCELERATE_USE_CPU"] = str(args.cpu or args.use_cpu) + if args.debug: + current_env["ACCELERATE_DEBUG_MODE"] = "true" + if args.gpu_ids != "all" and args.gpu_ids is not None: + if is_xpu_available(): + current_env["ZE_AFFINITY_MASK"] = args.gpu_ids + elif is_mlu_available(): + current_env["MLU_VISIBLE_DEVICES"] = args.gpu_ids + elif is_musa_available(): + current_env["MUSA_VISIBLE_DEVICES"] = args.gpu_ids + elif is_npu_available(): + current_env["ASCEND_RT_VISIBLE_DEVICES"] = args.gpu_ids + else: + current_env["CUDA_VISIBLE_DEVICES"] = args.gpu_ids + if args.num_machines > 1: + current_env["MASTER_ADDR"] = args.main_process_ip + current_env["MASTER_PORT"] = str(args.main_process_port) + + if args.mpirun_hostfile is not None: + current_env["CCL_WORKER_COUNT"] = str(mpirun_ccl) + elif args.num_processes > 1: + current_env["MASTER_ADDR"] = args.main_process_ip if args.main_process_ip is not None else "127.0.0.1" + current_env["MASTER_PORT"] = str(args.main_process_port) if args.main_process_port is not None else "29500" + + try: + mixed_precision = PrecisionType(args.mixed_precision.lower()) + except ValueError: + raise ValueError( + f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." + ) + + current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) + if args.mixed_precision.lower() == "fp8": + if not is_fp8_available(): + raise RuntimeError( + "FP8 is not available on this machine. Please ensure that either Transformer Engine or MSAMP is installed." + ) + current_env = setup_fp8_env(args, current_env) + + try: + dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) + except ValueError: + raise ValueError( + f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." + ) + current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value + current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode + current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph) + current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic) + + current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process) + if is_ipex_available(): + current_env["ACCELERATE_USE_IPEX"] = str(args.ipex).lower() + current_env["ACCELERATE_USE_XPU"] = str(args.use_xpu).lower() + if args.enable_cpu_affinity: + current_env["ACCELERATE_CPU_AFFINITY"] = "1" + return cmd, current_env + + +def prepare_multi_gpu_env(args: argparse.Namespace) -> Dict[str, str]: + """ + Prepares and returns an environment with the correct multi-GPU environment variables. + """ + num_processes = args.num_processes + num_machines = args.num_machines + main_process_ip = args.main_process_ip + main_process_port = args.main_process_port + if num_machines > 1: + args.nproc_per_node = str(num_processes // num_machines) + args.nnodes = str(num_machines) + args.node_rank = int(args.machine_rank) + if getattr(args, "same_network", False): + args.master_addr = str(main_process_ip) + args.master_port = str(main_process_port) + else: + args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}" + else: + args.nproc_per_node = str(num_processes) + if main_process_port is not None: + args.master_port = str(main_process_port) + + if main_process_port is None: + main_process_port = 29500 + + # only need to check port availability in main process, in case we have to start multiple launchers on the same machine + # for some reasons like splitting log files. + need_port_check = num_machines <= 1 or int(args.machine_rank) == 0 + if need_port_check and is_port_in_use(main_process_port): + raise ConnectionError( + f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. " + "Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)" + " and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`." + ) + + if args.module and args.no_python: + raise ValueError("--module and --no_python cannot be used together") + elif args.module: + args.module = True + elif args.no_python: + args.no_python = True + + current_env = os.environ.copy() + if args.debug: + current_env["ACCELERATE_DEBUG_MODE"] = "true" + gpu_ids = getattr(args, "gpu_ids", "all") + if gpu_ids != "all" and args.gpu_ids is not None: + if is_xpu_available(): + current_env["ZE_AFFINITY_MASK"] = gpu_ids + elif is_mlu_available(): + current_env["MLU_VISIBLE_DEVICES"] = gpu_ids + elif is_musa_available(): + current_env["MUSA_VISIBLE_DEVICES"] = gpu_ids + elif is_npu_available(): + current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids + else: + current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids + mixed_precision = args.mixed_precision.lower() + try: + mixed_precision = PrecisionType(mixed_precision) + except ValueError: + raise ValueError(f"Unknown mixed_precision mode: {mixed_precision}. Choose between {PrecisionType.list()}.") + + current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) + if args.mixed_precision.lower() == "fp8": + if not is_fp8_available(): + raise RuntimeError( + "FP8 is not available on this machine. Please ensure that either Transformer Engine or MSAMP is installed." + ) + current_env = setup_fp8_env(args, current_env) + + try: + dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) + except ValueError: + raise ValueError( + f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." + ) + current_env["ACCELERATE_DYNAMO_BACKEND"] = dynamo_backend.value + current_env["ACCELERATE_DYNAMO_MODE"] = args.dynamo_mode + current_env["ACCELERATE_DYNAMO_USE_FULLGRAPH"] = str(args.dynamo_use_fullgraph) + current_env["ACCELERATE_DYNAMO_USE_DYNAMIC"] = str(args.dynamo_use_dynamic) + + if args.use_fsdp: + current_env["ACCELERATE_USE_FSDP"] = "true" + if args.fsdp_cpu_ram_efficient_loading and not args.fsdp_sync_module_states: + raise ValueError("When using `--fsdp_cpu_ram_efficient_loading` set `--fsdp_sync_module_states` to `True`") + + current_env["FSDP_SHARDING_STRATEGY"] = str(args.fsdp_sharding_strategy) + current_env["FSDP_OFFLOAD_PARAMS"] = str(args.fsdp_offload_params).lower() + current_env["FSDP_MIN_NUM_PARAMS"] = str(args.fsdp_min_num_params) + if args.fsdp_auto_wrap_policy is not None: + current_env["FSDP_AUTO_WRAP_POLICY"] = str(args.fsdp_auto_wrap_policy) + if args.fsdp_transformer_layer_cls_to_wrap is not None: + current_env["FSDP_TRANSFORMER_CLS_TO_WRAP"] = str(args.fsdp_transformer_layer_cls_to_wrap) + if args.fsdp_backward_prefetch_policy is not None: + warnings.warn( + "`fsdp_backward_prefetch_policy` is deprecated and will be removed in version 0.27.0 of 🤗 Accelerate. Use" + " `fsdp_backward_prefetch` instead", + FutureWarning, + ) + args.fsdp_backward_prefetch = args.fsdp_backward_prefetch_policy + if args.fsdp_backward_prefetch is not None: + current_env["FSDP_BACKWARD_PREFETCH"] = str(args.fsdp_backward_prefetch) + if args.fsdp_state_dict_type is not None: + current_env["FSDP_STATE_DICT_TYPE"] = str(args.fsdp_state_dict_type) + current_env["FSDP_FORWARD_PREFETCH"] = str(args.fsdp_forward_prefetch).lower() + current_env["FSDP_USE_ORIG_PARAMS"] = str(args.fsdp_use_orig_params).lower() + current_env["FSDP_CPU_RAM_EFFICIENT_LOADING"] = str(args.fsdp_cpu_ram_efficient_loading).lower() + current_env["FSDP_SYNC_MODULE_STATES"] = str(args.fsdp_sync_module_states).lower() + current_env["FSDP_ACTIVATION_CHECKPOINTING"] = str(args.fsdp_activation_checkpointing).lower() + + if args.use_megatron_lm: + prefix = "MEGATRON_LM_" + current_env["ACCELERATE_USE_MEGATRON_LM"] = "true" + current_env[prefix + "TP_DEGREE"] = str(args.megatron_lm_tp_degree) + current_env[prefix + "PP_DEGREE"] = str(args.megatron_lm_pp_degree) + current_env[prefix + "GRADIENT_CLIPPING"] = str(args.megatron_lm_gradient_clipping) + if args.megatron_lm_num_micro_batches is not None: + current_env[prefix + "NUM_MICRO_BATCHES"] = str(args.megatron_lm_num_micro_batches) + if args.megatron_lm_sequence_parallelism is not None: + current_env[prefix + "SEQUENCE_PARALLELISM"] = str(args.megatron_lm_sequence_parallelism) + if args.megatron_lm_recompute_activations is not None: + current_env[prefix + "RECOMPUTE_ACTIVATIONS"] = str(args.megatron_lm_recompute_activations) + if args.megatron_lm_use_distributed_optimizer is not None: + current_env[prefix + "USE_DISTRIBUTED_OPTIMIZER"] = str(args.megatron_lm_use_distributed_optimizer) + + current_env["OMP_NUM_THREADS"] = str(args.num_cpu_threads_per_process) + if args.enable_cpu_affinity: + current_env["ACCELERATE_CPU_AFFINITY"] = "1" + return current_env + + +def prepare_deepspeed_cmd_env(args: argparse.Namespace) -> Tuple[List[str], Dict[str, str]]: + """ + Prepares and returns the command list and an environment with the correct DeepSpeed environment variables. + """ + num_processes = args.num_processes + num_machines = args.num_machines + main_process_ip = args.main_process_ip + main_process_port = args.main_process_port + cmd = None + + # make sure launcher is not None + if args.deepspeed_multinode_launcher is None: + # set to default pdsh + args.deepspeed_multinode_launcher = DEEPSPEED_MULTINODE_LAUNCHERS[0] + + if num_machines > 1 and args.deepspeed_multinode_launcher != DEEPSPEED_MULTINODE_LAUNCHERS[1]: + cmd = ["deepspeed", "--no_local_rank"] + cmd.extend(["--hostfile", str(args.deepspeed_hostfile), "--launcher", str(args.deepspeed_multinode_launcher)]) + if args.deepspeed_exclusion_filter is not None: + cmd.extend( + [ + "--exclude", + str(args.deepspeed_exclusion_filter), + ] + ) + elif args.deepspeed_inclusion_filter is not None: + cmd.extend( + [ + "--include", + str(args.deepspeed_inclusion_filter), + ] + ) + else: + cmd.extend(["--num_gpus", str(args.num_processes // args.num_machines)]) + if main_process_ip: + cmd.extend(["--master_addr", str(main_process_ip)]) + cmd.extend(["--master_port", str(main_process_port)]) + if args.module and args.no_python: + raise ValueError("--module and --no_python cannot be used together") + elif args.module: + cmd.append("--module") + elif args.no_python: + cmd.append("--no_python") + cmd.append(args.training_script) + cmd.extend(args.training_script_args) + elif num_machines > 1 and args.deepspeed_multinode_launcher == DEEPSPEED_MULTINODE_LAUNCHERS[1]: + args.nproc_per_node = str(num_processes // num_machines) + args.nnodes = str(num_machines) + args.node_rank = int(args.machine_rank) + if getattr(args, "same_network", False): + args.master_addr = str(main_process_ip) + args.master_port = str(main_process_port) + else: + args.rdzv_endpoint = f"{main_process_ip}:{main_process_port}" + else: + args.nproc_per_node = str(num_processes) + if main_process_port is not None: + args.master_port = str(main_process_port) + + if main_process_port is None: + main_process_port = 29500 + + # only need to check port availability in main process, in case we have to start multiple launchers on the same machine + # for some reasons like splitting log files. + need_port_check = num_machines <= 1 or int(args.machine_rank) == 0 + if need_port_check and is_port_in_use(main_process_port): + raise ConnectionError( + f"Tried to launch distributed communication on port `{main_process_port}`, but another process is utilizing it. " + "Please specify a different port (such as using the `--main_process_port` flag or specifying a different `main_process_port` in your config file)" + " and rerun your script. To automatically use the next open port (on a single node), you can set this to `0`." + ) + + if args.module and args.no_python: + raise ValueError("--module and --no_python cannot be used together") + elif args.module: + args.module = True + elif args.no_python: + args.no_python = True + + current_env = os.environ.copy() + if args.debug: + current_env["ACCELERATE_DEBUG_MODE"] = "true" + gpu_ids = getattr(args, "gpu_ids", "all") + if gpu_ids != "all" and args.gpu_ids is not None: + if is_xpu_available(): + current_env["ZE_AFFINITY_MASK"] = gpu_ids + elif is_mlu_available(): + current_env["MLU_VISIBLE_DEVICES"] = gpu_ids + elif is_musa_available(): + current_env["MUSA_VISIBLE_DEVICES"] = gpu_ids + elif is_npu_available(): + current_env["ASCEND_RT_VISIBLE_DEVICES"] = gpu_ids + else: + current_env["CUDA_VISIBLE_DEVICES"] = gpu_ids + try: + mixed_precision = PrecisionType(args.mixed_precision.lower()) + except ValueError: + raise ValueError( + f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." + ) + + current_env["PYTHONPATH"] = env_var_path_add("PYTHONPATH", os.path.abspath(".")) + current_env["ACCELERATE_MIXED_PRECISION"] = str(mixed_precision) + if args.mixed_precision.lower() == "fp8": + if not is_fp8_available(): + raise RuntimeError( + "FP8 is not available on this machine. Please ensure that either Transformer Engine or MSAMP is installed." + ) + current_env = setup_fp8_env(args, current_env) + current_env["ACCELERATE_CONFIG_DS_FIELDS"] = str(args.deepspeed_fields_from_accelerate_config).lower() + current_env["ACCELERATE_USE_DEEPSPEED"] = "true" + if args.zero_stage is not None: + current_env["ACCELERATE_DEEPSPEED_ZERO_STAGE"] = str(args.zero_stage) + if args.gradient_accumulation_steps is not None: + current_env["ACCELERATE_GRADIENT_ACCUMULATION_STEPS"] = str(args.gradient_accumulation_steps) + if args.gradient_clipping is not None: + current_env["ACCELERATE_GRADIENT_CLIPPING"] = str(args.gradient_clipping).lower() + if args.offload_optimizer_device is not None: + current_env["ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE"] = str(args.offload_optimizer_device).lower() + if args.offload_param_device is not None: + current_env["ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE"] = str(args.offload_param_device).lower() + if args.zero3_init_flag is not None: + current_env["ACCELERATE_DEEPSPEED_ZERO3_INIT"] = str(args.zero3_init_flag).lower() + if args.zero3_save_16bit_model is not None: + current_env["ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL"] = str(args.zero3_save_16bit_model).lower() + if args.deepspeed_config_file is not None: + current_env["ACCELERATE_DEEPSPEED_CONFIG_FILE"] = str(args.deepspeed_config_file) + if args.enable_cpu_affinity: + current_env["ACCELERATE_CPU_AFFINITY"] = "1" + if args.deepspeed_moe_layer_cls_names is not None: + current_env["ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMES"] = str(args.deepspeed_moe_layer_cls_names) + return cmd, current_env + + +def prepare_tpu( + args: argparse.Namespace, current_env: Dict[str, str], pod: bool = False +) -> Tuple[argparse.Namespace, Dict[str, str]]: + """ + Prepares and returns an environment with the correct TPU environment variables. + """ + if args.mixed_precision == "bf16" and is_torch_xla_available(check_is_tpu=True): + if args.downcast_bf16: + current_env["XLA_DOWNCAST_BF16"] = "1" + else: + current_env["XLA_USE_BF16"] = "1" + if args.debug: + current_env["ACCELERATE_DEBUG_MODE"] = "true" + if pod: + # Take explicit args and set them up for XLA + args.vm = args.tpu_vm + args.tpu = args.tpu_name + return args, current_env + + +def _convert_nargs_to_dict(nargs: List[str]) -> Dict[str, str]: + if len(nargs) < 0: + return {} + # helper function to infer type for argsparser + + def _infer_type(s): + try: + s = float(s) + + if s // 1 == s: + return int(s) + return s + except ValueError: + return s + + parser = argparse.ArgumentParser() + _, unknown = parser.parse_known_args(nargs) + for index, argument in enumerate(unknown): + if argument.startswith(("-", "--")): + action = None + if index + 1 < len(unknown): # checks if next index would be in list + if unknown[index + 1].startswith(("-", "--")): # checks if next element is an key + # raise an error if element is store_true or store_false + raise ValueError( + "SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types" + ) + else: # raise an error if last element is store_true or store_false + raise ValueError( + "SageMaker doesn’t support argparse actions for `store_true` or `store_false`. Please define explicit types" + ) + # adds argument to parser based on action_store true + if action is None: + parser.add_argument(argument, type=_infer_type) + else: + parser.add_argument(argument, action=action) + + return { + key: (literal_eval(value) if value in ("True", "False") else value) + for key, value in parser.parse_args(nargs).__dict__.items() + } + + +def prepare_sagemager_args_inputs( + sagemaker_config: SageMakerConfig, args: argparse.Namespace +) -> Tuple[argparse.Namespace, Dict[str, Any]]: + # configure environment + print("Configuring Amazon SageMaker environment") + os.environ["AWS_DEFAULT_REGION"] = sagemaker_config.region + + # configure credentials + if sagemaker_config.profile is not None: + os.environ["AWS_PROFILE"] = sagemaker_config.profile + elif args.aws_access_key_id is not None and args.aws_secret_access_key is not None: + os.environ["AWS_ACCESS_KEY_ID"] = args.aws_access_key_id + os.environ["AWS_SECRET_ACCESS_KEY"] = args.aws_secret_access_key + else: + raise OSError("You need to provide an aws_access_key_id and aws_secret_access_key when not using aws_profile") + + # extract needed arguments + source_dir = os.path.dirname(args.training_script) + if not source_dir: # checks if string is empty + source_dir = "." + entry_point = os.path.basename(args.training_script) + if not entry_point.endswith(".py"): + raise ValueError(f'Your training script should be a python script and not "{entry_point}"') + + print("Converting Arguments to Hyperparameters") + hyperparameters = _convert_nargs_to_dict(args.training_script_args) + + try: + mixed_precision = PrecisionType(args.mixed_precision.lower()) + except ValueError: + raise ValueError( + f"Unknown mixed_precision mode: {args.mixed_precision.lower()}. Choose between {PrecisionType.list()}." + ) + + try: + dynamo_backend = DynamoBackend(args.dynamo_backend.upper()) + except ValueError: + raise ValueError( + f"Unknown dynamo backend: {args.dynamo_backend.upper()}. Choose between {DynamoBackend.list()}." + ) + + # Environment variables to be set for use during training job + environment = { + "ACCELERATE_USE_SAGEMAKER": "true", + "ACCELERATE_MIXED_PRECISION": str(mixed_precision), + "ACCELERATE_DYNAMO_BACKEND": dynamo_backend.value, + "ACCELERATE_DYNAMO_MODE": args.dynamo_mode, + "ACCELERATE_DYNAMO_USE_FULLGRAPH": str(args.dynamo_use_fullgraph), + "ACCELERATE_DYNAMO_USE_DYNAMIC": str(args.dynamo_use_dynamic), + "ACCELERATE_SAGEMAKER_DISTRIBUTED_TYPE": sagemaker_config.distributed_type.value, + } + if args.mixed_precision.lower() == "fp8": + if not is_fp8_available(): + raise RuntimeError( + "FP8 is not available on this machine. Please ensure that either Transformer Engine or MSAMP is installed." + ) + environment = setup_fp8_env(args, environment) + # configure distribution set up + distribution = None + if sagemaker_config.distributed_type == SageMakerDistributedType.DATA_PARALLEL: + distribution = {"smdistributed": {"dataparallel": {"enabled": True}}} + + # configure sagemaker inputs + sagemaker_inputs = None + if sagemaker_config.sagemaker_inputs_file is not None: + print(f"Loading SageMaker Inputs from {sagemaker_config.sagemaker_inputs_file} file") + sagemaker_inputs = {} + with open(sagemaker_config.sagemaker_inputs_file) as file: + for i, line in enumerate(file): + if i == 0: + continue + l = line.split("\t") + sagemaker_inputs[l[0]] = l[1].strip() + print(f"Loaded SageMaker Inputs: {sagemaker_inputs}") + + # configure sagemaker metrics + sagemaker_metrics = None + if sagemaker_config.sagemaker_metrics_file is not None: + print(f"Loading SageMaker Metrics from {sagemaker_config.sagemaker_metrics_file} file") + sagemaker_metrics = [] + with open(sagemaker_config.sagemaker_metrics_file) as file: + for i, line in enumerate(file): + if i == 0: + continue + l = line.split("\t") + metric_dict = { + "Name": l[0], + "Regex": l[1].strip(), + } + sagemaker_metrics.append(metric_dict) + print(f"Loaded SageMaker Metrics: {sagemaker_metrics}") + + # configure session + print("Creating Estimator") + args = { + "image_uri": sagemaker_config.image_uri, + "entry_point": entry_point, + "source_dir": source_dir, + "role": sagemaker_config.iam_role_name, + "transformers_version": sagemaker_config.transformers_version, + "pytorch_version": sagemaker_config.pytorch_version, + "py_version": sagemaker_config.py_version, + "base_job_name": sagemaker_config.base_job_name, + "instance_count": sagemaker_config.num_machines, + "instance_type": sagemaker_config.ec2_instance_type, + "debugger_hook_config": False, + "distribution": distribution, + "hyperparameters": hyperparameters, + "environment": environment, + "metric_definitions": sagemaker_metrics, + } + + if sagemaker_config.additional_args is not None: + args = merge_dicts(sagemaker_config.additional_args, args) + return args, sagemaker_inputs + + +def env_var_path_add(env_var_name, path_to_add): + """ + Extends a path-based environment variable's value with a new path and returns the updated value. It's up to the + caller to set it in os.environ. + """ + paths = [p for p in os.environ.get(env_var_name, "").split(":") if len(p) > 0] + paths.append(str(path_to_add)) + return ":".join(paths) + + +class PrepareForLaunch: + """ + Prepare a function that will launched in a distributed setup. + + Args: + launcher (`Callable`): + The function to launch. + distributed_type ([`~state.DistributedType`]): + The distributed type to prepare for. + debug (`bool`, *optional*, defaults to `False`): + Whether or not this is a debug launch. + """ + + def __init__(self, launcher, distributed_type="NO", debug=False): + self.launcher = launcher + self.distributed_type = DistributedType(distributed_type) + self.debug = debug + + def __call__(self, index, *args): + if self.debug: + world_size = int(os.environ.get("WORLD_SIZE")) + rdv_file = os.environ.get("ACCELERATE_DEBUG_RDV_FILE") + torch.distributed.init_process_group( + "gloo", + rank=index, + store=torch.distributed.FileStore(rdv_file, world_size), + world_size=world_size, + ) + elif self.distributed_type in ( + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.MULTI_CPU, + ): + # Prepare the environment for torch.distributed + os.environ["LOCAL_RANK"] = str(index) + nproc = int(os.environ.get("NPROC", 1)) + node_rank = int(os.environ.get("NODE_RANK", 0)) + os.environ["RANK"] = str(nproc * node_rank + index) + + os.environ["FORK_LAUNCHED"] = str(1) + self.launcher(*args) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/megatron_lm.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/megatron_lm.py new file mode 100644 index 0000000000000000000000000000000000000000..552cb6d35f2a525c9ccde81f6c4e775705d4467f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/megatron_lm.py @@ -0,0 +1,1425 @@ +# 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. + +import argparse +import math +import os +from abc import ABC +from functools import partial + +import torch +import torch.nn.functional as F +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss +from torch.nn.parallel.distributed import DistributedDataParallel as torchDDP + +from ..optimizer import AcceleratedOptimizer +from ..scheduler import AcceleratedScheduler +from .imports import is_megatron_lm_available +from .operations import recursively_apply, send_to_device + + +if is_megatron_lm_available(): + from megatron import ( + get_args, + get_num_microbatches, + get_tensorboard_writer, + get_tokenizer, + print_rank_last, + ) + from megatron.arguments import ( + _add_data_args, + _add_validation_args, + core_transformer_config_from_args, + parse_args, + validate_args, + ) + from megatron.checkpointing import load_args_from_checkpoint, load_checkpoint, save_checkpoint + from megatron.core import mpu, tensor_parallel + from megatron.core.distributed import DistributedDataParallel as LocalDDP + from megatron.core.distributed import finalize_model_grads + from megatron.core.enums import ModelType + from megatron.core.parallel_state import get_tensor_model_parallel_group, get_tensor_model_parallel_src_rank + from megatron.core.pipeline_parallel import get_forward_backward_func + from megatron.core.utils import get_model_config + from megatron.data.dataset_utils import build_train_valid_test_datasets + from megatron.global_vars import set_global_variables + from megatron.initialize import ( + _compile_dependencies, + _init_autoresume, + _initialize_distributed, + _set_random_seed, + set_jit_fusion_options, + write_args_to_tensorboard, + ) + from megatron.model import BertModel, Float16Module, GPTModel, T5Model + from megatron.model.classification import Classification + from megatron.optimizer import get_megatron_optimizer + from megatron.text_generation.communication import broadcast_int_list, broadcast_tensor + from megatron.text_generation.generation import ( + beam_search_and_return_on_first_stage, + generate_tokens_probs_and_return_on_first_stage, + ) + from megatron.tokenizer.tokenizer import _vocab_size_with_padding + from megatron.training import ( + build_train_valid_test_data_iterators, + get_optimizer_param_scheduler, + num_floating_point_operations, + setup_model_and_optimizer, + train_step, + training_log, + ) + from megatron.utils import ( + average_losses_across_data_parallel_group, + calc_params_l2_norm, + get_ltor_masks_and_position_ids, + unwrap_model, + ) + + +# model utilities +def model_provider_func(pre_process=True, post_process=True, add_encoder=True, add_decoder=True): + """Build the model.""" + args = get_args() + mode = "pre-training" if args.pretraining_flag else "fine-tuning" + if args.rank == 0: + print(f"Building {args.model_type_name} model in the {mode} mode.") + print( + "The Megatron LM model weights are initialized at random in `accelerator.prepare`. " + "Please use `accelerator.load_checkpoint` to load a pre-trained checkpoint matching the distributed setup." + ) + config = core_transformer_config_from_args(args) + if args.model_type_name == "bert": + if args.pretraining_flag: + num_tokentypes = 2 if args.bert_binary_head else 0 + model = BertModel( + config=config, + num_tokentypes=num_tokentypes, + add_binary_head=args.bert_binary_head, + parallel_output=True, + pre_process=pre_process, + post_process=post_process, + ) + else: + model = Classification( + config=config, + num_classes=args.num_labels, + num_tokentypes=2, + pre_process=pre_process, + post_process=post_process, + ) + elif args.model_type_name == "gpt": + model = GPTModel( + config=config, + num_tokentypes=0, + parallel_output=True, + pre_process=pre_process, + post_process=post_process, + ) + elif args.model_type_name == "t5": + model = T5Model( + config=config, + num_tokentypes=0, + parallel_output=True, + pre_process=pre_process, + post_process=post_process, + add_encoder=add_encoder, + add_decoder=add_decoder, + ) + else: + raise ValueError(f"Unsupported model type: {args.model_type_name}") + return model + + +def prepare_model_optimizer_scheduler(accelerator): + accelerator.print("Preparing model optimizer scheduler") + args = get_args() + if accelerator.state.megatron_lm_plugin.custom_prepare_model_function is not None: + if accelerator.state.megatron_lm_plugin.custom_model_provider_function is None: + raise ValueError( + "You must provide a `custom_model_provider_function` when using a `custom_prepare_model_function`." + ) + custom_model_provider_func = accelerator.state.megatron_lm_plugin.custom_model_provider_function + model = accelerator.state.megatron_lm_plugin.custom_prepare_model_function(custom_model_provider_func) + optimizer = prepare_optimizer(accelerator, model) + scheduler = prepare_scheduler(accelerator, optimizer, scheduler=None) + else: + model_type = ModelType.encoder_or_decoder + if args.model_type_name == "t5": + model_type = ModelType.encoder_and_decoder + model_provider_func_ = model_provider_func + if accelerator.state.megatron_lm_plugin.custom_model_provider_function is not None: + model_provider_func_ = accelerator.state.megatron_lm_plugin.custom_model_provider_function + (model, optimizer, scheduler) = setup_model_and_optimizer( + model_provider_func_, + model_type, + no_wd_decay_cond=args.no_wd_decay_cond, + scale_lr_cond=args.scale_lr_cond, + lr_mult=args.lr_mult, + ) + args.model_len = len(model) + return model, optimizer, scheduler + + +# dataloader utilities +class MegatronLMDummyDataLoader: + """ + Dummy dataloader presents model parameters or param groups, this is primarily used to follow conventional training + + Args: + **dataset_kwargs: Megatron data arguments. + """ + + def __init__(self, **dataset_kwargs): + parser = argparse.ArgumentParser() + parser = _add_data_args(parser) + parser = _add_validation_args(parser) + data_args = parser.parse_known_args() + self.dataset_args = vars(data_args[0]) + self.dataset_args.update(dataset_kwargs) + self.dataset_args["megatron_dataset_flag"] = True + + def set_megatron_data_args(self): + args = get_args() + for key, value in self.dataset_args.items(): + old_value = getattr(args, key, "") + if old_value != value: + print( + f"WARNING: MegatronLMDummyDataLoader overriding arguments for " + f"{key}:{old_value} with {key}:{value}" + ) + setattr(args, key, value) + + def get_train_valid_test_datasets_provider(self, accelerator): + def train_valid_test_datasets_provider(train_val_test_num_samples): + """Build train, valid, and test datasets.""" + args = get_args() + dataset_args = { + "data_prefix": args.data_path if isinstance(args.data_path, (list, tuple)) else [args.data_path], + "splits_string": args.split, + "train_valid_test_num_samples": train_val_test_num_samples, + "seed": args.seed, + } + if args.model_type_name == "bert": + dataset_args.update( + { + "max_seq_length": args.seq_length, + "binary_head": args.bert_binary_head, + } + ) + elif args.model_type_name == "gpt": + dataset_args.update( + { + "max_seq_length": args.seq_length, + } + ) + elif args.model_type_name == "t5": + dataset_args.update( + { + "max_seq_length": args.encoder_seq_length, + "max_seq_length_dec": args.decoder_seq_length, + "dataset_type": "t5", + } + ) + else: + raise ValueError(f"Unsupported model type: {args.model_type_name}") + train_ds, valid_ds, test_ds = build_train_valid_test_datasets(**dataset_args) + return train_ds, valid_ds, test_ds + + if accelerator.state.megatron_lm_plugin.custom_megatron_datasets_provider_function is not None: + return accelerator.state.megatron_lm_plugin.custom_megatron_datasets_provider_function + try: + args = get_args() + # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source + if args.model_type_name == "bert": + from pretrain_bert import train_valid_test_datasets_provider + + train_valid_test_datasets_provider.is_distributed = True + return train_valid_test_datasets_provider + elif args.model_type_name == "gpt": + from pretrain_gpt import train_valid_test_datasets_provider + + train_valid_test_datasets_provider.is_distributed = True + return train_valid_test_datasets_provider + elif args.model_type_name == "t5": + from pretrain_t5 import train_valid_test_datasets_provider + + train_valid_test_datasets_provider.is_distributed = True + return train_valid_test_datasets_provider + except ImportError: + pass + return train_valid_test_datasets_provider + + def build_train_valid_test_data_iterators(self, accelerator): + args = get_args() + + train_valid_test_dataset_provider = self.get_train_valid_test_datasets_provider(accelerator) + if args.virtual_pipeline_model_parallel_size is not None: + train_data_iterator = [] + valid_data_iterator = [] + test_data_iterator = [] + for i in range(getattr(args, "model_len", 0)): + mpu.set_virtual_pipeline_model_parallel_rank(i) + iterators = build_train_valid_test_data_iterators(train_valid_test_dataset_provider) + train_data_iterator.append(iterators[0]) + valid_data_iterator.append(iterators[1]) + test_data_iterator.append(iterators[2]) + else: + train_data_iterator, valid_data_iterator, test_data_iterator = build_train_valid_test_data_iterators( + train_valid_test_dataset_provider + ) + + return train_data_iterator, valid_data_iterator, test_data_iterator + + +def _handle_megatron_data_iterator(accelerator, data_iterator): + class DummyMegatronDataloader: + def __iter__(self): + return self + + def __next__(self): + return {} + + is_data_iterator_empty = data_iterator is None + is_src_data_iterator_empty = torch.tensor(is_data_iterator_empty, dtype=torch.bool, device=accelerator.device) + torch.distributed.broadcast( + is_src_data_iterator_empty, get_tensor_model_parallel_src_rank(), group=get_tensor_model_parallel_group() + ) + if not is_src_data_iterator_empty and is_data_iterator_empty: + return DummyMegatronDataloader() + return data_iterator + + +def prepare_data_loader(accelerator, dataloader): + accelerator.print("Preparing dataloader") + args = get_args() + if not args.megatron_dataset_flag: + from ..data_loader import _PYTORCH_DATALOADER_KWARGS, prepare_data_loader + + micro_batch_size = args.micro_batch_size * args.num_micro_batches + kwargs = {k: getattr(dataloader, k, _PYTORCH_DATALOADER_KWARGS[k]) for k in _PYTORCH_DATALOADER_KWARGS} + if kwargs["batch_size"] is None: + if isinstance(kwargs["sampler"], torch.utils.data.BatchSampler): + kwargs["sampler"].batch_size = micro_batch_size + else: + del kwargs["sampler"] + del kwargs["shuffle"] + del kwargs["batch_size"] + kwargs["batch_sampler"].batch_size = micro_batch_size + else: + del kwargs["batch_sampler"] + kwargs["batch_size"] = micro_batch_size + + dataloader = torch.utils.data.DataLoader(dataloader.dataset, **kwargs) + # split_batches: + # Megatron only needs to fetch different data between different dp groups, + # and does not need to split the data within the dp group. + return prepare_data_loader( + dataloader, + accelerator.device, + num_processes=mpu.get_data_parallel_world_size(), + process_index=mpu.get_data_parallel_rank(), + split_batches=False, + put_on_device=True, + rng_types=accelerator.rng_types.copy(), + dispatch_batches=accelerator.dispatch_batches, + ) + else: + if args.consumed_samples is not None: + ( + args.consumed_train_samples, + args.consumed_valid_samples, + args.consumed_test_samples, + ) = args.consumed_samples + else: + args.consumed_train_samples, args.consumed_valid_samples, args.consumed_test_samples = 0, 0, 0 + args.micro_batch_size = args.micro_batch_size * args.num_micro_batches + # In order to be compatible with data in transform format, + # it needs to increase the size of mbs first, + # and then split the large batch data into some mbs. + ( + train_data_iterator, + valid_data_iterator, + test_data_iterator, + ) = dataloader.build_train_valid_test_data_iterators(accelerator) + args.micro_batch_size = args.micro_batch_size // args.num_micro_batches + + train_data_iterator = _handle_megatron_data_iterator( + accelerator=accelerator, data_iterator=train_data_iterator + ) + valid_data_iterator = _handle_megatron_data_iterator( + accelerator=accelerator, data_iterator=valid_data_iterator + ) + test_data_iterator = _handle_megatron_data_iterator(accelerator=accelerator, data_iterator=test_data_iterator) + + return train_data_iterator, valid_data_iterator, test_data_iterator + + +# optimizer utilities +class MegatronLMOptimizerWrapper(AcceleratedOptimizer): + def __init__(self, optimizer): + super().__init__(optimizer, device_placement=False, scaler=None) + + def zero_grad(self, set_to_none=None): + pass # `model(**batch)` is doing that automatically. Therefore, it's implementation is not needed + + def step(self): + pass # `model(**batch)` is doing that automatically. Therefore, it's implementation is not needed + + @property + def step_was_skipped(self): + """Whether or not the optimizer step was done, or skipped because of gradient overflow.""" + return self.optimizer.skipped_iter + + +def prepare_optimizer(accelerator, model): + accelerator.print("Preparing optimizer") + args = get_args() + return get_megatron_optimizer(model, args.no_wd_decay_cond, args.scale_lr_cond, args.lr_mult) + + +# scheduler utilities +class MegatronLMDummyScheduler: + """ + Dummy scheduler presents model parameters or param groups, this is primarily used to follow conventional training + loop when scheduler config is specified in the deepspeed config file. + + Args: + optimizer (`torch.optim.optimizer.Optimizer`): + The optimizer to wrap. + total_num_steps (int): + Total number of steps. + warmup_num_steps (int): + Number of steps for warmup. + **kwargs (additional keyword arguments, *optional*): + Other arguments. + """ + + def __init__(self, optimizer, total_num_steps=None, warmup_num_steps=0, **kwargs): + self.optimizer = optimizer + self.total_num_steps = total_num_steps + self.warmup_num_steps = warmup_num_steps + self.kwargs = kwargs + + +class MegatronLMSchedulerWrapper(AcceleratedScheduler): + def __init__(self, scheduler, optimizers): + super().__init__(scheduler, optimizers) + + def step(self, *args, **kwargs): + return # `model(**batch)` is doing that automatically. Therefore, it's implementation is not needed + + +def prepare_scheduler(accelerator, optimizer, scheduler): + accelerator.print("Preparing scheduler") + scheduler = get_optimizer_param_scheduler(optimizer) + return scheduler + + +class AbstractTrainStep(ABC): + """Abstract class for batching, forward pass and loss handler.""" + + def __init__(self, name): + super().__init__() + self.name = name + + def get_batch_func(self, accelerator, megatron_dataset_flag): + pass + + def get_forward_step_func(self): + pass + + def get_loss_func(self, accelerator): + pass + + +class BertTrainStep(AbstractTrainStep): + """ + Bert train step class. + + Args: + args (`argparse.Namespace`): Megatron-LM arguments. + """ + + def __init__(self, accelerator, args): + super().__init__("BertTrainStep") + self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag) + self.loss_func = self.get_loss_func(accelerator, args.pretraining_flag, args.num_labels) + self.forward_step = self.get_forward_step_func(args.pretraining_flag, args.bert_binary_head) + if not args.model_return_dict: + self.model_output_class = None + else: + from transformers.modeling_outputs import SequenceClassifierOutput + + self.model_output_class = SequenceClassifierOutput + + def get_batch_func(self, accelerator, megatron_dataset_flag): + def get_batch_megatron(data_iterator): + """Build the batch.""" + + # Items and their type. + keys = ["text", "types", "labels", "is_random", "loss_mask", "padding_mask"] + datatype = torch.int64 + + # Broadcast data. + if data_iterator is not None: + data = next(data_iterator) + else: + data = None + data_b = tensor_parallel.broadcast_data(keys, data, datatype) + + # Unpack. + tokens = data_b["text"].long() + types = data_b["types"].long() + sentence_order = data_b["is_random"].long() + loss_mask = data_b["loss_mask"].float() + lm_labels = data_b["labels"].long() + padding_mask = data_b["padding_mask"].long() + + return tokens, types, sentence_order, loss_mask, lm_labels, padding_mask + + def get_batch_transformer(data_iterator): + """Build the batch.""" + data = next(data_iterator) + data = send_to_device(data, torch.cuda.current_device()) + + # Unpack. + tokens = data["input_ids"].long() + padding_mask = data["attention_mask"].long() + if "token_type_ids" in data: + types = data["token_type_ids"].long() + else: + types = None + if "labels" in data: + lm_labels = data["labels"].long() + loss_mask = (data["labels"] != -100).to(torch.float) + else: + lm_labels = None + loss_mask = None + if "next_sentence_label" in data: + sentence_order = data["next_sentence_label"].long() + else: + sentence_order = None + + return tokens, types, sentence_order, loss_mask, lm_labels, padding_mask + + if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None: + return accelerator.state.megatron_lm_plugin.custom_get_batch_function + if megatron_dataset_flag: + try: + # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source + from pretrain_bert import get_batch + + return get_batch + except ImportError: + pass + return get_batch_megatron + else: + return get_batch_transformer + + def get_loss_func(self, accelerator, pretraining_flag, num_labels): + def loss_func_pretrain(loss_mask, sentence_order, output_tensor): + lm_loss_, sop_logits = output_tensor + + lm_loss_ = lm_loss_.float() + loss_mask = loss_mask.float() + lm_loss = torch.sum(lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum() + + if sop_logits is not None: + sop_loss = F.cross_entropy(sop_logits.view(-1, 2).float(), sentence_order.view(-1), ignore_index=-1) + sop_loss = sop_loss.float() + loss = lm_loss + sop_loss + averaged_losses = average_losses_across_data_parallel_group([lm_loss, sop_loss]) + return loss, {"lm loss": averaged_losses[0], "sop loss": averaged_losses[1]} + + else: + loss = lm_loss + averaged_losses = average_losses_across_data_parallel_group([lm_loss]) + return loss, {"lm loss": averaged_losses[0]} + + def loss_func_finetune(labels, logits): + if num_labels == 1: + # We are doing regression + loss_fct = MSELoss() + loss = loss_fct(logits.view(-1), labels.view(-1)) + elif self.num_labels > 1 and (labels.dtype in (torch.long, torch.int)): + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, num_labels), labels.view(-1)) + else: + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(logits, labels) + averaged_losses = average_losses_across_data_parallel_group([loss]) + return loss, {"loss": averaged_losses[0]} + + if accelerator.state.megatron_lm_plugin.custom_loss_function is not None: + return accelerator.state.megatron_lm_plugin.custom_loss_function + if pretraining_flag: + return loss_func_pretrain + else: + return loss_func_finetune + + def get_forward_step_func(self, pretraining_flag, bert_binary_head): + def forward_step(data_iterator, model): + """Forward step.""" + tokens, types, sentence_order, loss_mask, labels, padding_mask = self.get_batch(data_iterator) + if not bert_binary_head: + types = None + # Forward pass through the model. + if pretraining_flag: + output_tensor = model(tokens, padding_mask, tokentype_ids=types, lm_labels=labels) + return output_tensor, partial(self.loss_func, loss_mask, sentence_order) + else: + logits = model(tokens, padding_mask, tokentype_ids=types) + return logits, partial(self.loss_func, labels) + + return forward_step + + +class GPTTrainStep(AbstractTrainStep): + """ + GPT train step class. + + Args: + args (`argparse.Namespace`): Megatron-LM arguments. + """ + + def __init__(self, accelerator, args): + super().__init__("GPTTrainStep") + self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag) + self.loss_func = self.get_loss_func(accelerator) + self.forward_step = self.get_forward_step_func() + self.eod_token = args.padded_vocab_size - 1 + if args.vocab_file is not None: + tokenizer = get_tokenizer() + self.eod_token = tokenizer.eod + self.reset_position_ids = args.reset_position_ids + self.reset_attention_mask = args.reset_attention_mask + self.eod_mask_loss = args.eod_mask_loss + if not args.model_return_dict: + self.model_output_class = None + else: + from transformers.modeling_outputs import CausalLMOutputWithCrossAttentions + + self.model_output_class = CausalLMOutputWithCrossAttentions + + def get_batch_func(self, accelerator, megatron_dataset_flag): + def get_batch_megatron(data_iterator): + """Generate a batch""" + # Items and their type. + keys = ["text"] + datatype = torch.int64 + + # Broadcast data. + if data_iterator is not None: + data = next(data_iterator) + else: + data = None + data_b = tensor_parallel.broadcast_data(keys, data, datatype) + + # Unpack. + tokens_ = data_b["text"].long() + labels = tokens_[:, 1:].contiguous() + tokens = tokens_[:, :-1].contiguous() + + # Get the masks and postition ids. + attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids( + tokens, self.eod_token, self.reset_position_ids, self.reset_attention_mask, self.eod_mask_loss + ) + + return tokens, labels, loss_mask, attention_mask, position_ids + + def get_batch_transformer(data_iterator): + data = next(data_iterator) + data = {"input_ids": data["input_ids"]} + data = send_to_device(data, torch.cuda.current_device()) + + tokens_ = data["input_ids"].long() + padding = torch.zeros((tokens_.shape[0], 1), dtype=tokens_.dtype, device=tokens_.device) + self.eod_token + tokens_ = torch.concat([tokens_, padding], dim=1) + labels = tokens_[:, 1:].contiguous() + tokens = tokens_[:, :-1].contiguous() + # Get the masks and postition ids. + attention_mask, loss_mask, position_ids = get_ltor_masks_and_position_ids( + tokens, self.eod_token, self.reset_position_ids, self.reset_attention_mask, True + ) + return tokens, labels, loss_mask, attention_mask, position_ids + + if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None: + return accelerator.state.megatron_lm_plugin.custom_get_batch_function + if megatron_dataset_flag: + try: + # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source + from pretrain_gpt import get_batch + + return get_batch + except ImportError: + pass + return get_batch_megatron + else: + return get_batch_transformer + + def get_loss_func(self, accelerator): + args = get_args() + + def loss_func(loss_mask, output_tensor): + if args.return_logits: + losses, logits = output_tensor + else: + losses = output_tensor + losses = losses.float() + loss_mask = loss_mask.view(-1).float() + if args.context_parallel_size > 1: + loss = torch.cat([torch.sum(losses.view(-1) * loss_mask).view(1), loss_mask.sum().view(1)]) + torch.distributed.all_reduce(loss, group=mpu.get_context_parallel_group()) + loss = loss[0] / loss[1] + else: + loss = torch.sum(losses.view(-1) * loss_mask) / loss_mask.sum() + + # Check individual rank losses are not NaN prior to DP all-reduce. + if args.check_for_nan_in_loss_and_grad: + global_rank = torch.distributed.get_rank() + assert not loss.isnan(), ( + f"Rank {global_rank}: found NaN in local forward loss calculation. " + f"Device: {torch.cuda.current_device()}, node: {os.uname()[1]}" + ) + + # Reduce loss for logging. + averaged_loss = average_losses_across_data_parallel_group([loss]) + + output_dict = {"lm loss": averaged_loss[0]} + if args.return_logits: + output_dict.update({"logits": logits}) + return loss, output_dict + + if accelerator.state.megatron_lm_plugin.custom_loss_function is not None: + return accelerator.state.megatron_lm_plugin.custom_loss_function + return loss_func + + def get_forward_step_func(self): + def forward_step(data_iterator, model): + """Forward step.""" + # Get the batch. + tokens, labels, loss_mask, attention_mask, position_ids = self.get_batch(data_iterator) + output_tensor = model(tokens, position_ids, attention_mask, labels=labels) + + return output_tensor, partial(self.loss_func, loss_mask) + + return forward_step + + +class T5TrainStep(AbstractTrainStep): + """ + T5 train step class. + + Args: + args (`argparse.Namespace`): Megatron-LM arguments. + """ + + def __init__(self, accelerator, args): + super().__init__("T5TrainStep") + self.get_batch = self.get_batch_func(accelerator, args.megatron_dataset_flag) + self.loss_func = self.get_loss_func(accelerator) + self.forward_step = self.get_forward_step_func() + if not args.model_return_dict: + self.model_output_class = None + else: + from transformers.modeling_outputs import Seq2SeqLMOutput + + self.model_output_class = Seq2SeqLMOutput + + @staticmethod + def attn_mask_postprocess(attention_mask): + # We create a 3D attention mask from a 2D tensor mask. + # [b, 1, s] + attention_mask_b1s = attention_mask.unsqueeze(1) + # [b, s, 1] + attention_mask_bs1 = attention_mask.unsqueeze(2) + # [b, s, s] + attention_mask_bss = attention_mask_b1s * attention_mask_bs1 + # Convert attention mask to binary: + extended_attention_mask = attention_mask_bss < 0.5 + return extended_attention_mask + + @staticmethod + def get_decoder_mask(seq_length, device): + attention_mask = torch.tril(torch.ones((1, seq_length, seq_length), device=device)) + attention_mask = attention_mask < 0.5 + return attention_mask + + @staticmethod + def get_enc_dec_mask(attention_mask, dec_seq_length, device): + batch_size, _ = attention_mask.shape + # We create a 3D attention mask from a 2D tensor mask. + # [b, 1, s] + attention_mask_b1s = attention_mask.unsqueeze(1) + # [b, s, 1] + attention_mask_bs1 = torch.ones((batch_size, dec_seq_length, 1), device=device) + attention_mask_bss = attention_mask_bs1 * attention_mask_b1s + extended_attention_mask = attention_mask_bss < 0.5 + return extended_attention_mask + + def get_batch_func(self, accelerator, megatron_dataset_flag): + def get_batch_megatron(data_iterator): + """Build the batch.""" + + keys = ["text_enc", "text_dec", "labels", "loss_mask", "enc_mask", "dec_mask", "enc_dec_mask"] + datatype = torch.int64 + + # Broadcast data. + if data_iterator is not None: + data = next(data_iterator) + else: + data = None + data_b = tensor_parallel.broadcast_data(keys, data, datatype) + + # Unpack. + tokens_enc = data_b["text_enc"].long() + tokens_dec = data_b["text_dec"].long() + labels = data_b["labels"].long() + loss_mask = data_b["loss_mask"].float() + + enc_mask = data_b["enc_mask"] < 0.5 + dec_mask = data_b["dec_mask"] < 0.5 + enc_dec_mask = data_b["enc_dec_mask"] < 0.5 + + return tokens_enc, tokens_dec, loss_mask, labels, enc_mask, dec_mask, enc_dec_mask + + def get_batch_transformer(data_iterator): + """Build the batch.""" + data = next(data_iterator) + data = send_to_device(data, torch.cuda.current_device()) + + tokens_enc = data["input_ids"].long() + labels = data["labels"].long() + loss_mask = (labels != -100).to(torch.float) + if "decoder_input_ids" in data: + tokens_dec = data["decoder_input_ids"].long() + else: + tokens_dec = labels.new_zeros(labels.shape, device=labels.device, dtype=torch.long) + tokens_dec[..., 1:] = labels[..., :-1].clone() + tokens_dec[..., 0] = 0 + tokens_dec.masked_fill_(tokens_dec == -100, 0) + enc_mask = T5TrainStep.attn_mask_postprocess(data["attention_mask"].long()) + dec_mask = T5TrainStep.get_decoder_mask(tokens_dec.shape[1], tokens_dec.device) + enc_dec_mask = T5TrainStep.get_enc_dec_mask( + data["attention_mask"].long(), tokens_dec.shape[1], tokens_dec.device + ) + + return tokens_enc, tokens_dec, loss_mask, labels, enc_mask, dec_mask, enc_dec_mask + + if accelerator.state.megatron_lm_plugin.custom_get_batch_function is not None: + return accelerator.state.megatron_lm_plugin.custom_get_batch_function + if megatron_dataset_flag: + try: + # Use '--no-use-pep517 -e' to pip install nvidia's megatron from source + from pretrain_t5 import get_batch + + return get_batch + except ImportError: + pass + return get_batch_megatron + else: + return get_batch_transformer + + def get_loss_func(self, accelerator): + def loss_func(loss_mask, output_tensor): + lm_loss_ = output_tensor.float() + lm_loss = torch.sum(lm_loss_.view(-1) * loss_mask.reshape(-1)) / loss_mask.sum() + + loss = lm_loss + averaged_losses = average_losses_across_data_parallel_group([lm_loss]) + + return loss, {"lm loss": averaged_losses[0]} + + if accelerator.state.megatron_lm_plugin.custom_loss_function is not None: + return accelerator.state.megatron_lm_plugin.custom_loss_function + return loss_func + + def get_forward_step_func(self): + def forward_step(data_iterator, model): + """Forward step.""" + # Get the batch. + tokens_enc, tokens_dec, loss_mask, lm_labels, enc_mask, dec_mask, enc_dec_mask = self.get_batch( + data_iterator + ) + # Forward model lm_labels + output_tensor = model( + tokens_enc, tokens_dec, enc_mask, dec_mask, enc_dec_mask, tokentype_ids=None, lm_labels=lm_labels + ) + + return output_tensor, partial(self.loss_func, loss_mask) + + return forward_step + + +def finish_mpu_init(): + # torch.distributed initialization + args = get_args() + # Pytorch distributed. + _initialize_distributed() + + # Random seeds for reproducibility. + if args.rank == 0: + print(f"> setting random seeds to {args.seed} ...") + _set_random_seed(args.seed, args.data_parallel_random_init) + + +# intialize megatron setup +def initialize(accelerator, extra_args_provider=None, args_defaults={}): + accelerator.print("Initializing Megatron-LM") + assert torch.cuda.is_available(), "Megatron requires CUDA." + + # Parse arguments + args = parse_args(extra_args_provider, ignore_unknown_args=True) + + # Set defaults + for key, value in args_defaults.items(): + if getattr(args, key, None) is not None: + if args.rank == 0: + print( + f"WARNING: overriding default arguments for " f"{key}:{getattr(args, key)} with {key}:{value}", + flush=True, + ) + setattr(args, key, value) + + if args.use_checkpoint_args or args_defaults.get("use_checkpoint_args", False): + assert args.load is not None, "--use-checkpoints-args requires --load argument" + load_args_from_checkpoint(args) + + validate_args(args) + + # set global args, build tokenizer, and set adlr-autoresume, + # tensorboard-writer, and timers. + set_global_variables(args) + + # Megatron's MPU is the master. Complete initialization right away. + finish_mpu_init() + + # Autoresume. + _init_autoresume() + + # Compile dependencies. + _compile_dependencies() + + # Set pytorch JIT layer fusion options and warmup JIT functions. + set_jit_fusion_options() + args = get_args() + if getattr(args, "padded_vocab_size", None) is None: + args.padded_vocab_size = _vocab_size_with_padding(args.orig_vocab_size, args) + if args.model_type_name == "bert" and args.pretraining_flag and args.num_labels == 2: + args.bert_binary_head = True + else: + args.bert_binary_head = False + args.iteration = 0 + + +class MegatronEngine(torch.nn.Module): + """ + Megatron-LM model wrapper + + Args: + accelerator (:class:`~accelerate.Accelerator`): The accelerator object to use. + model: Megatron-LM model + optimizer: Megatron-LM optimizer + lr_scheduler: Megatron-LM lr scheduler + """ + + def __init__(self, accelerator, model, optimizer, scheduler): + super().__init__() + self.module = model + self.base_model = model[0] + self.optimizer = optimizer + self.scheduler = scheduler + args = get_args() + if accelerator.state.megatron_lm_plugin.custom_train_step_class is not None: + self.train_step_handler = accelerator.state.megatron_lm_plugin.custom_train_step_class( + args, **accelerator.state.megatron_lm_plugin.custom_train_step_kwargs + ) + elif args.model_type_name == "bert": + self.train_step_handler = BertTrainStep(accelerator, args) + elif args.model_type_name == "gpt": + self.train_step_handler = GPTTrainStep(accelerator, args) + elif args.model_type_name == "t5": + self.train_step_handler = T5TrainStep(accelerator, args) + else: + raise ValueError(f"Unsupported model type: {args.model_type_name}") + self.optimizer.skipped_iter = False + + # Tracking loss. + self.total_loss_dict = {} + self.eval_total_loss_dict = {} + self.iteration = 0 + self.report_memory_flag = True + self.num_floating_point_operations_so_far = 0 + self.module_config = None + if args.tensorboard_dir is not None: + write_args_to_tensorboard() + + def get_module_config(self): + args = get_args() + config = get_model_config(self.module[0]) + # Setup some training config params + config.grad_scale_func = self.optimizer.scale_loss + if isinstance(self.module[0], LocalDDP) and args.overlap_grad_reduce: + assert config.no_sync_func is None, ( + "When overlap_grad_reduce is True, config.no_sync_func must be None; " + "a custom no_sync_func is not supported when overlapping grad-reduce" + ) + config.no_sync_func = [model_chunk.no_sync for model_chunk in self.module] + if len(self.module) == 1: + config.no_sync_func = config.no_sync_func[0] + if args.delay_grad_reduce: + config.grad_sync_func = [model_chunk.start_grad_sync for model_chunk in self.module] + if len(self.module) == 1: + config.grad_sync_func = config.grad_sync_func[0] + if args.overlap_param_gather and args.delay_param_gather: + config.param_sync_func = [ + lambda x: self.optimizer.finish_param_sync(model_index, x) for model_index in range(len(self.module)) + ] + if len(self.module) == 1: + config.param_sync_func = config.param_sync_func[0] + config.finalize_model_grads_func = finalize_model_grads + return config + + def train(self): + for model_module in self.module: + model_module.train() + + if self.module_config is None: + self.module_config = self.get_module_config() + + self.log_eval_results() + + def eval(self): + for model_module in self.module: + model_module.eval() + + if self.module_config is None: + self.module_config = self.get_module_config() + + def get_batch_data_iterator(self, batch_data): + args = get_args() + data_chunks = [] + if len(batch_data) > 0: + if args.num_micro_batches > 1: + for i in range(0, args.num_micro_batches): + data_chunks.append( + { + k: v[i * args.micro_batch_size : (i + 1) * args.micro_batch_size] + for k, v in batch_data.items() + } + ) + else: + data_chunks = [batch_data] + + if len(self.module) > 1: + batch_data_iterator = ( + [iter(data_chunks) for _ in range(len(self.module))] + if len(batch_data) > 0 + else [None] * len(self.module) + ) + else: + batch_data_iterator = iter(data_chunks) if len(batch_data) > 0 else None + return batch_data_iterator + + def train_step(self, **batch_data): + """ + Training step for Megatron-LM + + Args: + batch_data (:obj:`dict`): The batch data to train on. + """ + + batch_data_iterator = self.get_batch_data_iterator(batch_data) + + loss_reduced, skipped_iter, grad_norm, num_zeros_in_grad = train_step( + forward_step_func=self.train_step_handler.forward_step, + data_iterator=batch_data_iterator, + model=self.module, + optimizer=self.optimizer, + opt_param_scheduler=self.scheduler, + config=self.module_config, + ) + + self.optimizer.skipped_iter = skipped_iter == 1 + + return loss_reduced, skipped_iter, grad_norm, num_zeros_in_grad + + def eval_step(self, **batch_data): + """ + Evaluation step for Megatron-LM + + Args: + batch_data (:obj:`dict`): The batch data to evaluate on. + """ + + args = get_args() + batch_data_iterator = self.get_batch_data_iterator(batch_data) + forward_backward_func = get_forward_backward_func() + loss_dicts = forward_backward_func( + forward_step_func=self.train_step_handler.forward_step, + data_iterator=batch_data_iterator, + model=self.module, + num_microbatches=get_num_microbatches(), + seq_length=args.seq_length, + micro_batch_size=args.micro_batch_size, + forward_only=True, + ) + # Empty unused memory + if args.empty_unused_memory_level >= 1: + torch.cuda.empty_cache() + + args.consumed_valid_samples += ( + mpu.get_data_parallel_world_size() * args.micro_batch_size * get_num_microbatches() + ) + + if mpu.is_pipeline_last_stage(ignore_virtual=True): + # Average loss across microbatches. + loss_reduced = {} + for key in loss_dicts[0]: + losses_reduced_for_key = [x[key] for x in loss_dicts] + if len(losses_reduced_for_key[0].shape) == 0: + loss_reduced[key] = sum(losses_reduced_for_key) / len(losses_reduced_for_key) + else: + loss_reduced[key] = torch.concat(losses_reduced_for_key) + return loss_reduced + return {} + + def forward(self, **batch_data): + # During training, we use train_step() + # model(**batch_data) performs following operations by delegating it to `self.train_step`: + # 1. Prepare **batch_data for Tendor, Pipeline and Model Parallelism + # 2. Set grad to zero. + # 3. forward pass and backward pass using Pipeline Parallelism + # 4. Empty unused memory. + # 5. Reduce gradients. + # 6. Update parameters. + # 7. Gather params when using Distributed Optimizer (Data Parallelism). + # 8. Update learning rate if scheduler is specified. + # 9. Empty unused memory. + # 10. Average loss across microbatches and across DP ranks. + # + # During evaluation, we use eval_step() + args = get_args() + if self.module[0].training: + loss_dict, skipped_iter, grad_norm, num_zeros_in_grad = self.train_step(**batch_data) + self.iteration += 1 + batch_size = mpu.get_data_parallel_world_size() * args.micro_batch_size * get_num_microbatches() + args.consumed_train_samples += batch_size + self.num_floating_point_operations_so_far += num_floating_point_operations(args, batch_size) + if args.tensorboard_dir is not None: + # Logging. + loss_scale = self.optimizer.get_loss_scale().item() + params_norm = None + if args.log_params_norm: + params_norm = calc_params_l2_norm(self.model) + self.report_memory_flag = training_log( + loss_dict, + self.total_loss_dict, + self.optimizer.param_groups[0]["lr"], + self.iteration, + loss_scale, + self.report_memory_flag, + skipped_iter, + grad_norm, + params_norm, + num_zeros_in_grad, + ) + else: + loss_dict = self.eval_step(**batch_data) + if args.tensorboard_dir is not None: + for key in loss_dict: + self.eval_total_loss_dict[key] = ( + self.eval_total_loss_dict.get(key, torch.cuda.FloatTensor([0.0])) + loss_dict[key] + ) + self.eval_total_loss_dict[key + "_num_iters"] = self.eval_total_loss_dict.get( + key + "_num_iters", torch.cuda.FloatTensor([0.0]) + ) + torch.cuda.FloatTensor([1.0]) + + loss = torch.tensor(0.0, device=torch.cuda.current_device()) + for key in loss_dict: + if len(loss_dict[key].shape) == 0: + loss += loss_dict[key] + + logits = None + if "logits" in loss_dict: + logits = loss_dict["logits"] + if self.train_step_handler.model_output_class is not None: + return self.train_step_handler.model_output_class(loss=loss, logits=logits) + return loss + + def log_eval_results(self): + args = get_args() + if args.tensorboard_dir is None or self.iteration == 0: + return + args = get_args() + writer = get_tensorboard_writer() + string = f"validation loss at iteration {self.iteration} | " + for key in self.eval_total_loss_dict: + if key.endswith("_num_iters"): + continue + value = self.eval_total_loss_dict[key] / self.eval_total_loss_dict[key + "_num_iters"] + string += f"{key} value: {value} | " + ppl = math.exp(min(20, value.item())) + if args.pretraining_flag: + string += f"{key} PPL: {ppl} | " + if writer: + writer.add_scalar(f"{key} validation", value.item(), self.iteration) + if args.pretraining_flag: + writer.add_scalar(f"{key} validation ppl", ppl, self.iteration) + + length = len(string) + 1 + print_rank_last("-" * length) + print_rank_last(string) + print_rank_last("-" * length) + self.eval_total_loss_dict = {} + + def save_checkpoint(self, output_dir): + self.log_eval_results() + args = get_args() + args.save = output_dir + torch.distributed.barrier() + save_checkpoint( + self.iteration, + self.module, + self.optimizer, + self.scheduler, + num_floating_point_operations_so_far=self.num_floating_point_operations_so_far, + ) + torch.distributed.barrier() + + def load_checkpoint(self, input_dir): + args = get_args() + args.load = input_dir + args.consumed_train_samples = 0 + args.consumed_valid_samples = 0 + torch.distributed.barrier() + iteration, num_floating_point_operations_so_far = load_checkpoint(self.module, self.optimizer, self.scheduler) + torch.distributed.barrier() + self.iteration = iteration + self.num_floating_point_operations_so_far = num_floating_point_operations_so_far + if args.fp16 and self.iteration == 0: + self.optimizer.reload_model_params() + + def megatron_generate( + self, + inputs, + attention_mask=None, + max_length=None, + max_new_tokens=None, + num_beams=None, + temperature=None, + top_k=None, + top_p=None, + length_penalty=None, + **kwargs, + ): + """ + Generate method for GPT2 model. This method is used for inference. Supports both greedy and beam search along + with sampling. Refer the Megatron-LM repo for more details + + Args: + inputs (torch.Tensor): input ids + attention_mask (torch.Tensor, optional): attention mask. Defaults to None. + max_length (int, optional): max length of the generated sequence. Defaults to None. + Either this or max_new_tokens should be provided. + max_new_tokens (int, optional): max number of tokens to be generated. Defaults to None. + Either this or max_length should be provided. + num_beams (int, optional): number of beams to use for beam search. Defaults to None. + temperature (float, optional): temperature for sampling. Defaults to 1.0. + top_k (int, optional): top k tokens to consider for sampling. Defaults to 0.0. + top_p (float, optional): tokens in top p probability are considered for sampling. Defaults to 0.0. + length_penalty (float, optional): length penalty for beam search. Defaults to None. + kwargs: additional key-value arguments + """ + + # checking if required arguments are passed + args = get_args() + if args.model_type_name != "gpt": + raise NotImplementedError("Generate method is not implemented for this model") + + if args.data_parallel_size > 1: + raise ValueError("Generate method requires data parallelism to be 1") + + if args.sequence_parallel: + raise ValueError("Generate method requires sequence parallelism to be False") + + if args.recompute_granularity is not None: + raise ValueError("Checkpoint activations cannot be set for inference") + + if args.vocab_file is None: + raise ValueError("Vocab file is required for inference") + + # Prepare inputs + if max_length is None and max_new_tokens is None: + raise ValueError("`max_length` or `max_new_tokens` are required for inference") + + if temperature is None: + temperature = 1.0 + elif not (0.0 < temperature <= 100.0): + raise ValueError("temperature must be a positive number less than or equal to 100.0") + + if top_k is None: + top_k = 0 + elif not (0 <= top_k <= 1000): + raise ValueError("top_k must be a positive number less than or equal to 1000") + + if top_p is None: + top_p = 0.0 + elif top_p > 0.0 and top_k > 0.0: + raise ValueError("top_p and top_k sampling cannot be set together") + else: + if not (0.0 <= top_p <= 1.0): + raise ValueError("top_p must be less than or equal to 1.0") + + top_p_decay = kwargs.get("top_p_decay", 0.0) + if not (0.0 <= top_p_decay <= 1.0): + raise ValueError("top_p_decay must be less than or equal to 1.0") + + top_p_bound = kwargs.get("top_p_bound", 0.0) + if not (0.0 <= top_p_bound <= 1.0): + raise ValueError("top_p_bound must be less than or equal to 1.0") + + add_BOS = kwargs.get("add_BOS", False) + if not (isinstance(add_BOS, bool)): + raise ValueError("add_BOS must be a boolean") + + beam_width = num_beams + if beam_width is not None: + if not isinstance(beam_width, int): + raise ValueError("beam_width must be an integer") + if beam_width < 1: + raise ValueError("beam_width must be greater than 0") + if inputs.shape[0] > 1: + return "When doing beam_search, batch size must be 1" + + tokenizer = get_tokenizer() + + stop_token = kwargs.get("stop_token", tokenizer.eod) + if stop_token is not None: + if not isinstance(stop_token, int): + raise ValueError("stop_token must be an integer") + + if length_penalty is None: + length_penalty = 1.0 + + sizes_list = None + prompts_tokens_tensor = None + prompts_length_tensor = None + if torch.distributed.get_rank() == 0: + # Get the prompts length. + if attention_mask is None: + prompts_length_tensor = torch.cuda.LongTensor([inputs.shape[1]] * inputs.shape[0]) + else: + prompts_length_tensor = attention_mask.sum(axis=-1).cuda() + + if max_new_tokens is None: + max_new_tokens = max_length - inputs.shape[1] + if max_new_tokens <= 0: + raise ValueError("max_new_tokens must be greater than 0") + + if add_BOS: + max_length = max_new_tokens + inputs.shape[1] + 1 + # making sure that `max_length` is a multiple of 4 to leverage fused kernels + max_length = 4 * math.ceil(max_length / 4) + max_new_tokens = max_length - (inputs.shape[1] + 1) + padding = torch.cuda.LongTensor([[tokenizer.eod] * max_new_tokens] * inputs.shape[0]) + prompts_tokens_tensor = torch.concat( + [torch.unsqueeze(padding[:, 0], axis=-1), inputs.cuda(), padding], axis=-1 + ) + else: + # making sure that `max_length` is a multiple of 4 to leverage fused kernels + max_length = max_new_tokens + inputs.shape[1] + max_length = 4 * math.ceil(max_length / 4) + max_new_tokens = max_length - inputs.shape[1] + padding = torch.cuda.LongTensor([[tokenizer.eod] * max_new_tokens] * inputs.shape[0]) + prompts_tokens_tensor = torch.concat([inputs.cuda(), padding], axis=-1) + + # We need the sizes of these tensors for the boradcast + sizes_list = [ + prompts_tokens_tensor.size(0), # Batch size + prompts_tokens_tensor.size(1), + ] # Sequence lenght + + # First, broadcast the sizes. + sizes_tensor = broadcast_int_list(2, int_list=sizes_list, rank=0) + + # Now that we have the sizes, we can boradcast the tokens + # and length tensors. + sizes = sizes_tensor.tolist() + context_tokens_tensor = broadcast_tensor(sizes, torch.int64, tensor=prompts_tokens_tensor, rank=0) + context_length_tensor = broadcast_tensor(sizes[0], torch.int64, tensor=prompts_length_tensor, rank=0) + + # Run the inference + random_seed = kwargs.get("random_seed", 0) + torch.random.manual_seed(random_seed) + unwrapped_model = unwrap_model(self.base_model, (torchDDP, LocalDDP, Float16Module)) + if beam_width is not None: + tokens, _ = beam_search_and_return_on_first_stage( + unwrapped_model, + context_tokens_tensor, + context_length_tensor, + beam_width, + stop_token=stop_token, + num_return_gen=1, + length_penalty=length_penalty, + ) + else: + tokens, _, _ = generate_tokens_probs_and_return_on_first_stage( + unwrapped_model, + context_tokens_tensor, + context_length_tensor, + return_output_log_probs=False, + top_k=top_k, + top_p=top_p, + top_p_decay=top_p_decay, + top_p_bound=top_p_bound, + temperature=temperature, + use_eod_token_for_early_termination=True, + ) + return tokens + + +# other utilities +def avg_losses_across_data_parallel_group(losses): + """ + Average losses across data parallel group. + + Args: + losses (List[Tensor]): List of losses to average across data parallel group. + """ + + return average_losses_across_data_parallel_group(losses) + + +def gather_across_data_parallel_groups(tensor): + """ + Recursively gather tensor in a nested list/tuple/dictionary of tensors from data parallel ranks. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather across data parallel ranks. + + """ + + def _gpu_gather_one(tensor): + if tensor.ndim == 0: + tensor = tensor.clone()[None] + output_tensors = [ + torch.empty_like(tensor) + for _ in range(torch.distributed.get_world_size(group=mpu.get_data_parallel_group())) + ] + torch.distributed.all_gather(output_tensors, tensor, group=mpu.get_data_parallel_group()) + return torch.cat(output_tensors, dim=0) + + return recursively_apply(_gpu_gather_one, tensor, error_on_other_type=True) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/memory.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/memory.py new file mode 100644 index 0000000000000000000000000000000000000000..baa5377f6a5cc07bd24489e43a34d086fd4f35f5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/memory.py @@ -0,0 +1,161 @@ +# 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. + +""" +A collection of utilities for ensuring that training can always occur. Heavily influenced by the +[toma](https://github.com/BlackHC/toma) library. +""" + +import functools +import gc +import inspect + +import torch + +from .imports import ( + is_cuda_available, + is_mlu_available, + is_mps_available, + is_musa_available, + is_npu_available, + is_xpu_available, +) + + +def clear_device_cache(garbage_collection=False): + """ + Clears the device cache by calling `torch.{backend}.empty_cache`. Can also run `gc.collect()`, but do note that + this is a *considerable* slowdown and should be used sparingly. + """ + if garbage_collection: + gc.collect() + + if is_xpu_available(): + torch.xpu.empty_cache() + elif is_mlu_available(): + torch.mlu.empty_cache() + elif is_musa_available(): + torch.musa.empty_cache() + elif is_npu_available(): + torch.npu.empty_cache() + elif is_mps_available(min_version="2.0"): + torch.mps.empty_cache() + elif is_cuda_available(): + torch.cuda.empty_cache() + + +def release_memory(*objects): + """ + Releases memory from `objects` by setting them to `None` and calls `gc.collect()` and `torch.cuda.empty_cache()`. + Returned objects should be reassigned to the same variables. + + Args: + objects (`Iterable`): + An iterable of objects + Returns: + A list of `None` objects to replace `objects` + + Example: + + ```python + >>> import torch + >>> from accelerate.utils import release_memory + + >>> a = torch.ones(1000, 1000).cuda() + >>> b = torch.ones(1000, 1000).cuda() + >>> a, b = release_memory(a, b) + ``` + """ + if not isinstance(objects, list): + objects = list(objects) + for i in range(len(objects)): + objects[i] = None + clear_device_cache(garbage_collection=True) + return objects + + +def should_reduce_batch_size(exception: Exception) -> bool: + """ + Checks if `exception` relates to CUDA out-of-memory, CUDNN not supported, or CPU out-of-memory + + Args: + exception (`Exception`): + An exception + """ + _statements = [ + "CUDA out of memory.", # CUDA OOM + "cuDNN error: CUDNN_STATUS_NOT_SUPPORTED.", # CUDNN SNAFU + "DefaultCPUAllocator: can't allocate memory", # CPU OOM + ] + if isinstance(exception, RuntimeError) and len(exception.args) == 1: + return any(err in exception.args[0] for err in _statements) + return False + + +def find_executable_batch_size(function: callable = None, starting_batch_size: int = 128): + """ + A basic decorator that will try to execute `function`. If it fails from exceptions related to out-of-memory or + CUDNN, the batch size is cut in half and passed to `function` + + `function` must take in a `batch_size` parameter as its first argument. + + Args: + function (`callable`, *optional*): + A function to wrap + starting_batch_size (`int`, *optional*): + The batch size to try and fit into memory + + Example: + + ```python + >>> from accelerate.utils import find_executable_batch_size + + + >>> @find_executable_batch_size(starting_batch_size=128) + ... def train(batch_size, model, optimizer): + ... ... + + + >>> train(model, optimizer) + ``` + """ + if function is None: + return functools.partial(find_executable_batch_size, starting_batch_size=starting_batch_size) + + batch_size = starting_batch_size + + def decorator(*args, **kwargs): + nonlocal batch_size + clear_device_cache(garbage_collection=True) + params = list(inspect.signature(function).parameters.keys()) + # Guard against user error + if len(params) < (len(args) + 1): + arg_str = ", ".join([f"{arg}={value}" for arg, value in zip(params[1:], args[1:])]) + raise TypeError( + f"Batch size was passed into `{function.__name__}` as the first argument when called." + f"Remove this as the decorator already does so: `{function.__name__}({arg_str})`" + ) + while True: + if batch_size == 0: + raise RuntimeError("No executable batch size found, reached zero.") + try: + return function(batch_size, *args, **kwargs) + except Exception as e: + if should_reduce_batch_size(e): + clear_device_cache(garbage_collection=True) + batch_size //= 2 + else: + raise + + return decorator diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/modeling.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/modeling.py new file mode 100644 index 0000000000000000000000000000000000000000..bd562236162255b66fff76e47555fd66f6f4f43c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/modeling.py @@ -0,0 +1,1945 @@ +# 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. + +import contextlib +import gc +import inspect +import json +import logging +import os +import re +import shutil +import tempfile +import warnings +from collections import OrderedDict, defaultdict +from typing import Dict, List, Optional, Set, Tuple, Union + +import torch +import torch.nn as nn + +from ..state import AcceleratorState +from .constants import SAFE_WEIGHTS_NAME, WEIGHTS_NAME +from .dataclasses import AutocastKwargs, CustomDtype, DistributedType +from .imports import ( + is_mlu_available, + is_mps_available, + is_musa_available, + is_npu_available, + is_peft_available, + is_torch_xla_available, + is_xpu_available, +) +from .memory import clear_device_cache +from .offload import load_offloaded_weight, offload_weight, save_offload_index +from .tqdm import is_tqdm_available, tqdm +from .versions import compare_versions, is_torch_version + + +if is_npu_available(check_device=False): + import torch_npu # noqa: F401 + +if is_mlu_available(check_device=False): + import torch_mlu # noqa: F401 + +if is_musa_available(check_device=False): + import torch_musa # noqa: F401 + +from safetensors import safe_open +from safetensors.torch import load_file as safe_load_file + + +WEIGHTS_INDEX_NAME = "pytorch_model.bin.index.json" + +logger = logging.getLogger(__name__) + + +def is_peft_model(model): + from .other import extract_model_from_parallel + + if is_peft_available(): + from peft import PeftModel + + return is_peft_available() and isinstance(extract_model_from_parallel(model), PeftModel) + + +def check_device_same(first_device, second_device): + """ + Utility method to check if two `torch` devices are similar. When dealing with CUDA devices, torch throws `False` + for `torch.device("cuda") == torch.device("cuda:0")` whereas they should be the same + + Args: + first_device (`torch.device`): + First device to check + second_device (`torch.device`): + Second device to check + """ + if first_device.type != second_device.type: + return False + + if first_device.type == "cuda" and first_device.index is None: + # In case the first_device is a cuda device and have + # the index attribute set to `None`, default it to `0` + first_device = torch.device("cuda", index=0) + + if second_device.type == "cuda" and second_device.index is None: + # In case the second_device is a cuda device and have + # the index attribute set to `None`, default it to `0` + second_device = torch.device("cuda", index=0) + + return first_device == second_device + + +def convert_file_size_to_int(size: Union[int, str]): + """ + Converts a size expressed as a string with digits an unit (like `"5MB"`) to an integer (in bytes). + + Args: + size (`int` or `str`): The size to convert. Will be directly returned if an `int`. + + Example: + + ```py + >>> convert_file_size_to_int("1MiB") + 1048576 + ``` + """ + mem_size = -1 + err_msg = ( + f"`size` {size} is not in a valid format. Use an integer for bytes, or a string with an unit (like '5.0GB')." + ) + try: + if isinstance(size, int): + mem_size = size + elif size.upper().endswith("GIB"): + mem_size = int(float(size[:-3]) * (2**30)) + elif size.upper().endswith("MIB"): + mem_size = int(float(size[:-3]) * (2**20)) + elif size.upper().endswith("KIB"): + mem_size = int(float(size[:-3]) * (2**10)) + elif size.upper().endswith("GB"): + int_size = int(float(size[:-2]) * (10**9)) + mem_size = int_size // 8 if size.endswith("b") else int_size + elif size.upper().endswith("MB"): + int_size = int(float(size[:-2]) * (10**6)) + mem_size = int_size // 8 if size.endswith("b") else int_size + elif size.upper().endswith("KB"): + int_size = int(float(size[:-2]) * (10**3)) + mem_size = int_size // 8 if size.endswith("b") else int_size + except ValueError: + raise ValueError(err_msg) + + if mem_size < 0: + raise ValueError(err_msg) + return mem_size + + +def dtype_byte_size(dtype: torch.dtype): + """ + Returns the size (in bytes) occupied by one parameter of type `dtype`. + + Example: + + ```py + >>> dtype_byte_size(torch.float32) + 4 + ``` + """ + if dtype == torch.bool: + return 1 / 8 + elif dtype == CustomDtype.INT2: + return 1 / 4 + elif dtype == CustomDtype.INT4: + return 1 / 2 + elif dtype == CustomDtype.FP8: + return 1 + elif is_torch_version(">=", "2.1.0") and dtype == torch.float8_e4m3fn: + return 1 + bit_search = re.search(r"[^\d](\d+)$", str(dtype)) + if bit_search is None: + raise ValueError(f"`dtype` is not a valid dtype: {dtype}.") + bit_size = int(bit_search.groups()[0]) + return bit_size // 8 + + +def id_tensor_storage(tensor: torch.Tensor) -> Tuple[torch.device, int, int]: + """ + Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For + example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is + guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with + non-overlapping lifetimes may have the same id. + """ + _SIZE = { + torch.int64: 8, + torch.float32: 4, + torch.int32: 4, + torch.bfloat16: 2, + torch.float16: 2, + torch.int16: 2, + torch.uint8: 1, + torch.int8: 1, + torch.bool: 1, + torch.float64: 8, + } + try: + storage_ptr = tensor.untyped_storage().data_ptr() + storage_size = tensor.untyped_storage().nbytes() + except Exception: + # Fallback for torch==1.10 + try: + storage_ptr = tensor.storage().data_ptr() + storage_size = tensor.storage().size() * _SIZE[tensor.dtype] + except NotImplementedError: + # Fallback for meta storage + storage_ptr = 0 + # On torch >=2.0 this is the tensor size + storage_size = tensor.nelement() * _SIZE[tensor.dtype] + + return tensor.device, storage_ptr, storage_size + + +def shard_checkpoint( + state_dict: Dict[str, torch.Tensor], max_shard_size: Union[int, str] = "10GB", weights_name: str = WEIGHTS_NAME +): + """ + Splits a model state dictionary in sub-checkpoints so that the final size of each sub-checkpoint does not exceed a + given size. + + The sub-checkpoints are determined by iterating through the `state_dict` in the order of its keys, so there is no + optimization made to make each sub-checkpoint as close as possible to the maximum size passed. For example, if the + limit is 10GB and we have weights of sizes [6GB, 6GB, 2GB, 6GB, 2GB, 2GB] they will get sharded as [6GB], [6+2GB], + [6+2+2GB] and not [6+2+2GB], [6+2GB], [6GB]. + + + + If one of the model's weight is bigger that `max_sahrd_size`, it will end up in its own sub-checkpoint which will + have a size greater than `max_shard_size`. + + + + Args: + state_dict (`Dict[str, torch.Tensor]`): The state dictionary of a model to save. + max_shard_size (`int` or `str`, *optional*, defaults to `"10GB"`): + The maximum size of each sub-checkpoint. If expressed as a string, needs to be digits followed by a unit + (like `"5MB"`). + weights_name (`str`, *optional*, defaults to `"pytorch_model.bin"`): + The name of the model save file. + """ + logger.warning( + "Note that `shard_checkpoint` is deprecated and will be removed in 0.33.0. We recommend you using " + "split_torch_state_dict_into_shards from huggingface_hub library" + ) + + max_shard_size = convert_file_size_to_int(max_shard_size) + + sharded_state_dicts = [{}] + last_block_size = 0 + total_size = 0 + storage_id_to_block = {} + + for key, weight in state_dict.items(): + # when bnb serialization is used the weights in the state dict can be strings + # check: https://github.com/huggingface/transformers/pull/24416 for more details + if isinstance(weight, str): + continue + else: + storage_id = id_tensor_storage(weight) + + # If a `weight` shares the same underlying storage as another tensor, we put `weight` in the same `block` + if storage_id in storage_id_to_block: + block_id = storage_id_to_block[storage_id] + sharded_state_dicts[block_id][key] = weight + continue + + weight_size = weight.numel() * dtype_byte_size(weight.dtype) + + # If this weight is going to tip up over the maximal size, we split. + if last_block_size + weight_size > max_shard_size: + sharded_state_dicts.append({}) + last_block_size = 0 + + sharded_state_dicts[-1][key] = weight + last_block_size += weight_size + total_size += weight_size + storage_id_to_block[storage_id] = len(sharded_state_dicts) - 1 + + # If we only have one shard, we return it + if len(sharded_state_dicts) == 1: + return {weights_name: sharded_state_dicts[0]}, None + + # Otherwise, let's build the index + weight_map = {} + shards = {} + for idx, shard in enumerate(sharded_state_dicts): + shard_file = weights_name.replace(".bin", f"-{idx + 1:05d}-of-{len(sharded_state_dicts):05d}.bin") + shard_file = shard_file.replace( + ".safetensors", f"-{idx + 1:05d}-of-{len(sharded_state_dicts):05d}.safetensors" + ) + shards[shard_file] = shard + for key in shard.keys(): + weight_map[key] = shard_file + + # Add the metadata + metadata = {"total_size": total_size} + index = {"metadata": metadata, "weight_map": weight_map} + return shards, index + + +def set_module_tensor_to_device( + module: nn.Module, + tensor_name: str, + device: Union[int, str, torch.device], + value: Optional[torch.Tensor] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + fp16_statistics: Optional[torch.HalfTensor] = None, + tied_params_map: Optional[Dict[int, Dict[torch.device, torch.Tensor]]] = None, +): + """ + A helper function to set a given tensor (parameter of buffer) of a module on a specific device (note that doing + `param.to(device)` creates a new tensor not linked to the parameter, which is why we need this function). + + Args: + module (`torch.nn.Module`): + The module in which the tensor we want to move lives. + tensor_name (`str`): + The full name of the parameter/buffer. + device (`int`, `str` or `torch.device`): + The device on which to set the tensor. + value (`torch.Tensor`, *optional*): + The value of the tensor (useful when going from the meta device to any other device). + dtype (`torch.dtype`, *optional*): + If passed along the value of the parameter will be cast to this `dtype`. Otherwise, `value` will be cast to + the dtype of the existing parameter in the model. + fp16_statistics (`torch.HalfTensor`, *optional*): + The list of fp16 statistics to set on the module, used for 8 bit model serialization. + tied_params_map (Dict[int, Dict[torch.device, torch.Tensor]], *optional*, defaults to `None`): + A map of current data pointers to dictionaries of devices to already dispatched tied weights. For a given + execution device, this parameter is useful to reuse the first available pointer of a shared weight on the + device for all others, instead of duplicating memory. + """ + # Recurse if needed + if "." in tensor_name: + splits = tensor_name.split(".") + for split in splits[:-1]: + new_module = getattr(module, split) + if new_module is None: + raise ValueError(f"{module} has no attribute {split}.") + module = new_module + tensor_name = splits[-1] + + if tensor_name not in module._parameters and tensor_name not in module._buffers: + raise ValueError(f"{module} does not have a parameter or a buffer named {tensor_name}.") + is_buffer = tensor_name in module._buffers + old_value = getattr(module, tensor_name) + + # Treat the case where old_value (or a custom `value`, typically offloaded to RAM/disk) belongs to a tied group, and one of the weight + # in the tied group has already been dispatched to the device, by avoiding reallocating memory on the device and just copying the pointer. + if ( + value is not None + and tied_params_map is not None + and value.data_ptr() in tied_params_map + and device in tied_params_map[value.data_ptr()] + ): + module._parameters[tensor_name] = tied_params_map[value.data_ptr()][device] + return + elif ( + tied_params_map is not None + and old_value.data_ptr() in tied_params_map + and device in tied_params_map[old_value.data_ptr()] + ): + module._parameters[tensor_name] = tied_params_map[old_value.data_ptr()][device] + return + + if old_value.device == torch.device("meta") and device not in ["meta", torch.device("meta")] and value is None: + raise ValueError(f"{tensor_name} is on the meta device, we need a `value` to put in on {device}.") + + param = module._parameters[tensor_name] if tensor_name in module._parameters else None + param_cls = type(param) + + if value is not None: + # We can expect mismatches when using bnb 4bit since Params4bit will reshape and pack the weights. + # In other cases, we want to make sure we're not loading checkpoints that do not match the config. + if old_value.shape != value.shape and param_cls.__name__ != "Params4bit": + raise ValueError( + f'Trying to set a tensor of shape {value.shape} in "{tensor_name}" (which has shape {old_value.shape}), this looks incorrect.' + ) + + if dtype is None: + # For compatibility with PyTorch load_state_dict which converts state dict dtype to existing dtype in model + value = value.to(old_value.dtype) + elif not str(value.dtype).startswith(("torch.uint", "torch.int", "torch.bool")): + value = value.to(dtype) + + device_quantization = None + with torch.no_grad(): + # leave it on cpu first before moving them to cuda + # # fix the case where the device is meta, we don't want to put it on cpu because there is no data =0 + if ( + param is not None + and param.device.type != "cuda" + and torch.device(device).type == "cuda" + and param_cls.__name__ in ["Int8Params", "FP4Params", "Params4bit"] + ): + device_quantization = device + device = "cpu" + # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)). + if isinstance(device, int): + if is_npu_available(): + device = f"npu:{device}" + elif is_mlu_available(): + device = f"mlu:{device}" + elif is_musa_available(): + device = f"musa:{device}" + elif is_xpu_available(): + device = f"xpu:{device}" + if "xpu" in str(device) and not is_xpu_available(): + raise ValueError(f'{device} is not available, you should use device="cpu" instead') + if value is None: + new_value = old_value.to(device) + if dtype is not None and device in ["meta", torch.device("meta")]: + if not str(old_value.dtype).startswith(("torch.uint", "torch.int", "torch.bool")): + new_value = new_value.to(dtype) + + if not is_buffer: + module._parameters[tensor_name] = param_cls(new_value, requires_grad=old_value.requires_grad) + elif isinstance(value, torch.Tensor): + new_value = value.to(device) + else: + new_value = torch.tensor(value, device=device) + if device_quantization is not None: + device = device_quantization + if is_buffer: + module._buffers[tensor_name] = new_value + elif value is not None or not check_device_same(torch.device(device), module._parameters[tensor_name].device): + param_cls = type(module._parameters[tensor_name]) + kwargs = module._parameters[tensor_name].__dict__ + if param_cls.__name__ in ["Int8Params", "FP4Params", "Params4bit"]: + if param_cls.__name__ == "Int8Params" and new_value.dtype == torch.float32: + # downcast to fp16 if any - needed for 8bit serialization + new_value = new_value.to(torch.float16) + # quantize module that are going to stay on the cpu so that we offload quantized weights + if device == "cpu" and param_cls.__name__ == "Int8Params": + new_value = param_cls(new_value, requires_grad=old_value.requires_grad, **kwargs).to(0).to("cpu") + new_value.CB = new_value.CB.to("cpu") + new_value.SCB = new_value.SCB.to("cpu") + else: + new_value = param_cls(new_value, requires_grad=old_value.requires_grad, **kwargs).to(device) + elif param_cls.__name__ in ["QTensor", "QBitsTensor"]: + new_value = torch.nn.Parameter(new_value, requires_grad=old_value.requires_grad).to(device) + else: + new_value = param_cls(new_value, requires_grad=old_value.requires_grad).to(device) + + module._parameters[tensor_name] = new_value + if fp16_statistics is not None: + module._parameters[tensor_name].SCB = fp16_statistics.to(device) + del fp16_statistics + # as we put the weight to meta, it doesn't have SCB attr anymore. make sure that it is not a meta weight + if ( + module.__class__.__name__ == "Linear8bitLt" + and getattr(module.weight, "SCB", None) is None + and str(module.weight.device) != "meta" + ): + # quantize only if necessary + device_index = torch.device(device).index if torch.device(device).type == "cuda" else None + if not getattr(module.weight, "SCB", None) and device_index is not None: + if module.bias is not None and module.bias.device.type != "meta": + # if a bias exists, we need to wait until the bias is set on the correct device + module = module.cuda(device_index) + elif module.bias is None: + # if no bias exists, we can quantize right away + module = module.cuda(device_index) + elif ( + module.__class__.__name__ == "Linear4bit" + and getattr(module.weight, "quant_state", None) is None + and str(module.weight.device) != "meta" + ): + # quantize only if necessary + device_index = torch.device(device).index if torch.device(device).type == "cuda" else None + if not getattr(module.weight, "quant_state", None) and device_index is not None: + module.weight = module.weight.cuda(device_index) + # clean pre and post foward hook + if device != "cpu": + clear_device_cache() + + # When handling tied weights, we update tied_params_map to keep track of the tied weights that have already been allocated on the device in + # order to avoid duplicating memory, see above. + if ( + tied_params_map is not None + and old_value.data_ptr() in tied_params_map + and device not in tied_params_map[old_value.data_ptr()] + ): + tied_params_map[old_value.data_ptr()][device] = new_value + elif ( + value is not None + and tied_params_map is not None + and value.data_ptr() in tied_params_map + and device not in tied_params_map[value.data_ptr()] + ): + tied_params_map[value.data_ptr()][device] = new_value + + +def named_module_tensors( + module: nn.Module, include_buffers: bool = True, recurse: bool = False, remove_non_persistent: bool = False +): + """ + A helper function that gathers all the tensors (parameters + buffers) of a given module. If `include_buffers=True` + it's the same as doing `module.named_parameters(recurse=recurse) + module.named_buffers(recurse=recurse)`. + + Args: + module (`torch.nn.Module`): + The module we want the tensors on. + include_buffer (`bool`, *optional*, defaults to `True`): + Whether or not to include the buffers in the result. + recurse (`bool`, *optional`, defaults to `False`): + Whether or not to go look in every submodule or just return the direct parameters and buffers. + remove_non_persistent (`bool`, *optional*, defaults to `False`): + Whether or not to remove the non persistent buffer from the buffers. Useful only when include_buffers = + True + """ + yield from module.named_parameters(recurse=recurse) + + if include_buffers: + non_persistent_buffers = set() + if remove_non_persistent: + non_persistent_buffers = get_non_persistent_buffers(module, recurse=recurse) + for named_buffer in module.named_buffers(recurse=recurse): + name, _ = named_buffer + if name not in non_persistent_buffers: + yield named_buffer + + +def get_non_persistent_buffers(module: nn.Module, recurse: bool = False): + """ + Gather all non persistent buffers of a given modules into a set + + Args: + module (`nn.Module`): + The module we want the non persistent buffers on. + recurse (`bool`, *optional*, defaults to `False`): + Whether or not to go look in every submodule or just return the direct non persistent buffers. + """ + + non_persistent_buffers_set = module._non_persistent_buffers_set + if recurse: + for _, m in module.named_modules(): + non_persistent_buffers_set |= m._non_persistent_buffers_set + + return non_persistent_buffers_set + + +class FindTiedParametersResult(list): + """ + This is a subclass of a list to handle backward compatibility for Transformers. Do not rely on the fact this is not + a list or on the `values` method as in the future this will be removed. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + + def values(self): + # TODO: at the next Transformers release (4.28.0) issue a deprecation warning here. + return sum([x[1:] for x in self], []) + + +def check_tied_parameters_in_config(model: nn.Module): + """ + Check if there is any indication in the given model that some weights should be tied. + + Args: + model (`torch.nn.Module`): The model to inspect + + Returns: + bool: True if the model needs to have tied weights + """ + + # based on model.tie_weights() method + has_tied_word_embedding = False + has_tied_encoder_decoder = False + has_tied_module = False + + if "PreTrainedModel" in [c.__name__ for c in inspect.getmro(model.__class__)]: + has_tied_word_embedding = ( + hasattr(model, "config") + and getattr(model.config, "tie_word_embeddings", False) + and model.get_output_embeddings() + ) + has_tied_encoder_decoder = ( + hasattr(model, "config") + and getattr(model.config, "is_encoder_decoder", False) + and getattr(model.config, "tie_encoder_decoder", False) + ) + has_tied_module = any(hasattr(module, "_tie_weights") for module in model.modules()) + + return any([has_tied_word_embedding, has_tied_encoder_decoder, has_tied_module]) + + +def _get_param_device(param, device_map): + if param in device_map: + return device_map[param] + parent_param = ".".join(param.split(".")[:-1]) + if parent_param == param: + raise ValueError(f"The `device_map` does not contain the module {param}.") + else: + return _get_param_device(parent_param, device_map) + + +def check_tied_parameters_on_same_device(tied_params, device_map): + """ + Check if tied parameters are on the same device + + Args: + tied_params (`List[List[str]]`): + A list of lists of parameter names being all tied together. + + device_map (`Dict[str, Union[int, str, torch.device]]`): + A map that specifies where each submodule should go. + + """ + for tie_param in tied_params: + tie_param_devices = {} + for param in tie_param: + tie_param_devices[param] = _get_param_device(param, device_map) + if len(set(tie_param_devices.values())) > 1: + logger.warn( + f"Tied parameters are on different devices: {tie_param_devices}. " + "Please modify your custom device map or set `device_map='auto'`. " + ) + + +def _get_named_modules( + module: torch.nn.Module, + memo: Optional[Set[torch.nn.Module]] = None, + prefix: str = "", + remove_duplicate: bool = True, +): + """ + Return an iterator over all modules in the network, yielding both the name of the module as well as the module + itself. Copied from PyTorch `torch.nn.Module.named_modules` for compatability with torch < 2.0 versions with + `remove_duplicate` option added. + + Args: + memo (set of `torch.nn.Module`, *optional*): + A memo to store the set of modules already added to the result + prefix (`str`, *optional*): + A prefix that will be added to the name of the module + remove_duplicate (`bool`, *optional*): + Whether to remove the duplicated module instances in the result or not + + Yields: + (str, Module): Tuple of name and module + + Note: + Duplicate modules are returned only once. In the following example, ``l`` will be returned only once. + """ + if memo is None: + memo = set() + if module not in memo: + if remove_duplicate: + memo.add(module) + yield prefix, module + for name, sub_module in module._modules.items(): + if module is None: + continue + submodule_prefix = prefix + ("." if prefix else "") + name + yield from _get_named_modules(sub_module, memo, submodule_prefix, remove_duplicate) + + +def _get_named_parameters(module: torch.nn.Module, prefix="", recurse=True, remove_duplicate: bool = True): + """ + Help yield various names + members of modules. Copied from PyTorch `torch.nn.Module.named_modules` for + compatability with torch < 2.0 versions with `remove_duplicate` option added. + """ + memo = set() + modules = ( + _get_named_modules(module, prefix=prefix, remove_duplicate=remove_duplicate) if recurse else [(prefix, module)] + ) + for module_prefix, module in modules: + members = module._parameters.items() + for k, v in members: + if v is None or v in memo: + continue + if remove_duplicate: + memo.add(v) + name = module_prefix + ("." if module_prefix else "") + k + yield name, v + + +def find_tied_parameters(model: torch.nn.Module, **kwargs): + """ + Find the tied parameters in a given model. + + + + The signature accepts keyword arguments, but they are for the recursive part of this function and you should ignore + them. + + + + Args: + model (`torch.nn.Module`): The model to inspect. + + Returns: + List[List[str]]: A list of lists of parameter names being all tied together. + + Example: + + ```py + >>> from collections import OrderedDict + >>> import torch.nn as nn + + >>> model = nn.Sequential(OrderedDict([("linear1", nn.Linear(4, 4)), ("linear2", nn.Linear(4, 4))])) + >>> model.linear2.weight = model.linear1.weight + >>> find_tied_parameters(model) + [['linear1.weight', 'linear2.weight']] + ``` + """ + + # get ALL model parameters and thier names + all_named_parameters = {name: param for name, param in _get_named_parameters(model, remove_duplicate=False)} + + # get ONLY unique named parameters, + # if parameter is tied and have multiple names, it will be included only once + no_duplicate_named_parameters = { + name: param for name, param in _get_named_parameters(model, remove_duplicate=True) + } + + # the difference of the two sets will give us the tied parameters + tied_param_names = set(all_named_parameters.keys()) - set(no_duplicate_named_parameters.keys()) + + # 'tied_param_names' contains the names of parameters that are tied in the model, but we do not know + # which names refer to the same parameter. To identify this, we need to group them together. + tied_param_groups = {} + for tied_param_name in tied_param_names: + tied_param = all_named_parameters[tied_param_name] + for param_name, param in no_duplicate_named_parameters.items(): + # compare if parameters are the same, if so, group thier names together + if param is tied_param: + if param_name not in tied_param_groups: + tied_param_groups[param_name] = [] + tied_param_groups[param_name].append(tied_param_name) + + return FindTiedParametersResult([sorted([weight] + list(set(tied))) for weight, tied in tied_param_groups.items()]) + + +def retie_parameters(model, tied_params): + """ + Reties tied parameters in a given model if the link was broken (for instance when adding hooks). + + Args: + model (`torch.nn.Module`): + The model in which to retie parameters. + tied_params (`List[List[str]]`): + A mapping parameter name to tied parameter name as obtained by `find_tied_parameters`. + """ + for tied_group in tied_params: + param_to_tie = None + # two loops : the first one to set param_to_tie , the second one to change the values of tied_group + for param_name in tied_group: + module = model + splits = param_name.split(".") + for split in splits[:-1]: + module = getattr(module, split) + param = getattr(module, splits[-1]) + if param_to_tie is None and param.device != torch.device("meta"): + param_to_tie = param + break + if param_to_tie is not None: + for param_name in tied_group: + module = model + splits = param_name.split(".") + for split in splits[:-1]: + module = getattr(module, split) + setattr(module, splits[-1], param_to_tie) + + +def _get_proper_dtype(dtype: Union[str, torch.device]) -> torch.dtype: + """ + Just does torch.dtype(dtype) if necessary. + """ + if isinstance(dtype, str): + # We accept "torch.float16" or just "float16" + dtype = dtype.replace("torch.", "") + dtype = getattr(torch, dtype) + return dtype + + +def compute_module_sizes( + model: nn.Module, + dtype: Optional[Union[str, torch.device]] = None, + special_dtypes: Optional[Dict[str, Union[str, torch.device]]] = None, + buffers_only: bool = False, +): + """ + Compute the size of each submodule of a given model. + """ + if dtype is not None: + dtype = _get_proper_dtype(dtype) + dtype_size = dtype_byte_size(dtype) + if special_dtypes is not None: + special_dtypes = {key: _get_proper_dtype(dtyp) for key, dtyp in special_dtypes.items()} + special_dtypes_size = {key: dtype_byte_size(dtyp) for key, dtyp in special_dtypes.items()} + module_sizes = defaultdict(int) + + module_list = [] + + if not buffers_only: + module_list = named_module_tensors(model, recurse=True) + else: + module_list = model.named_buffers(recurse=True) + + for name, tensor in module_list: + if special_dtypes is not None and name in special_dtypes: + size = tensor.numel() * special_dtypes_size[name] + elif dtype is None: + size = tensor.numel() * dtype_byte_size(tensor.dtype) + elif str(tensor.dtype).startswith(("torch.uint", "torch.int", "torch.bool")): + # According to the code in set_module_tensor_to_device, these types won't be converted + # so use their original size here + size = tensor.numel() * dtype_byte_size(tensor.dtype) + else: + size = tensor.numel() * min(dtype_size, dtype_byte_size(tensor.dtype)) + name_parts = name.split(".") + for idx in range(len(name_parts) + 1): + module_sizes[".".join(name_parts[:idx])] += size + + return module_sizes + + +def compute_module_total_buffer_size( + model: nn.Module, + dtype: Optional[Union[str, torch.device]] = None, + special_dtypes: Optional[Dict[str, Union[str, torch.device]]] = None, +): + """ + Compute the total size of buffers in each submodule of a given model. + """ + module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes, buffers_only=True) + return module_sizes.get("", 0) + + +def get_max_layer_size( + modules: List[Tuple[str, torch.nn.Module]], module_sizes: Dict[str, int], no_split_module_classes: List[str] +): + """ + Utility function that will scan a list of named modules and return the maximum size used by one full layer. The + definition of a layer being: + - a module with no direct children (just parameters and buffers) + - a module whose class name is in the list `no_split_module_classes` + + Args: + modules (`List[Tuple[str, torch.nn.Module]]`): + The list of named modules where we want to determine the maximum layer size. + module_sizes (`Dict[str, int]`): + A dictionary mapping each layer name to its size (as generated by `compute_module_sizes`). + no_split_module_classes (`List[str]`): + A list of class names for layers we don't want to be split. + + Returns: + `Tuple[int, List[str]]`: The maximum size of a layer with the list of layer names realizing that maximum size. + """ + max_size = 0 + layer_names = [] + modules_to_treat = modules.copy() + while len(modules_to_treat) > 0: + module_name, module = modules_to_treat.pop(0) + modules_children = list(module.named_children()) if isinstance(module, torch.nn.Module) else [] + if len(modules_children) == 0 or module.__class__.__name__ in no_split_module_classes: + # No splitting this one so we compare to the max_size + size = module_sizes[module_name] + if size > max_size: + max_size = size + layer_names = [module_name] + elif size == max_size: + layer_names.append(module_name) + else: + modules_to_treat = [(f"{module_name}.{n}", v) for n, v in modules_children] + modules_to_treat + return max_size, layer_names + + +def get_max_memory(max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None): + """ + Get the maximum memory available if nothing is passed, converts string to int otherwise. + """ + import psutil + + if max_memory is None: + max_memory = {} + # Make sure CUDA is initialized on each GPU to have the right memory info. + if is_npu_available(): + for i in range(torch.npu.device_count()): + try: + _ = torch.tensor(0, device=torch.device("npu", i)) + max_memory[i] = torch.npu.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + elif is_mlu_available(): + for i in range(torch.mlu.device_count()): + try: + _ = torch.tensor(0, device=torch.device("mlu", i)) + max_memory[i] = torch.mlu.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + elif is_musa_available(): + for i in range(torch.musa.device_count()): + try: + _ = torch.tensor(0, device=torch.device("musa", i)) + max_memory[i] = torch.musa.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + elif is_xpu_available(): + for i in range(torch.xpu.device_count()): + try: + _ = torch.tensor(0, device=torch.device("xpu", i)) + max_memory[i] = torch.xpu.max_memory_allocated(i) + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + else: + for i in range(torch.cuda.device_count()): + try: + _ = torch.tensor([0], device=i) + max_memory[i] = torch.cuda.mem_get_info(i)[0] + except Exception: + logger.info(f"Device {i} seems unavailable, Proceeding to check subsequent devices.") + continue + # allocate everything in the mps device as the RAM is shared + if is_mps_available(): + max_memory["mps"] = psutil.virtual_memory().available + else: + max_memory["cpu"] = psutil.virtual_memory().available + return max_memory + + for key in max_memory: + if isinstance(max_memory[key], str): + max_memory[key] = convert_file_size_to_int(max_memory[key]) + + # Need to sort the device by type to make sure that we allocate the gpu first. + # As gpu/npu/xpu are represented by int, we need to sort them first. + gpu_devices = [k for k in max_memory.keys() if isinstance(k, int)] + gpu_devices.sort() + # check if gpu/npu/xpu devices are available and if not, throw a warning + if is_npu_available(): + num_devices = torch.npu.device_count() + elif is_mlu_available(): + num_devices = torch.mlu.device_count() + elif is_musa_available(): + num_devices = torch.musa.device_count() + elif is_xpu_available(): + num_devices = torch.xpu.device_count() + else: + num_devices = torch.cuda.device_count() + for device in gpu_devices: + if device >= num_devices or device < 0: + logger.warning(f"Device {device} is not available, available devices are {list(range(num_devices))}") + # Add the other devices in the preset order if they are available + all_devices = gpu_devices + [k for k in ["mps", "cpu", "disk"] if k in max_memory.keys()] + # Raise an error if a device is not recognized + for k in max_memory.keys(): + if k not in all_devices: + raise ValueError( + f"Device {k} is not recognized, available devices are integers(for GPU/XPU), 'mps', 'cpu' and 'disk'" + ) + max_memory = {k: max_memory[k] for k in all_devices} + + return max_memory + + +def clean_device_map(device_map: Dict[str, Union[int, str, torch.device]], module_name: str = ""): + """ + Cleans a device_map by grouping all submodules that go on the same device together. + """ + # Get the value of the current module and if there is only one split across several keys, regroup it. + prefix = "" if module_name == "" else f"{module_name}." + values = [v for k, v in device_map.items() if k.startswith(prefix)] + if len(set(values)) == 1 and len(values) > 1: + for k in [k for k in device_map if k.startswith(prefix)]: + del device_map[k] + device_map[module_name] = values[0] + + # Recurse over the children + children_modules = [k for k in device_map.keys() if k.startswith(prefix) and len(k) > len(module_name)] + idx = len(module_name.split(".")) + 1 if len(module_name) > 0 else 1 + children_modules = set(".".join(k.split(".")[:idx]) for k in children_modules) + for child in children_modules: + clean_device_map(device_map, module_name=child) + + return device_map + + +def load_offloaded_weights(model, index, offload_folder): + """ + Loads the weights from the offload folder into the model. + + Args: + model (`torch.nn.Module`): + The model to load the weights into. + index (`dict`): + A dictionary containing the parameter name and its metadata for each parameter that was offloaded from the + model. + offload_folder (`str`): + The folder where the offloaded weights are stored. + """ + if index is None or len(index) == 0: + # Nothing to do + return + for param_name, metadata in index.items(): + if "SCB" in param_name: + continue + fp16_statistics = None + if "weight" in param_name and param_name.replace("weight", "SCB") in index.keys(): + weight_name = param_name.replace("weight", "SCB") + fp16_statistics = load_offloaded_weight( + os.path.join(offload_folder, f"{weight_name}.dat"), index[weight_name] + ) + tensor_file = os.path.join(offload_folder, f"{param_name}.dat") + weight = load_offloaded_weight(tensor_file, metadata) + set_module_tensor_to_device(model, param_name, "cpu", value=weight, fp16_statistics=fp16_statistics) + + +def get_module_leaves(module_sizes): + module_children = {} + for module in module_sizes: + if module == "" or "." not in module: + continue + parent = module.rsplit(".", 1)[0] + module_children[parent] = module_children.get(parent, 0) + 1 + leaves = [module for module in module_sizes if module_children.get(module, 0) == 0 and module != ""] + return leaves + + +def get_balanced_memory( + model: nn.Module, + max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None, + no_split_module_classes: Optional[List[str]] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + special_dtypes: Optional[Dict[str, Union[str, torch.device]]] = None, + low_zero: bool = False, +): + """ + Compute a `max_memory` dictionary for [`infer_auto_device_map`] that will balance the use of each available GPU. + + + + All computation is done analyzing sizes and dtypes of the model parameters. As a result, the model can be on the + meta device (as it would if initialized within the `init_empty_weights` context manager). + + + + Args: + model (`torch.nn.Module`): + The model to analyze. + max_memory (`Dict`, *optional*): + A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset. + Example: `max_memory={0: "1GB"}`. + no_split_module_classes (`List[str]`, *optional*): + A list of layer class names that should never be split across device (for instance any layer that has a + residual connection). + dtype (`str` or `torch.dtype`, *optional*): + If provided, the weights will be converted to that type when loaded. + special_dtypes (`Dict[str, Union[str, torch.device]]`, *optional*): + If provided, special dtypes to consider for some specific weights (will override dtype used as default for + all weights). + low_zero (`bool`, *optional*): + Minimizes the number of weights on GPU 0, which is convenient when it's used for other operations (like the + Transformers generate function). + """ + # Get default / clean up max_memory + user_not_set_max_memory = max_memory is None + max_memory = get_max_memory(max_memory) + + if is_npu_available(): + expected_device_type = "npu" + elif is_mlu_available(): + expected_device_type = "mlu" + elif is_musa_available(): + expected_device_type = "musa" + elif is_xpu_available(): + expected_device_type = "xpu" + else: + expected_device_type = "cuda" + num_devices = len([d for d in max_memory if torch.device(d).type == expected_device_type and max_memory[d] > 0]) + + if num_devices == 0: + return max_memory + + if num_devices == 1: + # We cannot do low_zero on just one GPU, but we will still reserve some memory for the buffer + low_zero = False + # If user just asked us to handle memory usage, we should avoid OOM + if user_not_set_max_memory: + for key in max_memory.keys(): + if isinstance(key, int): + max_memory[key] *= 0.9 # 90% is a good compromise + logger.info( + f"We will use 90% of the memory on device {key} for storing the model, and 10% for the buffer to avoid OOM. " + "You can set `max_memory` in to a higher value to use more memory (at your own risk)." + ) + break # only one device + + module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes) + per_gpu = module_sizes[""] // (num_devices - 1 if low_zero else num_devices) + + # We can't just set the memory to model_size // num_devices as it will end being too small: each GPU will get + # slightly less layers and some layers will end up offload at the end. So this function computes a buffer size to + # add which is the biggest of: + # - the size of no split block (if applicable) + # - the mean of the layer sizes + if no_split_module_classes is None: + no_split_module_classes = [] + elif not isinstance(no_split_module_classes, (list, tuple)): + no_split_module_classes = [no_split_module_classes] + + # Identify the size of the no_split_block modules + if len(no_split_module_classes) > 0: + no_split_children = {} + for name, size in module_sizes.items(): + if name == "": + continue + submodule = model + for submodule_name in name.split("."): + submodule = getattr(submodule, submodule_name) + class_name = submodule.__class__.__name__ + if class_name in no_split_module_classes and class_name not in no_split_children: + no_split_children[class_name] = size + + if set(no_split_children.keys()) == set(no_split_module_classes): + break + buffer = max(no_split_children.values()) if len(no_split_children) > 0 else 0 + else: + buffer = 0 + + # Compute mean of final modules. In the first dict of module sizes, leaves are the parameters + leaves = get_module_leaves(module_sizes) + module_sizes = {n: v for n, v in module_sizes.items() if n not in leaves} + # Once removed, leaves are the final modules. + leaves = get_module_leaves(module_sizes) + mean_leaves = int(sum([module_sizes[n] for n in leaves]) / max(len(leaves), 1)) + buffer = int(1.25 * max(buffer, mean_leaves)) + per_gpu += buffer + + # Sorted list of GPUs id (we may have some gpu ids not included in the our max_memory list - let's ignore them) + gpus_idx_list = list( + sorted( + device_id for device_id, device_mem in max_memory.items() if isinstance(device_id, int) and device_mem > 0 + ) + ) + # The last device is left with max_memory just in case the buffer is not enough. + for idx in gpus_idx_list[:-1]: + max_memory[idx] = min(max_memory[0] if low_zero and idx == 0 else per_gpu, max_memory[idx]) + + if low_zero: + min_zero = max(0, module_sizes[""] - sum([max_memory[i] for i in range(1, num_devices)])) + max_memory[0] = min(min_zero, max_memory[0]) + + return max_memory + + +def calculate_maximum_sizes(model: torch.nn.Module): + "Computes the total size of the model and its largest layer" + sizes = compute_module_sizes(model) + # `transformers` models store this information for us + no_split_modules = getattr(model, "_no_split_modules", None) + if no_split_modules is None: + no_split_modules = [] + + modules_to_treat = ( + list(model.named_parameters(recurse=False)) + + list(model.named_children()) + + list(model.named_buffers(recurse=False)) + ) + largest_layer = get_max_layer_size(modules_to_treat, sizes, no_split_modules) + total_size = sizes[""] + return total_size, largest_layer + + +def infer_auto_device_map( + model: nn.Module, + max_memory: Optional[Dict[Union[int, str], Union[int, str]]] = None, + no_split_module_classes: Optional[List[str]] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + special_dtypes: Optional[Dict[str, Union[str, torch.dtype]]] = None, + verbose: bool = False, + clean_result: bool = True, + offload_buffers: bool = False, +): + """ + Compute a device map for a given model giving priority to GPUs, then offload on CPU and finally offload to disk, + such that: + - we don't exceed the memory available of any of the GPU. + - if offload to the CPU is needed, there is always room left on GPU 0 to put back the layer offloaded on CPU that + has the largest size. + - if offload to the CPU is needed,we don't exceed the RAM available on the CPU. + - if offload to the disk is needed, there is always room left on the CPU to put back the layer offloaded on disk + that has the largest size. + + + + All computation is done analyzing sizes and dtypes of the model parameters. As a result, the model can be on the + meta device (as it would if initialized within the `init_empty_weights` context manager). + + + + Args: + model (`torch.nn.Module`): + The model to analyze. + max_memory (`Dict`, *optional*): + A dictionary device identifier to maximum memory. Will default to the maximum memory available if unset. + Example: `max_memory={0: "1GB"}`. + no_split_module_classes (`List[str]`, *optional*): + A list of layer class names that should never be split across device (for instance any layer that has a + residual connection). + dtype (`str` or `torch.dtype`, *optional*): + If provided, the weights will be converted to that type when loaded. + special_dtypes (`Dict[str, Union[str, torch.device]]`, *optional*): + If provided, special dtypes to consider for some specific weights (will override dtype used as default for + all weights). + verbose (`bool`, *optional*, defaults to `False`): + Whether or not to provide debugging statements as the function builds the device_map. + clean_result (`bool`, *optional*, defaults to `True`): + Clean the resulting device_map by grouping all submodules that go on the same device together. + offload_buffers (`bool`, *optional*, defaults to `False`): + In the layers that are offloaded on the CPU or the hard drive, whether or not to offload the buffers as + well as the parameters. + """ + # Get default / clean up max_memory + max_memory = get_max_memory(max_memory) + if no_split_module_classes is None: + no_split_module_classes = [] + elif not isinstance(no_split_module_classes, (list, tuple)): + no_split_module_classes = [no_split_module_classes] + + devices = list(max_memory.keys()) + if "disk" not in devices: + devices.append("disk") + gpus = [device for device in devices if device not in ["cpu", "disk"]] + + # Devices that need to keep space for a potential offloaded layer. + if "mps" in gpus: + main_devices = ["mps"] + elif len(gpus) > 0: + main_devices = [gpus[0], "cpu"] + else: + main_devices = ["cpu"] + + module_sizes = compute_module_sizes(model, dtype=dtype, special_dtypes=special_dtypes) + tied_parameters = find_tied_parameters(model) + + if check_tied_parameters_in_config(model) and len(tied_parameters) == 0: + logger.warn( + "The model weights are not tied. Please use the `tie_weights` method before using the `infer_auto_device` function." + ) + + device_map = OrderedDict() + current_device = 0 + current_memory_used = 0 + device_memory_used = {} + device_buffer_sizes = {} + + # Direct submodules and parameters + modules_to_treat = ( + list(model.named_parameters(recurse=False)) + + list(model.named_children()) + + list(model.named_buffers(recurse=False)) + ) + # Initialize maximum largest layer, to know which space to keep in memory + max_layer_size, max_layer_names = get_max_layer_size(modules_to_treat, module_sizes, no_split_module_classes) + + # Ready ? This is going to be a bit messy. + while len(modules_to_treat) > 0: + name, module = modules_to_treat.pop(0) + if verbose: + print(f"\nTreating module {name}.") + # Max size in the remaining layers may have changed since we took one, so we maybe update it. + max_layer_names = [n for n in max_layer_names if n != name and not n.startswith(name + ".")] + if len(max_layer_names) == 0: + max_layer_size, max_layer_names = get_max_layer_size( + [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)], + module_sizes, + no_split_module_classes, + ) + # Assess size needed + module_size = module_sizes[name] + + # We keep relevant tied parameters only: one of the tied parameters in the group is inside the current module + # and the other is not. + # Note: If we are currently processing the name `compute.weight`, an other parameter named e.g. `compute.weight_submodule.parameter` + # needs to be considered outside the current module, hence the check with additional dots. + tied_param_goups = [ + tied_group + for tied_group in tied_parameters + if any(name + "." in k + "." for k in tied_group) and not all(name + "." in k + "." for k in tied_group) + ] + + if verbose and len(tied_param_goups) > 0: + print(f" Found the relevant tied param groups {tied_param_goups}") + + # Then we keep track of all the parameters that are tied to the current module, but not in the current module + tied_params = sum( + [[p for p in tied_group if name + "." not in p + "."] for tied_group in tied_param_goups], [] + ) + + if verbose and len(tied_params) > 0: + print(f" So those parameters need to be taken into account {tied_params}") + + device = devices[current_device] + current_max_size = max_memory[device] if device != "disk" else None + current_memory_reserved = 0 + # Reduce max size available by the largest layer. + if devices[current_device] in main_devices: + current_max_size = current_max_size - max_layer_size + current_memory_reserved = max_layer_size + # Case 1 -> We're too big! + if current_max_size is not None and current_memory_used + module_size > current_max_size: + # Split or not split? + modules_children = ( + [] + if isinstance(module, nn.Parameter) or isinstance(module, torch.Tensor) + else list(module.named_children()) + ) + if verbose: + print( + f"Not enough space on {devices[current_device]} to put {name} (space available " + f"{current_max_size - current_memory_used}, module size {module_size})." + ) + if len(modules_children) == 0 or module.__class__.__name__ in no_split_module_classes: + # -> no split, we go to the next device + if verbose: + print("This module cannot be split, going to the next device.") + + device_memory_used[device] = current_memory_used + current_memory_reserved + current_device += 1 + modules_to_treat = [(name, module)] + modules_to_treat + current_memory_used = 0 + else: + # -> split, we replace the module studied by its children + parameters + if verbose: + print(f"Splitting {name}.") + modules_children = list(module.named_parameters(recurse=False)) + modules_children + modules_to_treat = [(f"{name}.{n}", v) for n, v in modules_children] + modules_to_treat + # Update the max layer size. + max_layer_size, max_layer_names = get_max_layer_size( + [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)], + module_sizes, + no_split_module_classes, + ) + + # Case 2, it fits! We're not entirely out of the wood though, because we may have some tied parameters. + elif len(tied_params) > 0: + # First locate all tied modules + tied_module_names = [] + tied_modules = [] + for tied_param in tied_params: + tied_module_index = [i for i, (n, _) in enumerate(modules_to_treat) if n in tied_param][0] + tied_module_names.append(modules_to_treat[tied_module_index][0]) + tied_modules.append(modules_to_treat[tied_module_index][1]) + if verbose: + print( + f" It looks like {name} is going to fit on {devices[current_device]} but we have tied " + f"parameters to account for.\n - Names {tied_params}\n - Module names {tied_module_names}" + ) + + # Let's see if it all fits first + module_size_with_ties = module_size + for tied_param, tied_module_name in zip(tied_params, tied_module_names): + module_size_with_ties += module_sizes[tied_module_name] - module_sizes[tied_param] + + if current_max_size is None or current_memory_used + module_size_with_ties <= current_max_size: + # We really really fit! + if verbose: + print(f"Putting {name} and {tied_module_names} on {devices[current_device]}.") + current_memory_used += module_size_with_ties + device_map[name] = devices[current_device] + for tied_module_name in tied_module_names: + if tied_module_name in [m[0] for m in modules_to_treat]: + # The module may have been removed by a previous iteration of this loop. + tied_module_index = [i for i, (n, _) in enumerate(modules_to_treat) if n == tied_module_name][ + 0 + ] + modules_to_treat.pop(tied_module_index) + device_map[tied_module_name] = devices[current_device] + + if not offload_buffers and isinstance(module, nn.Module): + current_buffer_size = compute_module_total_buffer_size( + module, dtype=dtype, special_dtypes=special_dtypes + ) + device_buffer_sizes[device] = device_buffer_sizes.get(device, 0) + current_buffer_size + + else: + # We don't fit with the tied modules. Next question is: can we split one of the tied modules to make it + # smaller or do we need to go on the next device? + if verbose: + print( + f"Not enough space on {devices[current_device]} to put {name} and {tied_module_names} (space " + f"available {current_max_size - current_memory_used}, needed size {module_size_with_ties})." + ) + split_happened = False + for tied_module_name, tied_module in zip(tied_module_names, tied_modules): + tied_module_children = list(tied_module.named_children()) + if len(tied_module_children) == 0 or tied_module.__class__.__name__ in no_split_module_classes: + # can't break this one. + continue + + if verbose: + print(f"Splitting {tied_module_name}.") + tied_module_children = list(tied_module.named_parameters(recurse=False)) + tied_module_children + tied_module_children = [(f"{tied_module_name}.{n}", v) for n, v in tied_module_children] + tied_module_index = [i for i, (n, _) in enumerate(modules_to_treat) if n == tied_module_name][0] + + modules_to_treat = ( + [(name, module)] + + modules_to_treat[:tied_module_index] + + tied_module_children + + modules_to_treat[tied_module_index + 1 :] + ) + # Update the max layer size. + max_layer_size, max_layer_names = get_max_layer_size( + [(n, m) for n, m in modules_to_treat if isinstance(m, torch.nn.Module)], + module_sizes, + no_split_module_classes, + ) + split_happened = True + break + + if not split_happened: + # If the tied module is not split, we go to the next device + if verbose: + print("None of the tied module can be split, going to the next device.") + + device_memory_used[device] = current_memory_used + current_memory_reserved + current_device += 1 + modules_to_treat = [(name, module)] + modules_to_treat + current_memory_used = 0 + + else: + if verbose: + if current_max_size is None: + print(f"Putting {name} (size={module_size}) on {devices[current_device]}.") + else: + print( + f"Putting {name} (size={module_size}) on {devices[current_device]} " + f"(available={current_max_size - current_memory_used})." + ) + current_memory_used += module_size + device_memory_used[device] = current_memory_used + current_memory_reserved + device_map[name] = devices[current_device] + + if not offload_buffers and isinstance(module, nn.Module): + current_buffer_size = compute_module_total_buffer_size( + module, dtype=dtype, special_dtypes=special_dtypes + ) + device_buffer_sizes[device] = device_buffer_sizes.get(device, 0) + current_buffer_size + + if clean_result: + device_map = clean_device_map(device_map) + + non_gpu_buffer_size = device_buffer_sizes.get("cpu", 0) + device_buffer_sizes.get("disk", 0) + if non_gpu_buffer_size > 0 and not offload_buffers: + is_buffer_fit_any_gpu = False + for gpu_device, gpu_max_memory in max_memory.items(): + if gpu_device == "cpu" or gpu_device == "disk": + continue + + if not is_buffer_fit_any_gpu: + gpu_memory_used = device_memory_used.get(gpu_device, 0) + + if gpu_max_memory >= non_gpu_buffer_size + gpu_memory_used: + is_buffer_fit_any_gpu = True + + if len(gpus) > 0 and not is_buffer_fit_any_gpu: + warnings.warn( + f"Current model requires {non_gpu_buffer_size} bytes of buffer for offloaded layers, which seems does " + f"not fit any GPU's remaining memory. If you are experiencing a OOM later, please consider using " + f"offload_buffers=True." + ) + + return device_map + + +def check_device_map(model: nn.Module, device_map: Dict[str, Union[int, str, torch.device]]): + """ + Checks a device map covers everything in a given model. + + Args: + model (`torch.nn.Module`): The model to check the device map against. + device_map (`Dict[str, Union[int, str, torch.device]]`): The device map to check. + """ + all_model_tensors = [name for name, _ in model.state_dict().items()] + for module_name in device_map.keys(): + if module_name == "": + all_model_tensors.clear() + break + else: + all_model_tensors = [ + name + for name in all_model_tensors + if not name == module_name and not name.startswith(module_name + ".") + ] + if len(all_model_tensors) > 0: + non_covered_params = ", ".join(all_model_tensors) + raise ValueError( + f"The device_map provided does not give any device for the following parameters: {non_covered_params}" + ) + + +def load_state_dict(checkpoint_file, device_map=None): + """ + Load a checkpoint from a given file. If the checkpoint is in the safetensors format and a device map is passed, the + weights can be fast-loaded directly on the GPU. + + Args: + checkpoint_file (`str`): The path to the checkpoint to load. + device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): + A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer + name, once a given module name is inside, every submodule of it will be sent to the same device. + """ + if checkpoint_file.endswith(".safetensors"): + with safe_open(checkpoint_file, framework="pt") as f: + metadata = f.metadata() + weight_names = f.keys() + + if metadata is None: + logger.warn( + f"The safetensors archive passed at {checkpoint_file} does not contain metadata. " + "Make sure to save your model with the `save_pretrained` method. Defaulting to 'pt' metadata." + ) + metadata = {"format": "pt"} + + if metadata.get("format") not in ["pt", "tf", "flax"]: + raise OSError( + f"The safetensors archive passed at {checkpoint_file} does not contain the valid metadata. Make sure " + "you save your model with the `save_pretrained` method." + ) + elif metadata["format"] != "pt": + raise ValueError(f"The checkpoint passed was saved with {metadata['format']}, we need a the pt format.") + if device_map is None: + return safe_load_file(checkpoint_file) + else: + # if we only have one device we can load everything directly + if len(set(device_map.values())) == 1: + device = list(device_map.values())[0] + target_device = device + if is_xpu_available(): + if compare_versions("safetensors", "<", "0.4.2"): + raise ImportError("Safetensors version must be >= 0.4.2 for XPU. Please upgrade safetensors.") + if isinstance(device, int): + target_device = f"xpu:{device}" + + return safe_load_file(checkpoint_file, device=target_device) + + devices = list(set(device_map.values()) - {"disk"}) + # cpu device should always exist as fallback option + if "cpu" not in devices: + devices.append("cpu") + + # For each device, get the weights that go there + device_weights = {device: [] for device in devices} + for module_name, device in device_map.items(): + if device in devices: + device_weights[device].extend( + [k for k in weight_names if k == module_name or k.startswith(module_name + ".")] + ) + + # all weights that haven't defined a device should be loaded on CPU + device_weights["cpu"].extend([k for k in weight_names if k not in sum(device_weights.values(), [])]) + tensors = {} + if is_tqdm_available(): + progress_bar = tqdm( + main_process_only=False, + total=sum([len(device_weights[device]) for device in devices]), + unit="w", + smoothing=0, + leave=False, + ) + else: + progress_bar = None + for device in devices: + target_device = device + if is_xpu_available(): + if compare_versions("safetensors", "<", "0.4.2"): + raise ImportError("Safetensors version must be >= 0.4.2 for XPU. Please upgrade safetensors.") + if isinstance(device, int): + target_device = f"xpu:{device}" + + with safe_open(checkpoint_file, framework="pt", device=target_device) as f: + for key in device_weights[device]: + if progress_bar is not None: + progress_bar.set_postfix(dev=device, refresh=False) + progress_bar.set_description(key) + tensors[key] = f.get_tensor(key) + if progress_bar is not None: + progress_bar.update() + if progress_bar is not None: + progress_bar.close() + + return tensors + else: + return torch.load(checkpoint_file, map_location=torch.device("cpu")) + + +def get_state_dict_offloaded_model(model: nn.Module): + """ + Returns the state dictionary for an offloaded model via iterative onloading + + Args: + model (`torch.nn.Module`): + The offloaded model we want to save + """ + from ..hooks import AlignDevicesHook + + state_dict = {} + placeholders = set() + for name, module in model.named_modules(): + if name == "": + continue + if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload: + original_device = module._hf_hook.execution_device + # assign hook execution device to cpu + module._hf_hook.execution_device = "cpu" + # onload meta tensors to execution device + try: + module._hf_hook.pre_forward(module) + except MemoryError: + raise MemoryError("Offloaded module must fit in CPU memory to call save_model!") from None + module_state_dict = module.state_dict() + # offload meta tensors from cpu + module._hf_hook.post_forward(module, torch.tensor([])) + # re-assign hook to original execution device + module._hf_hook.execution_device = original_device + else: + module_state_dict = module.state_dict() + + for key in module_state_dict: + # ignore placeholder parameters that are still on the meta device + if module_state_dict[key].device == torch.device("meta"): + placeholders.add(name + f".{key}") + continue + params = module_state_dict[key] + state_dict[name + f".{key}"] = params + for key in placeholders.copy(): + if key in state_dict: + placeholders.remove(key) + if placeholders: + logger.warning(f"The following tensors were not saved because they were still on meta device: {placeholders}") + + return state_dict + + +def get_state_dict_from_offload( + module: nn.Module, + module_name: str, + state_dict: Dict[str, Union[str, torch.tensor]], + device_to_put_offload: Union[int, str, torch.device] = "cpu", +): + """ + Retrieve the state dictionary (with parameters) from an offloaded module and load into a specified device (defualts + to cpu). + + Args: + module: (`torch.nn.Module`): + The module we want to retrieve a state dictionary from + module_name: (`str`): + The name of the module of interest + state_dict (`Dict[str, Union[int, str, torch.device]]`): + Dictionary of {module names: parameters} + device_to_put_offload (`Union[int, str, torch.device]`): + Device to load offloaded parameters into, defaults to the cpu. + """ + from ..hooks import AlignDevicesHook + + root = module_name[: module_name.rfind(".")] # module name without .weight or .bias + preforward = False + if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload: + # assign the device to which the offloaded parameters will be sent + original_device = module._hf_hook.execution_device + module._hf_hook.execution_device = device_to_put_offload + module._hf_hook.pre_forward(module) + preforward = True + + for m_key in module.state_dict(): + params = module.state_dict()[m_key] + if (root + f".{m_key}") in state_dict: + state_dict[root + f".{m_key}"] = params + + if preforward: + module._hf_hook.post_forward(module, torch.tensor([])) + module._hf_hook.execution_device = original_device + + return state_dict + + +def load_checkpoint_in_model( + model: nn.Module, + checkpoint: Union[str, os.PathLike], + device_map: Optional[Dict[str, Union[int, str, torch.device]]] = None, + offload_folder: Optional[Union[str, os.PathLike]] = None, + dtype: Optional[Union[str, torch.dtype]] = None, + offload_state_dict: bool = False, + offload_buffers: bool = False, + keep_in_fp32_modules: List[str] = None, + offload_8bit_bnb: bool = False, + strict: bool = False, +): + """ + Loads a (potentially sharded) checkpoint inside a model, potentially sending weights to a given device as they are + loaded. + + + + Once loaded across devices, you still need to call [`dispatch_model`] on your model to make it able to run. To + group the checkpoint loading and dispatch in one single call, use [`load_checkpoint_and_dispatch`]. + + + + Args: + model (`torch.nn.Module`): + The model in which we want to load a checkpoint. + checkpoint (`str` or `os.PathLike`): + The folder checkpoint to load. It can be: + - a path to a file containing a whole model state dict + - a path to a `.json` file containing the index to a sharded checkpoint + - a path to a folder containing a unique `.index.json` file and the shards of a checkpoint. + - a path to a folder containing a unique pytorch_model.bin or a model.safetensors file. + device_map (`Dict[str, Union[int, str, torch.device]]`, *optional*): + A map that specifies where each submodule should go. It doesn't need to be refined to each parameter/buffer + name, once a given module name is inside, every submodule of it will be sent to the same device. + offload_folder (`str` or `os.PathLike`, *optional*): + If the `device_map` contains any value `"disk"`, the folder where we will offload weights. + dtype (`str` or `torch.dtype`, *optional*): + If provided, the weights will be converted to that type when loaded. + offload_state_dict (`bool`, *optional*, defaults to `False`): + If `True`, will temporarily offload the CPU state dict on the hard drive to avoid getting out of CPU RAM if + the weight of the CPU state dict + the biggest shard does not fit. + offload_buffers (`bool`, *optional*, defaults to `False`): + Whether or not to include the buffers in the weights offloaded to disk. + keep_in_fp32_modules(`List[str]`, *optional*): + A list of the modules that we keep in `torch.float32` dtype. + offload_8bit_bnb (`bool`, *optional*): + Whether or not to enable offload of 8-bit modules on cpu/disk. + strict (`bool`, *optional*, defaults to `False`): + Whether to strictly enforce that the keys in the checkpoint state_dict match the keys of the model's + state_dict. + + """ + if offload_8bit_bnb: + from .bnb import quantize_and_offload_8bit + + tied_params = find_tied_parameters(model) + + if check_tied_parameters_in_config(model) and len(tied_params) == 0: + logger.warn( + "The model weights are not tied. Please use the `tie_weights` method before using the `infer_auto_device` function." + ) + if device_map is not None: + check_tied_parameters_on_same_device(tied_params, device_map) + + if offload_folder is None and device_map is not None and "disk" in device_map.values(): + raise ValueError( + "At least one of the model submodule will be offloaded to disk, please pass along an `offload_folder`." + ) + elif offload_folder is not None and device_map is not None and "disk" in device_map.values(): + os.makedirs(offload_folder, exist_ok=True) + + if isinstance(dtype, str): + # We accept "torch.float16" or just "float16" + dtype = dtype.replace("torch.", "") + dtype = getattr(torch, dtype) + + checkpoint_files = None + index_filename = None + if os.path.isfile(checkpoint): + if str(checkpoint).endswith(".json"): + index_filename = checkpoint + else: + checkpoint_files = [checkpoint] + elif os.path.isdir(checkpoint): + # check if the whole state dict is present + potential_state_bin = [f for f in os.listdir(checkpoint) if f == WEIGHTS_NAME] + potential_state_safetensor = [f for f in os.listdir(checkpoint) if f == SAFE_WEIGHTS_NAME] + if len(potential_state_bin) == 1: + checkpoint_files = [os.path.join(checkpoint, potential_state_bin[0])] + elif len(potential_state_safetensor) == 1: + checkpoint_files = [os.path.join(checkpoint, potential_state_safetensor[0])] + else: + # otherwise check for sharded checkpoints + potential_index = [f for f in os.listdir(checkpoint) if f.endswith(".index.json")] + if len(potential_index) == 0: + raise ValueError( + f"{checkpoint} is not a folder containing a `.index.json` file or a {WEIGHTS_NAME} or a {SAFE_WEIGHTS_NAME} file" + ) + elif len(potential_index) == 1: + index_filename = os.path.join(checkpoint, potential_index[0]) + else: + raise ValueError( + f"{checkpoint} containing more than one `.index.json` file, delete the irrelevant ones." + ) + else: + raise ValueError( + "`checkpoint` should be the path to a file containing a whole state dict, or the index of a sharded " + f"checkpoint, or a folder containing a sharded checkpoint or the whole state dict, but got {checkpoint}." + ) + + if index_filename is not None: + checkpoint_folder = os.path.split(index_filename)[0] + with open(index_filename) as f: + index = json.loads(f.read()) + + if "weight_map" in index: + index = index["weight_map"] + checkpoint_files = sorted(list(set(index.values()))) + checkpoint_files = [os.path.join(checkpoint_folder, f) for f in checkpoint_files] + + # Logic for missing/unexepected keys goes here. + + offload_index = {} + if offload_state_dict: + state_dict_folder = tempfile.mkdtemp() + state_dict_index = {} + + unexpected_keys = set() + model_keys = set(model.state_dict().keys()) + buffer_names = [name for name, _ in model.named_buffers()] + for checkpoint_file in checkpoint_files: + loaded_checkpoint = load_state_dict(checkpoint_file, device_map=device_map) + if device_map is None: + model.load_state_dict(loaded_checkpoint, strict=strict) + unexpected_keys.update(set(loaded_checkpoint.keys()) - model_keys) + else: + for param_name, param in loaded_checkpoint.items(): + # skip SCB parameter (for 8-bit serialization) + if "SCB" in param_name: + continue + + if param_name not in model_keys: + unexpected_keys.add(param_name) + if not strict: + continue # Skip loading this parameter. + + module_name = param_name + + while len(module_name) > 0 and module_name not in device_map: + module_name = ".".join(module_name.split(".")[:-1]) + if module_name == "" and "" not in device_map: + # TODO: group all errors and raise at the end. + raise ValueError(f"{param_name} doesn't have any device set.") + param_device = device_map[module_name] + new_dtype = dtype + if dtype is not None and torch.is_floating_point(param): + if keep_in_fp32_modules is not None and dtype == torch.float16: + proceed = False + for key in keep_in_fp32_modules: + if ((key in param_name) and (key + "." in param_name)) or key == param_name: + proceed = True + break + if proceed: + new_dtype = torch.float32 + + if "weight" in param_name and param_name.replace("weight", "SCB") in loaded_checkpoint.keys(): + if param.dtype == torch.int8: + fp16_statistics = loaded_checkpoint[param_name.replace("weight", "SCB")] + else: + fp16_statistics = None + + if param_device == "disk": + if offload_buffers or param_name not in buffer_names: + if new_dtype is None: + new_dtype = param.dtype + if offload_8bit_bnb: + quantize_and_offload_8bit( + model, param, param_name, new_dtype, offload_folder, offload_index, fp16_statistics + ) + continue + else: + set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype) + offload_weight(param, param_name, offload_folder, index=offload_index) + elif param_device == "cpu" and offload_state_dict: + if new_dtype is None: + new_dtype = param.dtype + if offload_8bit_bnb: + quantize_and_offload_8bit( + model, param, param_name, new_dtype, state_dict_folder, state_dict_index, fp16_statistics + ) + else: + set_module_tensor_to_device(model, param_name, "meta", dtype=new_dtype) + offload_weight(param, param_name, state_dict_folder, index=state_dict_index) + else: + set_module_tensor_to_device( + model, + param_name, + param_device, + value=param, + dtype=new_dtype, + fp16_statistics=fp16_statistics, + ) + + # Force Python to clean up. + del loaded_checkpoint + gc.collect() + + if not strict and len(unexpected_keys) > 0: + logger.warning( + f"Some weights of the model checkpoint at {checkpoint} were not used when" + f" initializing {model.__class__.__name__}: {unexpected_keys}. This may or may not be an issue - make sure that the checkpoint does not have unnecessary parameters, or that the model definition correctly corresponds to the checkpoint." + ) + + save_offload_index(offload_index, offload_folder) + + # Load back offloaded state dict on CPU + if offload_state_dict: + load_offloaded_weights(model, state_dict_index, state_dict_folder) + shutil.rmtree(state_dict_folder) + + retie_parameters(model, tied_params) + + +def get_mixed_precision_context_manager(native_amp: bool = False, autocast_kwargs: AutocastKwargs = None): + """ + Return a context manager for autocasting mixed precision + + Args: + native_amp (`bool`, *optional*, defaults to False): + Whether mixed precision is actually enabled. + cache_enabled (`bool`, *optional*, defaults to True): + Whether the weight cache inside autocast should be enabled. + """ + state = AcceleratorState() + if autocast_kwargs is None: + autocast_kwargs = {} + else: + autocast_kwargs = autocast_kwargs.to_kwargs() + if native_amp: + device_type = ( + "cuda" + if (state.distributed_type == DistributedType.XLA and is_torch_xla_available(check_is_gpu=True)) + else state.device.type + ) + if state.mixed_precision == "fp16": + return torch.autocast(device_type=device_type, dtype=torch.float16, **autocast_kwargs) + elif state.mixed_precision in ["bf16", "fp8"] and state.distributed_type in [ + DistributedType.NO, + DistributedType.MULTI_CPU, + DistributedType.MULTI_GPU, + DistributedType.MULTI_MLU, + DistributedType.MULTI_MUSA, + DistributedType.MULTI_NPU, + DistributedType.MULTI_XPU, + DistributedType.FSDP, + DistributedType.XLA, + ]: + return torch.autocast(device_type=device_type, dtype=torch.bfloat16, **autocast_kwargs) + else: + return torch.autocast(device_type=device_type, **autocast_kwargs) + else: + return contextlib.nullcontext() diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/offload.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/offload.py new file mode 100644 index 0000000000000000000000000000000000000000..d064847ca21bde644b443de315b239414aa2fd51 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/offload.py @@ -0,0 +1,213 @@ +# 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. + +import json +import os +from collections.abc import Mapping +from typing import Dict, List, Optional, Union + +import numpy as np +import torch +from safetensors import safe_open + + +def offload_weight(weight, weight_name, offload_folder, index=None): + dtype = None + # Check the string instead of the dtype to be compatible with versions of PyTorch that don't have bfloat16. + if str(weight.dtype) == "torch.bfloat16": + # Need to reinterpret the underlined data as int16 since NumPy does not handle bfloat16s. + weight = weight.view(torch.int16) + dtype = "bfloat16" + array = weight.cpu().numpy() + tensor_file = os.path.join(offload_folder, f"{weight_name}.dat") + if index is not None: + if dtype is None: + dtype = str(array.dtype) + index[weight_name] = {"dtype": dtype, "shape": list(array.shape)} + if array.ndim == 0: + array = array[None] + file_array = np.memmap(tensor_file, dtype=array.dtype, mode="w+", shape=array.shape) + file_array[:] = array[:] + file_array.flush() + return index + + +def load_offloaded_weight(weight_file, weight_info): + shape = tuple(weight_info["shape"]) + if shape == (): + # NumPy memory-mapped arrays can't have 0 dims so it was saved as 1d tensor + shape = (1,) + + dtype = weight_info["dtype"] + if dtype == "bfloat16": + # NumPy does not support bfloat16 so this was saved as a int16 + dtype = "int16" + + weight = np.memmap(weight_file, dtype=dtype, shape=shape, mode="r") + + if len(weight_info["shape"]) == 0: + weight = weight[0] + weight = torch.tensor(weight) + if weight_info["dtype"] == "bfloat16": + weight = weight.view(torch.bfloat16) + + return weight + + +def save_offload_index(index, offload_folder): + if index is None or len(index) == 0: + # Nothing to save + return + + offload_index_file = os.path.join(offload_folder, "index.json") + if os.path.isfile(offload_index_file): + with open(offload_index_file, encoding="utf-8") as f: + current_index = json.load(f) + else: + current_index = {} + current_index.update(index) + + with open(offload_index_file, "w", encoding="utf-8") as f: + json.dump(current_index, f, indent=2) + + +def offload_state_dict(save_dir: Union[str, os.PathLike], state_dict: Dict[str, torch.Tensor]): + """ + Offload a state dict in a given folder. + + Args: + save_dir (`str` or `os.PathLike`): + The directory in which to offload the state dict. + state_dict (`Dict[str, torch.Tensor]`): + The dictionary of tensors to offload. + """ + os.makedirs(save_dir, exist_ok=True) + index = {} + for name, parameter in state_dict.items(): + index = offload_weight(parameter, name, save_dir, index=index) + + # Update index + save_offload_index(index, save_dir) + + +class PrefixedDataset(Mapping): + """ + Will access keys in a given dataset by adding a prefix. + + Args: + dataset (`Mapping`): Any map with string keys. + prefix (`str`): A prefix to add when trying to access any element in the underlying dataset. + """ + + def __init__(self, dataset: Mapping, prefix: str): + self.dataset = dataset + self.prefix = prefix + + def __getitem__(self, key): + return self.dataset[f"{self.prefix}{key}"] + + def __iter__(self): + return iter([key for key in self.dataset if key.startswith(self.prefix)]) + + def __len__(self): + return len(self.dataset) + + +class OffloadedWeightsLoader(Mapping): + """ + A collection that loads weights stored in a given state dict or memory-mapped on disk. + + Args: + state_dict (`Dict[str, torch.Tensor]`, *optional*): + A dictionary parameter name to tensor. + save_folder (`str` or `os.PathLike`, *optional*): + The directory in which the weights are stored (by `offload_state_dict` for instance). + index (`Dict`, *optional*): + A dictionary from weight name to their information (`dtype`/ `shape` or safetensors filename). Will default + to the index saved in `save_folder`. + """ + + def __init__( + self, + state_dict: Dict[str, torch.Tensor] = None, + save_folder: Optional[Union[str, os.PathLike]] = None, + index: Mapping = None, + device=None, + ): + if state_dict is None and save_folder is None and index is None: + raise ValueError("Need either a `state_dict`, a `save_folder` or an `index` containing offloaded weights.") + + self.state_dict = {} if state_dict is None else state_dict + self.save_folder = save_folder + if index is None and save_folder is not None: + with open(os.path.join(save_folder, "index.json")) as f: + index = json.load(f) + self.index = {} if index is None else index + self.all_keys = list(self.state_dict.keys()) + self.all_keys.extend([key for key in self.index if key not in self.all_keys]) + self.device = device + + def __getitem__(self, key: str): + # State dict gets priority + if key in self.state_dict: + return self.state_dict[key] + weight_info = self.index[key] + if weight_info.get("safetensors_file") is not None: + device = "cpu" if self.device is None else self.device + tensor = None + try: + with safe_open(weight_info["safetensors_file"], framework="pt", device=device) as f: + tensor = f.get_tensor(weight_info.get("weight_name", key)) + except TypeError: + # if failed to get_tensor on the device, such as bf16 on mps, try to load it on CPU first + with safe_open(weight_info["safetensors_file"], framework="pt", device="cpu") as f: + tensor = f.get_tensor(weight_info.get("weight_name", key)) + + if "dtype" in weight_info: + tensor = tensor.to(getattr(torch, weight_info["dtype"])) + + if tensor.device != torch.device(device): + tensor = tensor.to(device) + return tensor + + weight_file = os.path.join(self.save_folder, f"{key}.dat") + return load_offloaded_weight(weight_file, weight_info) + + def __iter__(self): + return iter(self.all_keys) + + def __len__(self): + return len(self.all_keys) + + +def extract_submodules_state_dict(state_dict: Dict[str, torch.Tensor], submodule_names: List[str]): + """ + Extract the sub state-dict corresponding to a list of given submodules. + + Args: + state_dict (`Dict[str, torch.Tensor]`): The state dict to extract from. + submodule_names (`List[str]`): The list of submodule names we want to extract. + """ + result = {} + for module_name in submodule_names: + # We want to catch module_name parameter (module_name.xxx) or potentially module_name, but not any of the + # submodules that could being like module_name (transformers.h.1 and transformers.h.10 for instance) + result.update( + { + key: param + for key, param in state_dict.items() + if key == module_name or key.startswith(module_name + ".") + } + ) + return result diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/operations.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/operations.py new file mode 100644 index 0000000000000000000000000000000000000000..162009e76b6c65d6cd9939522cacb13007e6226d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/operations.py @@ -0,0 +1,868 @@ +# 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. +""" +A set of basic tensor ops compatible with tpu, gpu, and multigpu +""" + +import pickle +import warnings +from contextlib import contextmanager, nullcontext +from functools import update_wrapper, wraps +from typing import Any, Mapping + +import torch + +from ..state import AcceleratorState, PartialState +from .constants import TORCH_DISTRIBUTED_OPERATION_TYPES +from .dataclasses import DistributedType, TensorInformation +from .imports import ( + is_npu_available, + is_torch_distributed_available, + is_torch_version, + is_torch_xla_available, + is_xpu_available, +) + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + +if is_torch_distributed_available(): + from torch.distributed import ReduceOp + + +def is_torch_tensor(tensor): + return isinstance(tensor, torch.Tensor) + + +def is_torch_xpu_tensor(tensor): + return isinstance( + tensor, + torch.xpu.FloatTensor, + torch.xpu.ByteTensor, + torch.xpu.IntTensor, + torch.xpu.LongTensor, + torch.xpu.HalfTensor, + torch.xpu.DoubleTensor, + torch.xpu.BFloat16Tensor, + ) + + +def is_tensor_information(tensor_info): + return isinstance(tensor_info, TensorInformation) + + +def is_namedtuple(data): + """ + Checks if `data` is a `namedtuple` or not. Can have false positives, but only if a user is trying to mimic a + `namedtuple` perfectly. + """ + return isinstance(data, tuple) and hasattr(data, "_asdict") and hasattr(data, "_fields") + + +def honor_type(obj, generator): + """ + Cast a generator to the same type as obj (list, tuple, or namedtuple) + """ + # Some objects may not be able to instantiate from a generator directly + if is_namedtuple(obj): + return type(obj)(*list(generator)) + else: + return type(obj)(generator) + + +def recursively_apply(func, data, *args, test_type=is_torch_tensor, error_on_other_type=False, **kwargs): + """ + Recursively apply a function on a data structure that is a nested list/tuple/dictionary of a given base type. + + Args: + func (`callable`): + The function to recursively apply. + data (nested list/tuple/dictionary of `main_type`): + The data on which to apply `func` + *args: + Positional arguments that will be passed to `func` when applied on the unpacked data. + main_type (`type`, *optional*, defaults to `torch.Tensor`): + The base type of the objects to which apply `func`. + error_on_other_type (`bool`, *optional*, defaults to `False`): + Whether to return an error or not if after unpacking `data`, we get on an object that is not of type + `main_type`. If `False`, the function will leave objects of types different than `main_type` unchanged. + **kwargs (additional keyword arguments, *optional*): + Keyword arguments that will be passed to `func` when applied on the unpacked data. + + Returns: + The same data structure as `data` with `func` applied to every object of type `main_type`. + """ + if isinstance(data, (tuple, list)): + return honor_type( + data, + ( + recursively_apply( + func, o, *args, test_type=test_type, error_on_other_type=error_on_other_type, **kwargs + ) + for o in data + ), + ) + elif isinstance(data, Mapping): + return type(data)( + { + k: recursively_apply( + func, v, *args, test_type=test_type, error_on_other_type=error_on_other_type, **kwargs + ) + for k, v in data.items() + } + ) + elif test_type(data): + return func(data, *args, **kwargs) + elif error_on_other_type: + raise TypeError( + f"Unsupported types ({type(data)}) passed to `{func.__name__}`. Only nested list/tuple/dicts of " + f"objects that are valid for `{test_type.__name__}` should be passed." + ) + return data + + +def send_to_device(tensor, device, non_blocking=False, skip_keys=None): + """ + Recursively sends the elements in a nested list/tuple/dictionary of tensors to a given device. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to send to a given device. + device (`torch.device`): + The device to send the data to. + + Returns: + The same data structure as `tensor` with all tensors sent to the proper device. + """ + if is_torch_tensor(tensor) or hasattr(tensor, "to"): + # `torch.Tensor.to("npu")` could not find context when called for the first time (see this [issue](https://gitee.com/ascend/pytorch/issues/I8KECW?from=project-issue)). + if device == "npu": + device = "npu:0" + if device == "xpu": + device = "xpu:0" + try: + return tensor.to(device, non_blocking=non_blocking) + except TypeError: # .to() doesn't accept non_blocking as kwarg + return tensor.to(device) + except AssertionError as error: + # `torch.Tensor.to()` is not supported by `torch_npu` (see this [issue](https://github.com/Ascend/pytorch/issues/16)). + # This call is inside the try-block since is_npu_available is not supported by torch.compile. + if is_npu_available(): + if isinstance(device, int): + device = f"npu:{device}" + elif is_xpu_available(): + if isinstance(device, int): + device = f"xpu:{device}" + else: + raise error + try: + return tensor.to(device, non_blocking=non_blocking) + except TypeError: # .to() doesn't accept non_blocking as kwarg + return tensor.to(device) + elif isinstance(tensor, (tuple, list)): + return honor_type( + tensor, (send_to_device(t, device, non_blocking=non_blocking, skip_keys=skip_keys) for t in tensor) + ) + elif isinstance(tensor, Mapping): + if isinstance(skip_keys, str): + skip_keys = [skip_keys] + elif skip_keys is None: + skip_keys = [] + return type(tensor)( + { + k: t if k in skip_keys else send_to_device(t, device, non_blocking=non_blocking, skip_keys=skip_keys) + for k, t in tensor.items() + } + ) + else: + return tensor + + +def get_data_structure(data): + """ + Recursively gathers the information needed to rebuild a nested list/tuple/dictionary of tensors. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): + The data to send to analyze. + + Returns: + The same data structure as `data` with [`~utils.TensorInformation`] instead of tensors. + """ + + def _get_data_structure(tensor): + return TensorInformation(shape=tensor.shape, dtype=tensor.dtype) + + return recursively_apply(_get_data_structure, data) + + +def get_shape(data): + """ + Recursively gathers the shape of a nested list/tuple/dictionary of tensors as a list. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): + The data to send to analyze. + + Returns: + The same data structure as `data` with lists of tensor shapes instead of tensors. + """ + + def _get_shape(tensor): + return list(tensor.shape) + + return recursively_apply(_get_shape, data) + + +def initialize_tensors(data_structure): + """ + Recursively initializes tensors from a nested list/tuple/dictionary of [`~utils.TensorInformation`]. + + Returns: + The same data structure as `data` with tensors instead of [`~utils.TensorInformation`]. + """ + + def _initialize_tensor(tensor_info): + return torch.empty(*tensor_info.shape, dtype=tensor_info.dtype) + + return recursively_apply(_initialize_tensor, data_structure, test_type=is_tensor_information) + + +def find_batch_size(data): + """ + Recursively finds the batch size in a nested list/tuple/dictionary of lists of tensors. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to find the batch size. + + Returns: + `int`: The batch size. + """ + if isinstance(data, (tuple, list, Mapping)) and (len(data) == 0): + raise ValueError(f"Cannot find the batch size from empty {type(data)}.") + + if isinstance(data, (tuple, list)): + return find_batch_size(data[0]) + elif isinstance(data, Mapping): + for k in data.keys(): + return find_batch_size(data[k]) + elif not isinstance(data, torch.Tensor): + raise TypeError(f"Can only find the batch size of tensors but got {type(data)}.") + return data.shape[0] + + +def ignorant_find_batch_size(data): + """ + Same as [`utils.operations.find_batch_size`] except will ignore if `ValueError` and `TypeErrors` are raised + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to find the batch size. + + Returns: + `int`: The batch size. + """ + try: + return find_batch_size(data) + except (ValueError, TypeError): + pass + return None + + +def listify(data): + """ + Recursively finds tensors in a nested list/tuple/dictionary and converts them to a list of numbers. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): The data from which to convert to regular numbers. + + Returns: + The same data structure as `data` with lists of numbers instead of `torch.Tensor`. + """ + + def _convert_to_list(tensor): + tensor = tensor.detach().cpu() + if tensor.dtype == torch.bfloat16: + # As of Numpy 1.21.4, NumPy does not support bfloat16 (see + # https://github.com/numpy/numpy/blob/a47ecdea856986cd60eabbd53265c2ca5916ad5d/doc/source/user/basics.types.rst ). + # Until Numpy adds bfloat16, we must convert float32. + tensor = tensor.to(torch.float32) + return tensor.tolist() + + return recursively_apply(_convert_to_list, data) + + +def _tpu_gather(tensor): + def _tpu_gather_one(tensor): + if tensor.ndim == 0: + tensor = tensor.clone()[None] + + # Can only gather contiguous tensors + if not tensor.is_contiguous(): + tensor = tensor.contiguous() + return xm.all_gather(tensor) + + res = recursively_apply(_tpu_gather_one, tensor, error_on_other_type=True) + xm.mark_step() + return res + + +def _gpu_gather(tensor): + state = PartialState() + if is_torch_version(">=", "1.13"): + gather_op = torch.distributed.all_gather_into_tensor + else: + gather_op = torch.distributed._all_gather_base + + def _gpu_gather_one(tensor): + if tensor.ndim == 0: + tensor = tensor.clone()[None] + + # Can only gather contiguous tensors + if not tensor.is_contiguous(): + tensor = tensor.contiguous() + + if state.backend is not None and state.backend != "gloo": + # We use `empty` as `all_gather_into_tensor` slightly + # differs from `all_gather` for better efficiency, + # and we rely on the number of items in the tensor + # rather than its direct shape + output_tensors = torch.empty( + state.num_processes * tensor.numel(), + dtype=tensor.dtype, + device=state.device, + ) + gather_op(output_tensors, tensor) + return output_tensors.view(-1, *tensor.size()[1:]) + else: + # a backend of `None` is always CPU + # also gloo does not support `all_gather_into_tensor`, + # which will result in a larger memory overhead for the op + output_tensors = [torch.empty_like(tensor) for _ in range(state.num_processes)] + torch.distributed.all_gather(output_tensors, tensor) + return torch.cat(output_tensors, dim=0) + + return recursively_apply(_gpu_gather_one, tensor, error_on_other_type=True) + + +class DistributedOperationException(Exception): + """ + An exception class for distributed operations. Raised if the operation cannot be performed due to the shape of the + tensors. + """ + + pass + + +def verify_operation(function): + """ + Verifies that `tensor` is the same shape across all processes. Only ran if `PartialState().debug` is `True`. + """ + + @wraps(function) + def wrapper(*args, **kwargs): + if PartialState().distributed_type == DistributedType.NO or not PartialState().debug: + return function(*args, **kwargs) + operation = f"{function.__module__}.{function.__name__}" + if "tensor" in kwargs: + tensor = kwargs["tensor"] + else: + tensor = args[0] + if PartialState().device.type != find_device(tensor).type: + raise DistributedOperationException( + f"One or more of the tensors passed to {operation} were not on the {tensor.device.type} while the `Accelerator` is configured for {PartialState().device.type}. " + f"Please move it to the {PartialState().device.type} before calling {operation}." + ) + shapes = get_shape(tensor) + output = gather_object([shapes]) + if output[0] is not None: + are_same = output.count(output[0]) == len(output) + if not are_same: + process_shape_str = "\n - ".join([f"Process {i}: {shape}" for i, shape in enumerate(output)]) + raise DistributedOperationException( + f"Cannot apply desired operation due to shape mismatches. " + "All shapes across devices must be valid." + f"\n\nOperation: `{operation}`\nInput shapes:\n - {process_shape_str}" + ) + return function(*args, **kwargs) + + return wrapper + + +def chained_operation(function): + """ + Checks that `verify_operation` failed and if so reports a more helpful error chaining the existing + `DistributedOperationException`. + """ + + @wraps(function) + def wrapper(*args, **kwargs): + try: + return function(*args, **kwargs) + except DistributedOperationException as e: + operation = f"{function.__module__}.{function.__name__}" + raise DistributedOperationException( + f"Error found while calling `{operation}`. Please see the earlier error for more details." + ) from e + + return wrapper + + +@verify_operation +def gather(tensor): + """ + Recursively gather tensor in a nested list/tuple/dictionary of tensors from all devices. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather. + + Returns: + The same data structure as `tensor` with all tensors sent to the proper device. + """ + if PartialState().distributed_type == DistributedType.XLA: + return _tpu_gather(tensor) + elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES: + return _gpu_gather(tensor) + else: + return tensor + + +def _gpu_gather_object(object: Any): + output_objects = [None for _ in range(PartialState().num_processes)] + torch.distributed.all_gather_object(output_objects, object) + # all_gather_object returns a list of lists, so we need to flatten it + return [x for y in output_objects for x in y] + + +def gather_object(object: Any): + """ + Recursively gather object in a nested list/tuple/dictionary of objects from all devices. + + Args: + object (nested list/tuple/dictionary of picklable object): + The data to gather. + + Returns: + The same data structure as `object` with all the objects sent to every device. + """ + if PartialState().distributed_type == DistributedType.XLA: + raise NotImplementedError("gather objects in TPU is not supported") + elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES: + return _gpu_gather_object(object) + else: + return object + + +def _gpu_broadcast(data, src=0): + def _gpu_broadcast_one(tensor, src=0): + torch.distributed.broadcast(tensor, src=src) + return tensor + + return recursively_apply(_gpu_broadcast_one, data, error_on_other_type=True, src=src) + + +def _tpu_broadcast(tensor, src=0, name="broadcast tensor"): + if isinstance(tensor, (list, tuple)): + return honor_type(tensor, (_tpu_broadcast(t, name=f"{name}_{i}") for i, t in enumerate(tensor))) + elif isinstance(tensor, Mapping): + return type(tensor)({k: _tpu_broadcast(v, name=f"{name}_{k}") for k, v in tensor.items()}) + return xm.mesh_reduce(name, tensor, lambda x: x[src]) + + +TENSOR_TYPE_TO_INT = { + torch.float: 1, + torch.double: 2, + torch.half: 3, + torch.bfloat16: 4, + torch.uint8: 5, + torch.int8: 6, + torch.int16: 7, + torch.int32: 8, + torch.int64: 9, + torch.bool: 10, +} + +TENSOR_INT_TO_DTYPE = {v: k for k, v in TENSOR_TYPE_TO_INT.items()} + + +def gather_tensor_shape(tensor): + """ + Grabs the shape of `tensor` only available on one process and returns a tensor of its shape + """ + # Allocate 80 bytes to store the shape + max_tensor_dimension = 2**20 + state = PartialState() + base_tensor = torch.empty(max_tensor_dimension, dtype=torch.int, device=state.device) + + # Since PyTorch can't just send a tensor to another GPU without + # knowing its size, we store the size of the tensor with data + # in an allocation + if tensor is not None: + shape = tensor.shape + tensor_dtype = TENSOR_TYPE_TO_INT[tensor.dtype] + base_tensor[: len(shape) + 1] = torch.tensor(list(shape) + [tensor_dtype], dtype=int) + # Perform a reduction to copy the size data onto all GPUs + base_tensor = reduce(base_tensor, reduction="sum") + base_tensor = base_tensor[base_tensor.nonzero()] + # The last non-zero data contains the coded dtype the source tensor is + dtype = int(base_tensor[-1:][0]) + base_tensor = base_tensor[:-1] + return base_tensor, dtype + + +def copy_tensor_to_devices(tensor=None) -> torch.Tensor: + """ + Copys a tensor that only exists on a single device and broadcasts it to other devices. Differs from `broadcast` as + each worker doesn't need to know its shape when used (and tensor can be `None`) + + Args: + tensor (`torch.tensor`): + The tensor that should be sent to all devices. Must only have it be defined on a single device, the rest + should be `None`. + """ + state = PartialState() + shape, dtype = gather_tensor_shape(tensor) + if tensor is None: + tensor = torch.zeros(shape, dtype=TENSOR_INT_TO_DTYPE[dtype]).to(state.device) + return reduce(tensor, reduction="sum") + + +@verify_operation +def broadcast(tensor, from_process: int = 0): + """ + Recursively broadcast tensor in a nested list/tuple/dictionary of tensors to all devices. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather. + from_process (`int`, *optional*, defaults to 0): + The process from which to send the data + + Returns: + The same data structure as `tensor` with all tensors broadcasted to the proper device. + """ + if PartialState().distributed_type == DistributedType.XLA: + return _tpu_broadcast(tensor, src=from_process, name="accelerate.utils.broadcast") + elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES: + return _gpu_broadcast(tensor, src=from_process) + else: + return tensor + + +def broadcast_object_list(object_list, from_process: int = 0): + """ + Broadcast a list of picklable objects form one process to the others. + + Args: + object_list (list of picklable objects): + The list of objects to broadcast. This list will be modified inplace. + from_process (`int`, *optional*, defaults to 0): + The process from which to send the data. + + Returns: + The same list containing the objects from process 0. + """ + if PartialState().distributed_type == DistributedType.XLA: + for i, obj in enumerate(object_list): + object_list[i] = xm.mesh_reduce("accelerate.utils.broadcast_object_list", obj, lambda x: x[from_process]) + elif PartialState().distributed_type in TORCH_DISTRIBUTED_OPERATION_TYPES: + torch.distributed.broadcast_object_list(object_list, src=from_process) + return object_list + + +def slice_tensors(data, tensor_slice, process_index=None, num_processes=None): + """ + Recursively takes a slice in a nested list/tuple/dictionary of tensors. + + Args: + data (nested list/tuple/dictionary of `torch.Tensor`): + The data to slice. + tensor_slice (`slice`): + The slice to take. + + Returns: + The same data structure as `data` with all the tensors slices. + """ + + def _slice_tensor(tensor, tensor_slice): + return tensor[tensor_slice] + + return recursively_apply(_slice_tensor, data, tensor_slice) + + +def concatenate(data, dim=0): + """ + Recursively concatenate the tensors in a nested list/tuple/dictionary of lists of tensors with the same shape. + + Args: + data (nested list/tuple/dictionary of lists of tensors `torch.Tensor`): + The data to concatenate. + dim (`int`, *optional*, defaults to 0): + The dimension on which to concatenate. + + Returns: + The same data structure as `data` with all the tensors concatenated. + """ + if isinstance(data[0], (tuple, list)): + return honor_type(data[0], (concatenate([d[i] for d in data], dim=dim) for i in range(len(data[0])))) + elif isinstance(data[0], Mapping): + return type(data[0])({k: concatenate([d[k] for d in data], dim=dim) for k in data[0].keys()}) + elif not isinstance(data[0], torch.Tensor): + raise TypeError(f"Can only concatenate tensors but got {type(data[0])}") + return torch.cat(data, dim=dim) + + +class CannotPadNestedTensorWarning(UserWarning): + pass + + +@chained_operation +def pad_across_processes(tensor, dim=0, pad_index=0, pad_first=False): + """ + Recursively pad the tensors in a nested list/tuple/dictionary of tensors from all devices to the same size so they + can safely be gathered. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to gather. + dim (`int`, *optional*, defaults to 0): + The dimension on which to pad. + pad_index (`int`, *optional*, defaults to 0): + The value with which to pad. + pad_first (`bool`, *optional*, defaults to `False`): + Whether to pad at the beginning or the end. + """ + + def _pad_across_processes(tensor, dim=0, pad_index=0, pad_first=False): + if getattr(tensor, "is_nested", False): + warnings.warn( + "Cannot pad nested tensors without more information. Leaving unprocessed.", + CannotPadNestedTensorWarning, + ) + return tensor + if dim >= len(tensor.shape): + return tensor + + # Gather all sizes + size = torch.tensor(tensor.shape, device=tensor.device)[None] + sizes = gather(size).cpu() + # Then pad to the maximum size + max_size = max(s[dim] for s in sizes) + if max_size == tensor.shape[dim]: + return tensor + + old_size = tensor.shape + new_size = list(old_size) + new_size[dim] = max_size + new_tensor = tensor.new_zeros(tuple(new_size)) + pad_index + if pad_first: + indices = tuple( + slice(max_size - old_size[dim], max_size) if i == dim else slice(None) for i in range(len(new_size)) + ) + else: + indices = tuple(slice(0, old_size[dim]) if i == dim else slice(None) for i in range(len(new_size))) + new_tensor[indices] = tensor + return new_tensor + + return recursively_apply( + _pad_across_processes, tensor, error_on_other_type=True, dim=dim, pad_index=pad_index, pad_first=pad_first + ) + + +def pad_input_tensors(tensor, batch_size, num_processes, dim=0): + """ + Takes a `tensor` of arbitrary size and pads it so that it can work given `num_processes` needed dimensions. + + New tensors are just the last input repeated. + + E.g.: + Tensor: ([3,4,4]) Num processes: 4 Expected result shape: ([4,4,4]) + + """ + + def _pad_input_tensors(tensor, batch_size, num_processes, dim=0): + remainder = batch_size // num_processes + last_inputs = batch_size - (remainder * num_processes) + if batch_size // num_processes == 0: + to_pad = num_processes - batch_size + else: + to_pad = num_processes - (batch_size // num_processes) + # In the rare case that `to_pad` is negative, + # we need to pad the last inputs - the found `to_pad` + if last_inputs > to_pad & to_pad < 1: + to_pad = last_inputs - to_pad + old_size = tensor.shape + new_size = list(old_size) + new_size[0] = batch_size + to_pad + new_tensor = tensor.new_zeros(tuple(new_size)) + indices = tuple(slice(0, old_size[dim]) if i == dim else slice(None) for i in range(len(new_size))) + new_tensor[indices] = tensor + return new_tensor + + return recursively_apply( + _pad_input_tensors, + tensor, + error_on_other_type=True, + batch_size=batch_size, + num_processes=num_processes, + dim=dim, + ) + + +@verify_operation +def reduce(tensor, reduction="mean", scale=1.0): + """ + Recursively reduce the tensors in a nested list/tuple/dictionary of lists of tensors across all processes by the + mean of a given operation. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to reduce. + reduction (`str`, *optional*, defaults to `"mean"`): + A reduction method. Can be of "mean", "sum", or "none" + scale (`float`, *optional*): + A default scaling value to be applied after the reduce, only valied on XLA. + + Returns: + The same data structure as `data` with all the tensors reduced. + """ + + def _reduce_across_processes(tensor, reduction="mean", scale=1.0): + state = PartialState() + cloned_tensor = tensor.clone() + if state.distributed_type == DistributedType.NO: + return cloned_tensor + if state.distributed_type == DistributedType.XLA: + # Some processes may have different HLO graphs than other + # processes, for example in the breakpoint API + # accelerator.set_trigger(). Use mark_step to make HLOs + # the same on all processes. + xm.mark_step() + xm.all_reduce(xm.REDUCE_SUM, [cloned_tensor], scale) + xm.mark_step() + elif state.distributed_type.value in TORCH_DISTRIBUTED_OPERATION_TYPES: + torch.distributed.all_reduce(cloned_tensor, ReduceOp.SUM) + if reduction == "mean": + cloned_tensor /= state.num_processes + return cloned_tensor + + return recursively_apply( + _reduce_across_processes, tensor, error_on_other_type=True, reduction=reduction, scale=scale + ) + + +def convert_to_fp32(tensor): + """ + Recursively converts the elements nested list/tuple/dictionary of tensors in FP16/BF16 precision to FP32. + + Args: + tensor (nested list/tuple/dictionary of `torch.Tensor`): + The data to convert from FP16/BF16 to FP32. + + Returns: + The same data structure as `tensor` with all tensors that were in FP16/BF16 precision converted to FP32. + """ + + def _convert_to_fp32(tensor): + return tensor.float() + + def _is_fp16_bf16_tensor(tensor): + return (is_torch_tensor(tensor) or hasattr(tensor, "dtype")) and tensor.dtype in ( + torch.float16, + torch.bfloat16, + ) + + return recursively_apply(_convert_to_fp32, tensor, test_type=_is_fp16_bf16_tensor) + + +class ConvertOutputsToFp32: + """ + Decorator to apply to a function outputing tensors (like a model forward pass) that ensures the outputs in FP16 + precision will be convert back to FP32. + + Args: + model_forward (`Callable`): + The function which outputs we want to treat. + + Returns: + The same function as `model_forward` but with converted outputs. + """ + + def __init__(self, model_forward): + self.model_forward = model_forward + update_wrapper(self, model_forward) + + def __call__(self, *args, **kwargs): + return convert_to_fp32(self.model_forward(*args, **kwargs)) + + def __getstate__(self): + raise pickle.PicklingError( + "Cannot pickle a prepared model with automatic mixed precision, please unwrap the model with `Accelerator.unwrap_model(model)` before pickling it." + ) + + +def convert_outputs_to_fp32(model_forward): + model_forward = ConvertOutputsToFp32(model_forward) + + def forward(*args, **kwargs): + return model_forward(*args, **kwargs) + + # To act like a decorator so that it can be popped when doing `extract_model_from_parallel` + forward.__wrapped__ = model_forward + + return forward + + +def find_device(data): + """ + Finds the device on which a nested dict/list/tuple of tensors lies (assuming they are all on the same device). + + Args: + (nested list/tuple/dictionary of `torch.Tensor`): The data we want to know the device of. + """ + if isinstance(data, Mapping): + for obj in data.values(): + device = find_device(obj) + if device is not None: + return device + elif isinstance(data, (tuple, list)): + for obj in data: + device = find_device(obj) + if device is not None: + return device + elif isinstance(data, torch.Tensor): + return data.device + + +@contextmanager +def GatheredParameters(params, modifier_rank=None, fwd_module=None, enabled=True): + """ + Wrapper around `deepspeed.runtime.zero.GatheredParameters`, but if Zero-3 is not enabled, will be a no-op context + manager. + """ + # We need to use the `AcceleratorState` here since it has access to the deepspeed plugin + if AcceleratorState().distributed_type != DistributedType.DEEPSPEED or ( + AcceleratorState().deepspeed_plugin is not None + and not AcceleratorState().deepspeed_plugin.is_zero3_init_enabled() + ): + gather_param_context = nullcontext() + else: + import deepspeed + + gather_param_context = deepspeed.zero.GatheredParameters( + params, modifier_rank=modifier_rank, fwd_module=fwd_module, enabled=enabled + ) + with gather_param_context: + yield diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/other.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/other.py new file mode 100644 index 0000000000000000000000000000000000000000..a313d08685be25707109c4973b346cdb0a4af90b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/other.py @@ -0,0 +1,366 @@ +# 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. + +import collections +import os +import platform +import re +import socket +from contextlib import contextmanager +from functools import partial, reduce +from types import MethodType +from typing import OrderedDict + +import torch +from packaging.version import Version +from safetensors.torch import save_file as safe_save_file + +from ..commands.config.default import write_basic_config # noqa: F401 +from ..logging import get_logger +from ..state import PartialState +from .constants import FSDP_PYTORCH_VERSION +from .dataclasses import DistributedType +from .imports import is_deepspeed_available, is_torch_distributed_available, is_torch_xla_available +from .modeling import id_tensor_storage +from .transformer_engine import convert_model +from .versions import is_torch_version + + +logger = get_logger(__name__) + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + +def is_compiled_module(module): + """ + Check whether the module was compiled with torch.compile() + """ + if is_torch_version("<", "2.0.0") or not hasattr(torch, "_dynamo"): + return False + return isinstance(module, torch._dynamo.eval_frame.OptimizedModule) + + +def extract_model_from_parallel(model, keep_fp32_wrapper: bool = True, recursive: bool = False): + """ + Extract a model from its distributed containers. + + Args: + model (`torch.nn.Module`): + The model to extract. + keep_fp32_wrapper (`bool`, *optional*): + Whether to remove mixed precision hooks from the model. + recursive (`bool`, *optional*, defaults to `False`): + Whether to recursively extract all cases of `module.module` from `model` as well as unwrap child sublayers + recursively, not just the top-level distributed containers. + + Returns: + `torch.nn.Module`: The extracted model. + """ + options = (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel) + + is_compiled = is_compiled_module(model) + if is_compiled: + compiled_model = model + model = model._orig_mod + + if is_deepspeed_available(): + from deepspeed import DeepSpeedEngine + + options += (DeepSpeedEngine,) + + if is_torch_version(">=", FSDP_PYTORCH_VERSION) and is_torch_distributed_available(): + from torch.distributed.fsdp.fully_sharded_data_parallel import FullyShardedDataParallel as FSDP + + options += (FSDP,) + + while isinstance(model, options): + model = model.module + + if recursive: + # This is needed in cases such as using FSDPv2 on XLA + def _recursive_unwrap(module): + # Wrapped modules are standardly wrapped as `module`, similar to the cases earlier + # with DDP, DataParallel, DeepSpeed, and FSDP + if hasattr(module, "module"): + unwrapped_module = _recursive_unwrap(module.module) + else: + unwrapped_module = module + # Next unwrap child sublayers recursively + for name, child in unwrapped_module.named_children(): + setattr(unwrapped_module, name, _recursive_unwrap(child)) + return unwrapped_module + + # Start with top-level + model = _recursive_unwrap(model) + + if not keep_fp32_wrapper: + forward = model.forward + original_forward = model.__dict__.pop("_original_forward", None) + if original_forward is not None: + while hasattr(forward, "__wrapped__"): + forward = forward.__wrapped__ + if forward == original_forward: + break + model.forward = MethodType(forward, model) + if getattr(model, "_converted_to_transformer_engine", False): + convert_model(model, to_transformer_engine=False) + + if is_compiled: + compiled_model._orig_mod = model + model = compiled_model + + return model + + +def wait_for_everyone(): + """ + Introduces a blocking point in the script, making sure all processes have reached this point before continuing. + + + + Make sure all processes will reach this instruction otherwise one of your processes will hang forever. + + + """ + PartialState().wait_for_everyone() + + +def clean_state_dict_for_safetensors(state_dict: dict): + """ + Cleans the state dictionary from a model and removes tensor aliasing if present. + + Args: + state_dict (`dict`): + The state dictionary from a model + """ + ptrs = collections.defaultdict(list) + # When bnb serialization is used, weights in state dict can be strings + for name, tensor in state_dict.items(): + if not isinstance(tensor, str): + ptrs[id_tensor_storage(tensor)].append(name) + + # These are all pointers of tensors with shared memory + shared_ptrs = {ptr: names for ptr, names in ptrs.items() if len(names) > 1} + warn_names = set() + for names in shared_ptrs.values(): + # When not all duplicates have been cleaned, we still remove those keys but put a clear warning. + # If the link between tensors was done at runtime then `from_pretrained` will not get + # the key back leading to random tensor. A proper warning will be shown + # during reload (if applicable), but since the file is not necessarily compatible with + # the config, better show a proper warning. + found_names = [name for name in names if name in state_dict] + warn_names.update(found_names[1:]) + for name in found_names[1:]: + del state_dict[name] + if len(warn_names) > 0: + logger.warning( + f"Removed shared tensor {warn_names} while saving. This should be OK, but check by verifying that you don't receive any warning while reloading", + ) + state_dict = {k: v.contiguous() if isinstance(v, torch.Tensor) else v for k, v in state_dict.items()} + return state_dict + + +def save(obj, f, save_on_each_node: bool = False, safe_serialization: bool = False): + """ + Save the data to disk. Use in place of `torch.save()`. + + Args: + obj: + The data to save + f: + The file (or file-like object) to use to save the data + save_on_each_node (`bool`, *optional*, defaults to `False`): + Whether to only save on the global main process + safe_serialization (`bool`, *optional*, defaults to `False`): + Whether to save `obj` using `safetensors` or the traditional PyTorch way (that uses `pickle`). + """ + # When TorchXLA is enabled, it's necessary to transfer all data to the CPU before saving. + # Another issue arises with `id_tensor_storage`, which treats all XLA tensors as identical. + # If tensors remain on XLA, calling `clean_state_dict_for_safetensors` will result in only + # one XLA tensor remaining. + if PartialState().distributed_type == DistributedType.XLA: + obj = xm._maybe_convert_to_cpu(obj) + # Check if it's a model and remove duplicates + if safe_serialization: + save_func = partial(safe_save_file, metadata={"format": "pt"}) + if isinstance(obj, OrderedDict): + obj = clean_state_dict_for_safetensors(obj) + else: + save_func = torch.save + + if PartialState().is_main_process and not save_on_each_node: + save_func(obj, f) + elif PartialState().is_local_main_process and save_on_each_node: + save_func(obj, f) + + +@contextmanager +def clear_environment(): + """ + A context manager that will temporarily clear environment variables. + + When this context exits, the previous environment variables will be back. + + Example: + + ```python + >>> import os + >>> from accelerate.utils import clear_environment + + >>> os.environ["FOO"] = "bar" + >>> with clear_environment(): + ... print(os.environ) + ... os.environ["FOO"] = "new_bar" + ... print(os.environ["FOO"]) + {} + new_bar + + >>> print(os.environ["FOO"]) + bar + ``` + """ + _old_os_environ = os.environ.copy() + os.environ.clear() + + try: + yield + finally: + os.environ.clear() # clear any added keys, + os.environ.update(_old_os_environ) # then restore previous environment + + +@contextmanager +def patch_environment(**kwargs): + """ + A context manager that will add each keyword argument passed to `os.environ` and remove them when exiting. + + Will convert the values in `kwargs` to strings and upper-case all the keys. + + Example: + + ```python + >>> import os + >>> from accelerate.utils import patch_environment + + >>> with patch_environment(FOO="bar"): + ... print(os.environ["FOO"]) # prints "bar" + >>> print(os.environ["FOO"]) # raises KeyError + ``` + """ + existing_vars = {} + for key, value in kwargs.items(): + key = key.upper() + if key in os.environ: + existing_vars[key] = os.environ[key] + os.environ[key] = str(value) + + try: + yield + finally: + for key in kwargs: + key = key.upper() + if key in existing_vars: + # restore previous value + os.environ[key] = existing_vars[key] + else: + os.environ.pop(key, None) + + +def get_pretty_name(obj): + """ + Gets a pretty name from `obj`. + """ + if not hasattr(obj, "__qualname__") and not hasattr(obj, "__name__"): + obj = getattr(obj, "__class__", obj) + if hasattr(obj, "__qualname__"): + return obj.__qualname__ + if hasattr(obj, "__name__"): + return obj.__name__ + return str(obj) + + +def merge_dicts(source, destination): + """ + Recursively merges two dictionaries. + + Args: + source (`dict`): The dictionary to merge into `destination`. + destination (`dict`): The dictionary to merge `source` into. + """ + for key, value in source.items(): + if isinstance(value, dict): + node = destination.setdefault(key, {}) + merge_dicts(value, node) + else: + destination[key] = value + + return destination + + +def is_port_in_use(port: int = None) -> bool: + """ + Checks if a port is in use on `localhost`. Useful for checking if multiple `accelerate launch` commands have been + run and need to see if the port is already in use. + """ + if port is None: + port = 29500 + with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: + return s.connect_ex(("localhost", port)) == 0 + + +def convert_bytes(size): + "Converts `size` from bytes to the largest possible unit" + for x in ["bytes", "KB", "MB", "GB", "TB"]: + if size < 1024.0: + return f"{round(size, 2)} {x}" + size /= 1024.0 + + return f"{round(size, 2)} PB" + + +def check_os_kernel(): + """Warns if the kernel version is below the recommended minimum on Linux.""" + # see issue #1929 + info = platform.uname() + system = info.system + if system != "Linux": + return + + _, version, *_ = re.split(r"(\d+\.\d+\.\d+)", info.release) + min_version = "5.5.0" + if Version(version) < Version(min_version): + msg = ( + f"Detected kernel version {version}, which is below the recommended minimum of {min_version}; this can " + "cause the process to hang. It is recommended to upgrade the kernel to the minimum version or higher." + ) + logger.warning(msg, main_process_only=True) + + +def recursive_getattr(obj, attr: str): + """ + Recursive `getattr`. + + Args: + obj: + A class instance holding the attribute. + attr (`str`): + The attribute that is to be retrieved, e.g. 'attribute1.attribute2'. + """ + + def _getattr(obj, attr): + return getattr(obj, attr) + + return reduce(_getattr, [obj] + attr.split(".")) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/random.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/random.py new file mode 100644 index 0000000000000000000000000000000000000000..cf6e8f4444f7a17510aa55e74cdf997aceb5a3ce --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/random.py @@ -0,0 +1,132 @@ +# 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. + +import random +from typing import List, Optional, Union + +import numpy as np +import torch + +from ..state import AcceleratorState +from .constants import CUDA_DISTRIBUTED_TYPES +from .dataclasses import DistributedType, RNGType +from .imports import is_mlu_available, is_musa_available, is_npu_available, is_torch_xla_available, is_xpu_available + + +if is_torch_xla_available(): + import torch_xla.core.xla_model as xm + + +def set_seed(seed: int, device_specific: bool = False, deterministic: bool = False): + """ + Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch`. + + Args: + seed (`int`): + The seed to set. + device_specific (`bool`, *optional*, defaults to `False`): + Whether to differ the seed on each device slightly with `self.process_index`. + deterministic (`bool`, *optional*, defaults to `False`): + Whether to use deterministic algorithms where available. Can slow down training. + """ + if device_specific: + seed += AcceleratorState().process_index + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + if is_xpu_available(): + torch.xpu.manual_seed_all(seed) + elif is_npu_available(): + torch.npu.manual_seed_all(seed) + elif is_mlu_available(): + torch.mlu.manual_seed_all(seed) + elif is_musa_available(): + torch.musa.manual_seed_all(seed) + else: + torch.cuda.manual_seed_all(seed) + # ^^ safe to call this function even if cuda is not available + if is_torch_xla_available(): + xm.set_rng_state(seed) + + if deterministic: + torch.use_deterministic_algorithms(True) + + +def synchronize_rng_state(rng_type: Optional[RNGType] = None, generator: Optional[torch.Generator] = None): + # Get the proper rng state + if rng_type == RNGType.TORCH: + rng_state = torch.get_rng_state() + elif rng_type == RNGType.CUDA: + rng_state = torch.cuda.get_rng_state() + elif rng_type == RNGType.XLA: + assert is_torch_xla_available(), "Can't synchronize XLA seeds as torch_xla is unavailable." + rng_state = torch.tensor(xm.get_rng_state()) + elif rng_type == RNGType.NPU: + assert is_npu_available(), "Can't synchronize NPU seeds on an environment without NPUs." + rng_state = torch.npu.get_rng_state() + elif rng_type == RNGType.MLU: + assert is_mlu_available(), "Can't synchronize MLU seeds on an environment without MLUs." + rng_state = torch.mlu.get_rng_state() + elif rng_type == RNGType.MUSA: + assert is_musa_available(), "Can't synchronize MUSA seeds on an environment without MUSAs." + rng_state = torch.musa.get_rng_state() + elif rng_type == RNGType.XPU: + assert is_xpu_available(), "Can't synchronize XPU seeds on an environment without XPUs." + rng_state = torch.xpu.get_rng_state() + elif rng_type == RNGType.GENERATOR: + assert generator is not None, "Need a generator to synchronize its seed." + rng_state = generator.get_state() + + # Broadcast the rng state from device 0 to other devices + state = AcceleratorState() + if state.distributed_type == DistributedType.XLA: + rng_state = rng_state.to(xm.xla_device()) + xm.collective_broadcast([rng_state]) + xm.mark_step() + rng_state = rng_state.cpu() + elif ( + state.distributed_type in CUDA_DISTRIBUTED_TYPES + or state.distributed_type == DistributedType.MULTI_MLU + or state.distributed_type == DistributedType.MULTI_MUSA + or state.distributed_type == DistributedType.MULTI_NPU + or state.distributed_type == DistributedType.MULTI_XPU + ): + rng_state = rng_state.to(state.device) + torch.distributed.broadcast(rng_state, 0) + rng_state = rng_state.cpu() + elif state.distributed_type == DistributedType.MULTI_CPU: + torch.distributed.broadcast(rng_state, 0) + + # Set the broadcast rng state + if rng_type == RNGType.TORCH: + torch.set_rng_state(rng_state) + elif rng_type == RNGType.CUDA: + torch.cuda.set_rng_state(rng_state) + elif rng_type == RNGType.NPU: + torch.npu.set_rng_state(rng_state) + elif rng_type == RNGType.MLU: + torch.mlu.set_rng_state(rng_state) + elif rng_type == RNGType.MUSA: + torch.musa.set_rng_state(rng_state) + elif rng_type == RNGType.XPU: + torch.xpu.set_rng_state(rng_state) + elif rng_type == RNGType.XLA: + xm.set_rng_state(rng_state.item()) + elif rng_type == RNGType.GENERATOR: + generator.set_state(rng_state) + + +def synchronize_rng_states(rng_types: List[Union[str, RNGType]], generator: Optional[torch.Generator] = None): + for rng_type in rng_types: + synchronize_rng_state(RNGType(rng_type), generator=generator) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/rich.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/rich.py new file mode 100644 index 0000000000000000000000000000000000000000..2d48661b7fcef92ef1168b74cc275c6d3ccc67a1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/rich.py @@ -0,0 +1,24 @@ +# 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. + +from .imports import is_rich_available + + +if is_rich_available(): + from rich.traceback import install + + install(show_locals=False) + +else: + raise ModuleNotFoundError("To use the rich extension, install rich with `pip install rich`") diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/torch_xla.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/torch_xla.py new file mode 100644 index 0000000000000000000000000000000000000000..140133926c2f88d39c70f5a9f46a08f88bed36da --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/torch_xla.py @@ -0,0 +1,51 @@ +# 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. + +import importlib.metadata +import subprocess +import sys + + +def install_xla(upgrade: bool = False): + """ + Helper function to install appropriate xla wheels based on the `torch` version in Google Colaboratory. + + Args: + upgrade (`bool`, *optional*, defaults to `False`): + Whether to upgrade `torch` and install the latest `torch_xla` wheels. + + Example: + + ```python + >>> from accelerate.utils import install_xla + + >>> install_xla(upgrade=True) + ``` + """ + in_colab = False + if "IPython" in sys.modules: + in_colab = "google.colab" in str(sys.modules["IPython"].get_ipython()) + + if in_colab: + if upgrade: + torch_install_cmd = ["pip", "install", "-U", "torch"] + subprocess.run(torch_install_cmd, check=True) + # get the current version of torch + torch_version = importlib.metadata.version("torch") + torch_version_trunc = torch_version[: torch_version.rindex(".")] + xla_wheel = f"https://storage.googleapis.com/tpu-pytorch/wheels/colab/torch_xla-{torch_version_trunc}-cp37-cp37m-linux_x86_64.whl" + xla_install_cmd = ["pip", "install", xla_wheel] + subprocess.run(xla_install_cmd, check=True) + else: + raise RuntimeError("`install_xla` utility works only on google colab.") diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/tqdm.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/tqdm.py new file mode 100644 index 0000000000000000000000000000000000000000..1771366c84d5a1f5d07489d19de77a17c97dbd89 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/tqdm.py @@ -0,0 +1,47 @@ +# 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. + +import warnings + +from .imports import is_tqdm_available + + +if is_tqdm_available(): + from tqdm.auto import tqdm as _tqdm + +from ..state import PartialState + + +def tqdm(*args, main_process_only: bool = True, **kwargs): + """ + Wrapper around `tqdm.tqdm` that optionally displays only on the main process. + + Args: + main_process_only (`bool`, *optional*): + Whether to display the progress bar only on the main process + """ + if not is_tqdm_available(): + raise ImportError("Accelerate's `tqdm` module requires `tqdm` to be installed. Please run `pip install tqdm`.") + if len(args) > 0 and isinstance(args[0], bool): + warnings.warn( + f"Passing `{args[0]}` as the first argument to Accelerate's `tqdm` wrapper is deprecated " + "and will be removed in v0.33.0. Please use the `main_process_only` keyword argument instead.", + FutureWarning, + ) + main_process_only = args[0] + args = args[1:] + disable = kwargs.pop("disable", False) + if main_process_only and not disable: + disable = PartialState().local_process_index != 0 + return _tqdm(*args, **kwargs, disable=disable) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/transformer_engine.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/transformer_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..0899c463de42cc9e8adf3c842b2cc6fa49b5050f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/transformer_engine.py @@ -0,0 +1,139 @@ +# 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. + +from types import MethodType + +import torch.nn as nn + +from .imports import is_fp8_available +from .operations import GatheredParameters + + +# Do not import `transformer_engine` at package level to avoid potential issues + + +def convert_model(model, to_transformer_engine=True, _convert_linear=True, _convert_ln=True): + """ + Recursively converts the linear and layernorm layers of a model to their `transformers_engine` counterpart. + """ + if not is_fp8_available(): + raise ImportError("Using `convert_model` requires transformer_engine to be installed.") + import transformer_engine.pytorch as te + + for name, module in model.named_children(): + if isinstance(module, nn.Linear) and to_transformer_engine and _convert_linear: + has_bias = module.bias is not None + params_to_gather = [module.weight] + if has_bias: + params_to_gather.append(module.bias) + + with GatheredParameters(params_to_gather, modifier_rank=0): + if any(p % 16 != 0 for p in module.weight.shape): + return + te_module = te.Linear( + module.in_features, module.out_features, bias=has_bias, params_dtype=module.weight.dtype + ) + te_module.weight.copy_(module.weight) + if has_bias: + te_module.bias.copy_(module.bias) + + setattr(model, name, te_module) + # Note: @xrsrke (Phuc) found that te.LayerNorm doesn't have any real memory savings or speedups over nn.LayerNorm + elif isinstance(module, nn.LayerNorm) and to_transformer_engine and _convert_ln: + with GatheredParameters([module.weight, module.bias], modifier_rank=0): + te_module = te.LayerNorm(module.normalized_shape[0], eps=module.eps, params_dtype=module.weight.dtype) + te_module.weight.copy_(module.weight) + te_module.bias.copy_(module.bias) + + setattr(model, name, te_module) + elif isinstance(module, te.Linear) and not to_transformer_engine and _convert_linear: + has_bias = module.bias is not None + new_module = nn.Linear( + module.in_features, module.out_features, bias=has_bias, params_dtype=module.weight.dtype + ) + new_module.weight.copy_(module.weight) + if has_bias: + new_module.bias.copy_(module.bias) + + setattr(model, name, new_module) + elif isinstance(module, te.LayerNorm) and not to_transformer_engine and _convert_ln: + new_module = nn.LayerNorm(module.normalized_shape[0], eps=module.eps, params_dtype=module.weight.dtype) + new_module.weight.copy_(module.weight) + new_module.bias.copy_(module.bias) + + setattr(model, name, new_module) + else: + convert_model( + module, + to_transformer_engine=to_transformer_engine, + _convert_linear=_convert_linear, + _convert_ln=_convert_ln, + ) + + +def has_transformer_engine_layers(model): + """ + Returns whether a given model has some `transformer_engine` layer or not. + """ + if not is_fp8_available(): + raise ImportError("Using `has_transformer_engine_layers` requires transformer_engine to be installed.") + import transformer_engine.pytorch as te + + for m in model.modules(): + if isinstance(m, (te.LayerNorm, te.Linear, te.TransformerLayer)): + return True + return False + + +def contextual_fp8_autocast(model_forward, fp8_recipe, use_during_eval=False): + """ + Wrapper for a model's forward method to apply FP8 autocast. Is context aware, meaning that by default it will + disable FP8 autocast during eval mode, which is generally better for more accurate metrics. + """ + if not is_fp8_available(): + raise ImportError("Using `contextual_fp8_autocast` requires transformer_engine to be installed.") + from transformer_engine.pytorch import fp8_autocast + + def forward(self, *args, **kwargs): + enabled = use_during_eval or self.training + with fp8_autocast(enabled=enabled, fp8_recipe=fp8_recipe): + return model_forward(*args, **kwargs) + + # To act like a decorator so that it can be popped when doing `extract_model_from_parallel` + forward.__wrapped__ = model_forward + + return forward + + +def apply_fp8_autowrap(model, fp8_recipe_handler): + """ + Applies FP8 context manager to the model's forward method + """ + if not is_fp8_available(): + raise ImportError("Using `apply_fp8_autowrap` requires transformer_engine to be installed.") + import transformer_engine.common.recipe as te_recipe + + kwargs = fp8_recipe_handler.to_kwargs() if fp8_recipe_handler is not None else {} + if "fp8_format" in kwargs: + kwargs["fp8_format"] = getattr(te_recipe.Format, kwargs["fp8_format"]) + use_during_eval = kwargs.pop("use_autocast_during_eval", False) + fp8_recipe = te_recipe.DelayedScaling(**kwargs) + new_forward = contextual_fp8_autocast(model.forward, fp8_recipe, use_during_eval) + + if hasattr(model.forward, "__func__"): + model.forward = MethodType(new_forward, model) + else: + model.forward = new_forward + + return model diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/versions.py b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/versions.py new file mode 100644 index 0000000000000000000000000000000000000000..985c918f0e057bacc70c372f6906071bb73db577 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/src/accelerate/utils/versions.py @@ -0,0 +1,56 @@ +# 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. + +import importlib.metadata +from typing import Union + +from packaging.version import Version, parse + +from .constants import STR_OPERATION_TO_FUNC + + +torch_version = parse(importlib.metadata.version("torch")) + + +def compare_versions(library_or_version: Union[str, Version], operation: str, requirement_version: str): + """ + Compares a library version to some requirement using a given operation. + + Args: + library_or_version (`str` or `packaging.version.Version`): + A library name or a version to check. + operation (`str`): + A string representation of an operator, such as `">"` or `"<="`. + requirement_version (`str`): + The version to compare the library version against + """ + if operation not in STR_OPERATION_TO_FUNC.keys(): + raise ValueError(f"`operation` must be one of {list(STR_OPERATION_TO_FUNC.keys())}, received {operation}") + operation = STR_OPERATION_TO_FUNC[operation] + if isinstance(library_or_version, str): + library_or_version = parse(importlib.metadata.version(library_or_version)) + return operation(library_or_version, parse(requirement_version)) + + +def is_torch_version(operation: str, version: str): + """ + Compares the current PyTorch version to a given reference with an operation. + + Args: + operation (`str`): + A string representation of an operator, such as `">"` or `"<="` + version (`str`): + A string version of PyTorch + """ + return compare_versions(torch_version, operation, version) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/utils/log_reports.py b/tasks/tasksmith-5d12db5414d2/environment/source/utils/log_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..151643e2d78add8613a49022c34c44467fc8120b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/utils/log_reports.py @@ -0,0 +1,177 @@ +# 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. +import json +import os +from datetime import date +from pathlib import Path + +from tabulate import DataRow, TableFormat, tabulate + + +hf_table_format = TableFormat( + lineabove=None, + linebelowheader=None, + linebetweenrows=None, + linebelow=None, + headerrow=DataRow("", "|", "|"), + datarow=DataRow("", "|", "|"), + padding=1, + with_header_hide=None, +) + + +failed = [] +group_info = [] + +no_error_payload = {"type": "section", "text": {"type": "plain_text", "text": "No failed tests! 🤗", "emoji": True}} + +payload = [ + { + "type": "header", + "text": { + "type": "plain_text", + "text": f"🤗 Accelerate nightly {os.environ.get('TEST_TYPE', '')} test results", + "emoji": True, + }, + } +] + +total_num_failed = 0 +for log in Path().glob("*.log"): + section_num_failed = 0 + with open(log) as f: + for line in f: + line = json.loads(line) + if line.get("nodeid", "") != "": + test = line["nodeid"] + if line.get("duration", None) is not None: + duration = f'{line["duration"]:.4f}' + if line.get("outcome", "") == "failed": + section_num_failed += 1 + failed.append([test, duration, log.name.split("_")[0]]) + total_num_failed += 1 + group_info.append([str(log), section_num_failed, failed]) + failed = [] + log.unlink() + +message = "" +all_files2failed = [] +if total_num_failed > 0: + for name, num_failed, failed_tests in group_info: + if num_failed > 0: + if num_failed == 1: + message += f"*{name[1:]}: {num_failed} failed test*\n" + else: + message += f"*{name[1:]}: {num_failed} failed tests*\n" + failed_table = [] + files2failed = {} + for test in failed_tests: + data = test[0].split("::") + data[0] = data[0].split("/")[-1] + if data[0] not in files2failed: + files2failed[data[0]] = [data[1:]] + else: + files2failed[data[0]] += [data[1:]] + failed_table.append(data) + + files = [test[0] for test in failed_table] + individual_files = list(set(files)) + # Count number of instances in failed_tests + table = [] + for file in individual_files: + table.append([file, len(files2failed[file])]) + + failed_table = tabulate( + table, + headers=["Test Location", "Num Failed"], + tablefmt=hf_table_format, + stralign="right", + ) + message += f"\n```\n{failed_table}\n```" + all_files2failed.append(files2failed) + if len(message) > 3000: + err = "Too many failed tests, please see the full report in the Action results." + offset = len(err) + 10 + message = message[: 3000 - offset] + f"\n...\n```\n{err}" + print(f"### {message}") +else: + message = "No failed tests! 🤗" + print(f"## {message}") + payload.append(no_error_payload) + +if os.environ.get("TEST_TYPE", "") != "": + from slack_sdk import WebClient + + client = WebClient(token=os.environ["SLACK_API_TOKEN"]) + if message != "No failed tests! 🤗": + md_report = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": message, + }, + } + payload.append(md_report) + action_button = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": "*For more details:*", + }, + "accessory": { + "type": "button", + "text": { + "type": "plain_text", + "text": "Check Action results", + "emoji": True, + }, + "url": f'https://github.com/{os.environ["GITHUB_REPOSITORY"]}/actions/runs/{os.environ["GITHUB_RUN_ID"]}', + }, + } + payload.append(action_button) + date_report = { + "type": "context", + "elements": [ + { + "type": "plain_text", + "text": f"Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}", + } + ], + } + payload.append(date_report) + response = client.chat_postMessage(channel="#accelerate-ci-daily", text=message, blocks=payload) + ts = response.data["ts"] + for failed_file in all_files2failed: + for test_location, test_failures in failed_file.items(): + # Keep only the first instance of the test name + test_class = "" + for i, row in enumerate(test_failures): + if row[0] != test_class: + test_class = row[0] + else: + test_failures[i][0] = "" + + payload = { + "type": "section", + "text": { + "type": "mrkdwn", + "text": f"Test location: {test_location}\n```\n{tabulate(test_failures, headers=['Class', 'Test'], tablefmt=hf_table_format, stralign='right')}\n```", + }, + } + + client.chat_postMessage( + channel="#accelerate-ci-daily", + thread_ts=ts, + blocks=[payload], + ) diff --git a/tasks/tasksmith-5d12db5414d2/environment/source/utils/stale.py b/tasks/tasksmith-5d12db5414d2/environment/source/utils/stale.py new file mode 100644 index 0000000000000000000000000000000000000000..24333fed4c76b34cf895f30a253a9a7042f9d324 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/environment/source/utils/stale.py @@ -0,0 +1,69 @@ +# Copyright 2022 The HuggingFace Team, the AllenNLP library authors. 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. +""" +Script to close stale issue. Taken in part from the AllenNLP repository. +https://github.com/allenai/allennlp. +""" + +import os +from datetime import datetime as dt +from datetime import timezone + +from github import Github + + +LABELS_TO_EXEMPT = [ + "good first issue", + "feature request", + "wip", +] + + +def main(): + g = Github(os.environ["GITHUB_TOKEN"]) + repo = g.get_repo("huggingface/accelerate") + open_issues = repo.get_issues(state="open") + + for issue in open_issues: + comments = sorted([comment for comment in issue.get_comments()], key=lambda i: i.created_at, reverse=True) + last_comment = comments[0] if len(comments) > 0 else None + current_time = dt.now(timezone.utc) + days_since_updated = (current_time - issue.updated_at).days + days_since_creation = (current_time - issue.created_at).days + if ( + last_comment is not None + and last_comment.user.login == "github-actions[bot]" + and days_since_updated > 7 + and days_since_creation >= 30 + and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) + ): + # Close issue since it has been 7 days of inactivity since bot mention. + issue.edit(state="closed") + elif ( + days_since_updated > 23 + and days_since_creation >= 30 + and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) + ): + # Add stale comment + issue.create_comment( + "This issue has been automatically marked as stale because it has not had " + "recent activity. If you think this still needs to be addressed " + "please comment on this thread.\n\nPlease note that issues that do not follow the " + "[contributing guidelines](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md) " + "are likely to be ignored." + ) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/instruction.md b/tasks/tasksmith-5d12db5414d2/instruction.md new file mode 100644 index 0000000000000000000000000000000000000000..cb63bb19e65bbf04eec75e4857cf5cd9bd363ebf --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/instruction.md @@ -0,0 +1,7 @@ +Fix a regression in `FullyShardedDataParallelPlugin.set_auto_wrap_policy`: transformer-based auto-wrapping can attempt to resolve individual characters instead of layer class names from a model's `_no_split_modules` metadata. When no explicit `transformer_cls_names_to_wrap` is supplied, the policy should wrap instances of every class named by that metadata, and no unrelated classes. If the model has no such metadata and no explicit classes are supplied, policy setup should succeed without selecting any classes to wrap. + +**Example that must work:** a model with `_no_split_modules = ["MyTransformerBlock"]` passed to `set_auto_wrap_policy` with `transformer_cls_names_to_wrap=None` should resolve `"MyTransformerBlock"` as the class to wrap and produce a `functools.partial` as `auto_wrap_policy`. It must **not** attempt to look up individual characters such as `'M'`, `'y'`, etc. + +**Example that must still work:** when `transformer_cls_names_to_wrap` is already set explicitly, `_no_split_modules` is ignored and the explicit value is used. + +Work in `/workspace`. Submit your fix in the existing Python source files under `src/accelerate`. Preserve the other public behavior. The environment is offline; dependencies are preinstalled. Grading runs the relevant repository tests in a fresh environment, using your submitted source files. diff --git a/tasks/tasksmith-5d12db5414d2/solution/reference/src/accelerate/utils/dataclasses.py b/tasks/tasksmith-5d12db5414d2/solution/reference/src/accelerate/utils/dataclasses.py new file mode 100644 index 0000000000000000000000000000000000000000..0cb6c59dd9ac1d98757c2e7033f0e0f1c8783cba --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/solution/reference/src/accelerate/utils/dataclasses.py @@ -0,0 +1,2217 @@ +# 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. + +""" +General namespace and dataclass related classes +""" + +import argparse +import copy +import enum +import functools +import os +import warnings +from contextlib import contextmanager +from dataclasses import dataclass, field +from datetime import timedelta +from typing import Any, Callable, Dict, Iterable, List, Literal, Optional, Tuple, Union, get_args + +import torch + +from .constants import FSDP_AUTO_WRAP_POLICY, FSDP_BACKWARD_PREFETCH, FSDP_SHARDING_STRATEGY +from .environment import parse_flag_from_env, str_to_bool +from .imports import ( + is_cuda_available, + is_mlu_available, + is_msamp_available, + is_npu_available, + is_transformer_engine_available, + is_xpu_available, +) +from .versions import compare_versions + + +class KwargsHandler: + """ + Internal mixin that implements a `to_kwargs()` method for a dataclass. + """ + + def to_dict(self): + return copy.deepcopy(self.__dict__) + + def to_kwargs(self): + """ + Returns a dictionary containing the attributes with values different from the default of this class. + """ + # import clear_environment here to avoid circular import problem + from .other import clear_environment + + with clear_environment(): + default_dict = self.__class__().to_dict() + this_dict = self.to_dict() + return {k: v for k, v in this_dict.items() if default_dict[k] != v} + + +class EnumWithContains(enum.EnumMeta): + "A metaclass that adds the ability to check if `self` contains an item with the `in` operator" + + def __contains__(cls, item): + try: + cls(item) + except ValueError: + return False + return True + + +class BaseEnum(enum.Enum, metaclass=EnumWithContains): + "An enum class that can get the value of an item with `str(Enum.key)`" + + def __str__(self): + return self.value + + @classmethod + def list(cls): + "Method to list all the possible items in `cls`" + return list(map(str, cls)) + + +@dataclass +class AutocastKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize how `torch.autocast` behaves. Please refer to the + documentation of this [context manager](https://pytorch.org/docs/stable/amp.html#torch.autocast) for more + information on each argument. + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import AutocastKwargs + + kwargs = AutocastKwargs(cache_enabled=True) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + enabled: bool = True + cache_enabled: bool = None + + +class DDPCommunicationHookType(BaseEnum): + """ + Represents a type of communication hook used in DDP. + + Values: + + - **NO** -- no communication hook + - **FP16** -- DDP communication hook to compress the gradients in FP16 + - **BF16** -- DDP communication hook to compress the gradients in BF16 + - **POWER_SGD** -- DDP communication hook to use PowerSGD + - **BATCHED_POWER_SGD** -- DDP communication hook to use batched PowerSGD + """ + + NO = "no" + FP16 = "fp16" + BF16 = "bf16" + POWER_SGD = "power_sgd" + BATCHED_POWER_SGD = "batched_power_sgd" + + +@dataclass +class DistributedDataParallelKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize how your model is wrapped in a + `torch.nn.parallel.DistributedDataParallel`. Please refer to the documentation of this + [wrapper](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html) for more + information on each argument. + + + + `gradient_as_bucket_view` is only available in PyTorch 1.7.0 and later versions. + + `static_graph` is only available in PyTorch 1.11.0 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import DistributedDataParallelKwargs + + kwargs = DistributedDataParallelKwargs(find_unused_parameters=True) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + dim: int = 0 + broadcast_buffers: bool = True + bucket_cap_mb: int = 25 + find_unused_parameters: bool = False + check_reduction: bool = False + gradient_as_bucket_view: bool = False + static_graph: bool = False + + comm_hook: DDPCommunicationHookType = DDPCommunicationHookType.NO + comm_wrapper: Literal[ + DDPCommunicationHookType.NO, DDPCommunicationHookType.FP16, DDPCommunicationHookType.BF16 + ] = DDPCommunicationHookType.NO + comm_state_option: dict = field(default_factory=dict) + + def to_dict(self, ignore_keys=("comm_hook", "comm_wrapper", "comm_state_option")): + return {k: v for k, v in super().to_dict().items() if k not in ignore_keys} + + def register_comm_hook(self, model): + from torch.distributed.algorithms.ddp_comm_hooks import default_hooks, powerSGD_hook + + hook_map: Dict[DDPCommunicationHookType, Callable] = { + DDPCommunicationHookType.FP16: default_hooks.fp16_compress_hook, + DDPCommunicationHookType.BF16: default_hooks.bf16_compress_hook, + DDPCommunicationHookType.POWER_SGD: powerSGD_hook.powerSGD_hook, + DDPCommunicationHookType.BATCHED_POWER_SGD: powerSGD_hook.batched_powerSGD_hook, + } + + wrapper_map: Dict[DDPCommunicationHookType, Callable] = { + DDPCommunicationHookType.FP16: default_hooks.fp16_compress_wrapper, + DDPCommunicationHookType.BF16: default_hooks.bf16_compress_wrapper, + } + + hook: Optional[Callable] = hook_map.get(self.comm_hook) + wrapper: Optional[Callable] = wrapper_map.get(self.comm_wrapper) + + if hook and wrapper: + hook = wrapper(hook) + + if hook: + state = ( + powerSGD_hook.PowerSGDState(None, **self.comm_state_option) + if self.comm_hook in (DDPCommunicationHookType.POWER_SGD, DDPCommunicationHookType.BATCHED_POWER_SGD) + else None + ) + model.register_comm_hook( + state=state, + hook=hook, + ) + + +@dataclass +class GradScalerKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the behavior of mixed precision, specifically how the + `torch.cuda.amp.GradScaler` used is created. Please refer to the documentation of this + [scaler](https://pytorch.org/docs/stable/amp.html?highlight=gradscaler) for more information on each argument. + + + + `GradScaler` is only available in PyTorch 1.5.0 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import GradScalerKwargs + + kwargs = GradScalerKwargs(backoff_filter=0.25) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + init_scale: float = 65536.0 + growth_factor: float = 2.0 + backoff_factor: float = 0.5 + growth_interval: int = 2000 + enabled: bool = True + + +@dataclass +class InitProcessGroupKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the distributed processes. Please refer + to the documentation of this + [method](https://pytorch.org/docs/stable/distributed.html#torch.distributed.init_process_group) for more + information on each argument. + + Note: If `timeout` is set to `None`, the default will be based upon how `backend` is set. + + ```python + from datetime import timedelta + from accelerate import Accelerator + from accelerate.utils import InitProcessGroupKwargs + + kwargs = InitProcessGroupKwargs(timeout=timedelta(seconds=800)) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + """ + + backend: Optional[str] = "nccl" + init_method: Optional[str] = None + timeout: Optional[timedelta] = None + + def __post_init__(self): + if self.timeout is None: + seconds = 1800 if self.backend != "nccl" else 600 + self.timeout = timedelta(seconds=seconds) + + +# Literals +Backend = Literal["MSAMP", "TE"] +OptLevel = Literal["O1", "O2"] +FP8Format = Literal["E4M3", "HYBRID"] +AmaxComputeAlgorithm = Literal["max", "most_recent"] + + +@dataclass +class FP8RecipeKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the recipe for FP8 mixed precision + training with `transformer-engine` or `ms-amp`. + + + + For more information on `transformer-engine` args, please refer to the API + [documentation](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/api/common.html). + + For more information on the `ms-amp` args, please refer to the Optimization Level + [documentation](https://azure.github.io/MS-AMP/docs/user-tutorial/optimization-level). + + + + ```python + from accelerate import Accelerator + from accelerate.utils import FP8RecipeKwargs + + kwargs = FP8RecipeKwargs(backend="te", fp8_format="HYBRID") + accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=[kwargs]) + ``` + + To use MS-AMP as an engine, pass `backend="msamp"` and the `optimization_level`: + + ```python + kwargs = FP8RecipeKwargs(backend="msamp", optimization_level="02") + ``` + + Args: + backend (`str`, *optional*): + Which FP8 engine to use. Must be one of `"msamp"` (MS-AMP) or `"te"` (TransformerEngine). If not passed, + will use whichever is available in the environment, prioritizing MS-AMP. + use_autocast_during_eval (`bool`, *optional*, default to `False`): + Whether to use FP8 autocast during eval mode. Generally better metrics are found when this is `False`. + margin (`int`, *optional*, default to 0): + The margin to use for the gradient scaling. + interval (`int`, *optional*, default to 1): + The interval to use for how often the scaling factor is recomputed. + fp8_format (`str`, *optional*, default to "HYBRID"): + The format to use for the FP8 recipe. Must be one of `HYBRID` or `E4M3`. (Generally `HYBRID` for training, + `E4M3` for evaluation) + amax_history_len (`int`, *optional*, default to 1024): + The length of the history to use for the scaling factor computation + amax_compute_algo (`str`, *optional*, default to "most_recent"): + The algorithm to use for the scaling factor computation. Must be one of `max` or `most_recent`. + override_linear_precision (`tuple` of three `bool`, *optional*, default to `(False, False, False)`): + Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. + optimization_level (`str`), one of `O1`, `O2`. (default is `O2`): + What level of 8-bit collective communication should be used with MS-AMP. In general: + * O1: Weight gradients and `all_reduce` communications are done in fp8, reducing GPU + memory usage and communication bandwidth + * O2: First-order optimizer states are in 8-bit, and second order states are in FP16. + Only available when using Adam or AdamW. This maintains accuracy and can potentially save the + highest memory. + * 03: Specifically for DeepSpeed, implements capabilities so weights and master weights of models + are stored in FP8. If `fp8` is selected and deepspeed is enabled, will be used by default. (Not + available currently). + """ + + backend: Backend = None + use_autocast_during_eval: bool = None + opt_level: OptLevel = None + margin: int = None + interval: int = None + fp8_format: FP8Format = None + amax_history_len: int = None + amax_compute_algo: AmaxComputeAlgorithm = None + override_linear_precision: Tuple[bool, bool, bool] = None + + def __post_init__(self): + env_prefix = "ACCELERATE_FP8_" + default_backend = "msamp" if is_msamp_available() else "te" + if self.backend is None: + self.backend = os.environ.get(env_prefix + "BACKEND", default_backend) + self.backend = self.backend.upper() + if self.backend not in get_args(Backend): + raise ValueError("`backend` must be 'MSAMP' or 'TE' (TransformerEngine).") + # Check TE args + if self.backend == "TE": + if not is_transformer_engine_available(): + raise ValueError( + "TransformerEngine is not available. Please either install it, or use the 'MSAMP' backend (if installed)." + ) + if self.use_autocast_during_eval is None: + self.use_autocast_during_eval = parse_flag_from_env(env_prefix + "USE_AUTOCAST_DURING_EVAL") + if self.margin is None: + self.margin = int(os.environ.get(env_prefix + "MARGIN", 0)) + if self.interval is None: + self.interval = int(os.environ.get(env_prefix + "INTERVAL", 1)) + if self.fp8_format is None: + self.fp8_format = os.environ.get(env_prefix + "FORMAT", "HYBRID") + self.fp8_format = self.fp8_format.upper() + if self.fp8_format not in get_args(FP8Format): + raise ValueError(f"`fp8_format` must be one of {' or '.join(get_args(FP8Format))}.") + if self.amax_compute_algo is None: + self.amax_compute_algo = os.environ.get(env_prefix + "AMAX_COMPUTE_ALGO", "most_recent") + self.amax_compute_algo = self.amax_compute_algo.lower() + if self.amax_compute_algo not in get_args(AmaxComputeAlgorithm): + raise ValueError(f"`amax_compute_algo` must be one of {' or '.join(get_args(AmaxComputeAlgorithm))}") + if self.amax_history_len is None: + self.amax_history_len = int(os.environ.get(env_prefix + "AMAX_HISTORY_LEN", 1024)) + if self.override_linear_precision is None: + fprop = parse_flag_from_env(env_prefix + "OVERRIDE_FPROP") + dgrad = parse_flag_from_env(env_prefix + "OVERRIDE_DGRAD") + wgrad = parse_flag_from_env(env_prefix + "OVERRIDE_WGRAD") + self.override_linear_precision = (fprop, dgrad, wgrad) + elif self.backend == "MSAMP": + if not is_msamp_available(): + raise ValueError( + "MS-AMP is not available. Please either install it, or use the 'TE' backend (if installed)." + ) + if self.opt_level is None: + self.opt_level = os.environ.get(env_prefix + "OPT_LEVEL", "O2") + if self.opt_level not in get_args(OptLevel): + raise ValueError(f"`optimization_level` must be one of {' or '.join(get_args(OptLevel))}") + + +# Literal +ProfilerActivity = Literal["cpu", "xpu", "mtia", "cuda"] + + +@dataclass +class ProfileKwargs(KwargsHandler): + """ + Use this object in your [`Accelerator`] to customize the initialization of the profiler. Please refer to the + documentation of this [context manager](https://pytorch.org/docs/stable/profiler.html#torch.profiler.profile) for + more information on each argument. + + + + `torch.profiler` is only available in PyTorch 1.8.1 and later versions. + + + + Example: + + ```python + from accelerate import Accelerator + from accelerate.utils import ProfileKwargs + + kwargs = ProfileKwargs(activities=["cpu", "cuda"]) + accelerator = Accelerator(kwargs_handlers=[kwargs]) + ``` + + Args: + activities (`List[str]`, *optional*, default to `None`): + The list of activity groups to use in profiling. Must be one of `"cpu"`, `"xpu"`, `"mtia"`, or `"cuda"`. + schedule_option (`Dict[str, int]`, *optional*, default to `None`): + The schedule option to use for the profiler. Available keys are `wait`, `warmup`, `active`, `repeat` and + `skip_first`. The profiler will skip the first `skip_first` steps, then wait for `wait` steps, then do the + warmup for the next `warmup` steps, then do the active recording for the next `active` steps and then + repeat the cycle starting with `wait` steps. The optional number of cycles is specified with the `repeat` + parameter, the zero value means that the cycles will continue until the profiling is finished. + on_trace_ready (`Callable`, *optional*, default to `None`): + Callable that is called at each step when schedule returns `ProfilerAction.RECORD_AND_SAVE` during the + profiling. + record_shapes (`bool`, *optional*, default to `False`): + Save information about operator’s input shapes. + profile_memory (`bool`, *optional*, default to `False`): + Track tensor memory allocation/deallocation + with_stack (`bool`, *optional*, default to `False`): + Record source information (file and line number) for the ops. + with_flops (`bool`, *optional*, default to `False`): + Use formula to estimate the FLOPS of specific operators + with_modules (`bool`, *optional*, default to `False`): + Record module hierarchy (including function names) corresponding to the callstack of the op. + output_trace_dir (`str`, *optional*, default to `None`): + Exports the collected trace in Chrome JSON format. Chrome use 'chrome://tracing' view json file. Defaults + to None, which means profiling does not store json files. + """ + + activities: Optional[List[ProfilerActivity]] = None + schedule_option: Optional[Dict[str, int]] = None + on_trace_ready: Optional[Callable] = None + record_shapes: bool = False + profile_memory: bool = False + with_stack: bool = False + with_flops: bool = False + with_modules: bool = False + output_trace_dir: Optional[str] = None + + def _get_profiler_activity(self, activity: ProfilerActivity) -> torch.profiler.ProfilerActivity: + """Get the profiler activity from the string. + + Args: + activity (str): The profiler activity name. + + Returns: + torch.profiler.ProfilerActivity: The profiler activity. + """ + + profiler_activity_map: dict[str, torch.profiler.ProfilerActivity] = { + "cpu": torch.profiler.ProfilerActivity.CPU, + "xpu": torch.profiler.ProfilerActivity.XPU, + "mita": torch.profiler.ProfilerActivity.MTIA, + "cuda": torch.profiler.ProfilerActivity.CUDA, + } + + if activity not in profiler_activity_map: + raise ValueError(f"Invalid profiler activity: {activity}. Must be one of {list(profiler_activity_map)}.") + return profiler_activity_map[activity] + + def build(self) -> torch.profiler.profile: + """ + Build a profiler object with the current configuration. + + Returns: + torch.profiler.profile: The profiler object. + """ + activities: Optional[List[ProfilerActivity]] = None + if self.activities is not None: + activities = [self._get_profiler_activity(activity) for activity in self.activities] + schedule: Optional[torch.profiler.schedule] = None + if self.schedule_option is not None: + schedule = torch.profiler.schedule(**self.schedule_option) + + return torch.profiler.profile( + activities=activities, + schedule=schedule, + on_trace_ready=self.on_trace_ready, + record_shapes=self.record_shapes, + profile_memory=self.profile_memory, + with_stack=self.with_stack, + with_flops=self.with_flops, + with_modules=self.with_modules, + ) + + +class DeprecatedFieldDescriptor: + """ + Descriptor for deprecated fields in an enum class. + + Args: + field_name (`str`): + The name of the deprecated field. + replaced_with (`str`): + The name of the field that replaces the deprecated one. + """ + + def __init__(self, field_name, replaced_with): + self.field_name = field_name + self.replaced_with = replaced_with + + def __get__(self, instance, owner): + warnings.warn( + f"The `{self.field_name}` of `{owner}` is deprecated and will be removed in v1.0.0. " + f"Please use the `{self.replaced_with}` instead.", + FutureWarning, + ) + return getattr(owner, self.replaced_with) + + +class DistributedType(str, enum.Enum): + """ + Represents a type of distributed environment. + + Values: + + - **NO** -- Not a distributed environment, just a single process. + - **MULTI_CPU** -- Distributed on multiple CPU nodes. + - **MULTI_GPU** -- Distributed on multiple GPUs. + - **MULTI_MLU** -- Distributed on multiple MLUs. + - **MULTI_MUSA** -- Distributed on multiple MUSAs. + - **MULTI_NPU** -- Distributed on multiple NPUs. + - **MULTI_XPU** -- Distributed on multiple XPUs. + - **DEEPSPEED** -- Using DeepSpeed. + - **XLA** -- Using TorchXLA. + - **TPU** -- This field will be deprecated in v0.27.0. Use XLA instead. + """ + + # Subclassing str as well as Enum allows the `DistributedType` to be JSON-serializable out of the box. + NO = "NO" + MULTI_CPU = "MULTI_CPU" + MULTI_GPU = "MULTI_GPU" + MULTI_NPU = "MULTI_NPU" + MULTI_MLU = "MULTI_MLU" + MULTI_MUSA = "MULTI_MUSA" + MULTI_XPU = "MULTI_XPU" + DEEPSPEED = "DEEPSPEED" + FSDP = "FSDP" + XLA = "XLA" + MEGATRON_LM = "MEGATRON_LM" + TPU = DeprecatedFieldDescriptor("TPU", "XLA") + + +class SageMakerDistributedType(str, enum.Enum): + """ + Represents a type of distributed environment. + + Values: + + - **NO** -- Not a distributed environment, just a single process. + - **DATA_PARALLEL** -- using sagemaker distributed data parallelism. + - **MODEL_PARALLEL** -- using sagemaker distributed model parallelism. + """ + + # Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box. + NO = "NO" + DATA_PARALLEL = "DATA_PARALLEL" + MODEL_PARALLEL = "MODEL_PARALLEL" + + +class FP8BackendType(str, enum.Enum): + """ + Represents the backend used for FP8. + + Values: + + - **TE** -- using TransformerEngine. + - **MSAMP** -- using msamp. + """ + + # Subclassing str as well as Enum allows the `FP8BackendType` to be JSON-serializable out of the box. + TE = "TE" + MSAMP = "MSAMP" + + +class ComputeEnvironment(str, enum.Enum): + """ + Represents a type of the compute environment. + + Values: + + - **LOCAL_MACHINE** -- private/custom cluster hardware. + - **AMAZON_SAGEMAKER** -- Amazon SageMaker as compute environment. + """ + + # Subclassing str as well as Enum allows the `ComputeEnvironment` to be JSON-serializable out of the box. + LOCAL_MACHINE = "LOCAL_MACHINE" + AMAZON_SAGEMAKER = "AMAZON_SAGEMAKER" + + +class DynamoBackend(str, BaseEnum): + """ + Represents a dynamo backend (see https://pytorch.org/docs/stable/torch.compiler.html). + + Values: + + - **NO** -- Do not use torch dynamo. + - **EAGER** -- Uses PyTorch to run the extracted GraphModule. This is quite useful in debugging TorchDynamo + issues. + - **AOT_EAGER** -- Uses AotAutograd with no compiler, i.e, just using PyTorch eager for the AotAutograd's + extracted forward and backward graphs. This is useful for debugging, and unlikely to give speedups. + - **INDUCTOR** -- Uses TorchInductor backend with AotAutograd and cudagraphs by leveraging codegened Triton + kernels. [Read + more](https://dev-discuss.pytorch.org/t/torchinductor-a-pytorch-native-compiler-with-define-by-run-ir-and-symbolic-shapes/747) + - **AOT_TS_NVFUSER** -- nvFuser with AotAutograd/TorchScript. [Read + more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593) + - **NVPRIMS_NVFUSER** -- nvFuser with PrimTorch. [Read + more](https://dev-discuss.pytorch.org/t/tracing-with-primitives-update-1-nvfuser-and-its-primitives/593) + - **CUDAGRAPHS** -- cudagraphs with AotAutograd. [Read more](https://github.com/pytorch/torchdynamo/pull/757) + - **OFI** -- Uses Torchscript optimize_for_inference. Inference only. [Read + more](https://pytorch.org/docs/stable/generated/torch.jit.optimize_for_inference.html) + - **FX2TRT** -- Uses Nvidia TensorRT for inference optimizations. Inference only. [Read + more](https://github.com/pytorch/TensorRT/blob/master/docsrc/tutorials/getting_started_with_fx_path.rst) + - **ONNXRT** -- Uses ONNXRT for inference on CPU/GPU. Inference only. [Read more](https://onnxruntime.ai/) + - **TENSORRT** -- Uses ONNXRT to run TensorRT for inference optimizations. [Read + more](https://github.com/onnx/onnx-tensorrt) + - **AOT_TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for training. [Read + more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md) + - **TORCHXLA_TRACE_ONCE** -- Uses Pytorch/XLA with TorchDynamo optimization, for inference. [Read + more](https://github.com/pytorch/xla/blob/r2.0/docs/dynamo.md) + - **IPEX** -- Uses IPEX for inference on CPU. Inference only. [Read + more](https://github.com/intel/intel-extension-for-pytorch). + - **TVM** -- Uses Apach TVM for inference optimizations. [Read more](https://tvm.apache.org/) + + """ + + # Subclassing str as well as Enum allows the `SageMakerDistributedType` to be JSON-serializable out of the box. + NO = "NO" + EAGER = "EAGER" + AOT_EAGER = "AOT_EAGER" + INDUCTOR = "INDUCTOR" + AOT_TS_NVFUSER = "AOT_TS_NVFUSER" + NVPRIMS_NVFUSER = "NVPRIMS_NVFUSER" + CUDAGRAPHS = "CUDAGRAPHS" + OFI = "OFI" + FX2TRT = "FX2TRT" + ONNXRT = "ONNXRT" + TENSORRT = "TENSORRT" + AOT_TORCHXLA_TRACE_ONCE = "AOT_TORCHXLA_TRACE_ONCE" + TORCHXLA_TRACE_ONCE = "TORCHXLA_TRACE_ONCE" + IPEX = "IPEX" + TVM = "TVM" + + +class LoggerType(BaseEnum): + """Represents a type of supported experiment tracker + + Values: + + - **ALL** -- all available trackers in the environment that are supported + - **TENSORBOARD** -- TensorBoard as an experiment tracker + - **WANDB** -- wandb as an experiment tracker + - **COMETML** -- comet_ml as an experiment tracker + - **DVCLIVE** -- dvclive as an experiment tracker + """ + + ALL = "all" + AIM = "aim" + TENSORBOARD = "tensorboard" + WANDB = "wandb" + COMETML = "comet_ml" + MLFLOW = "mlflow" + CLEARML = "clearml" + DVCLIVE = "dvclive" + + +class PrecisionType(str, BaseEnum): + """Represents a type of precision used on floating point values + + Values: + + - **NO** -- using full precision (FP32) + - **FP16** -- using half precision + - **BF16** -- using brain floating point precision + """ + + NO = "no" + FP8 = "fp8" + FP16 = "fp16" + BF16 = "bf16" + + +class RNGType(BaseEnum): + TORCH = "torch" + CUDA = "cuda" + MLU = "mlu" + MUSA = "musa" + NPU = "npu" + XLA = "xla" + XPU = "xpu" + GENERATOR = "generator" + + +class CustomDtype(enum.Enum): + r""" + An enum that contains multiple custom dtypes that can be used for `infer_auto_device_map`. + """ + + FP8 = "fp8" + INT4 = "int4" + INT2 = "int2" + + +# data classes + + +@dataclass +class TensorInformation: + shape: torch.Size + dtype: torch.dtype + + +@dataclass +class DataLoaderConfiguration: + """ + Configuration for dataloader-related items when calling `accelerator.prepare`. + """ + + split_batches: bool = field( + default=False, + metadata={ + "help": "Whether or not the accelerator should split the batches yielded by the dataloaders across the devices. If" + " `True` the actual batch size used will be the same on any kind of distributed processes, but it must be a" + " round multiple of the `num_processes` you are using. If `False`, actual batch size used will be the one set" + " in your script multiplied by the number of processes." + }, + ) + dispatch_batches: bool = field( + default=None, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator is only iterated through on the main process" + " and then the batches are split and broadcast to each process. Will default to `True` for `DataLoader` whose" + " underlying dataset is an `IterableDataset`, `False` otherwise." + }, + ) + even_batches: bool = field( + default=True, + metadata={ + "help": "If set to `True`, in cases where the total batch size across all processes does not exactly divide the" + " dataset, samples at the start of the dataset will be duplicated so the batch can be divided equally among" + " all workers." + }, + ) + use_seedable_sampler: bool = field( + default=False, + metadata={ + "help": "Whether or not use a fully seedable random sampler ([`data_loader.SeedableRandomSampler`])." + "Ensures training results are fully reproducable using a different sampling technique. " + "While seed-to-seed results may differ, on average the differences are neglible when using" + "multiple different seeds to compare. Should also be ran with [`~utils.set_seed`] for the best results." + }, + ) + non_blocking: bool = field( + default=False, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator will utilize non-blocking host-to-device" + " transfers, allowing for better overlap between dataloader communication and computation. Recommended that the" + " prepared dataloader has `pin_memory` set to `True` to work properly." + }, + ) + use_stateful_dataloader: bool = field( + default=False, + metadata={ + "help": "If set to `True`, the dataloader prepared by the Accelerator will be backed by " + "[torchdata.StatefulDataLoader](https://github.com/pytorch/data/tree/main/torchdata/stateful_dataloader). This requires `torchdata` version 0.8.0 or higher that supports StatefulDataLoader to be installed." + }, + ) + + +@dataclass +class ProjectConfiguration: + """ + Configuration for the Accelerator object based on inner-project needs. + """ + + project_dir: str = field(default=None, metadata={"help": "A path to a directory for storing data."}) + logging_dir: str = field( + default=None, + metadata={ + "help": "A path to a directory for storing logs of locally-compatible loggers. If None, defaults to `project_dir`." + }, + ) + automatic_checkpoint_naming: bool = field( + default=False, + metadata={"help": "Whether saved states should be automatically iteratively named."}, + ) + + total_limit: int = field( + default=None, + metadata={"help": "The maximum number of total saved states to keep."}, + ) + + iteration: int = field( + default=0, + metadata={"help": "The current save iteration."}, + ) + + save_on_each_node: bool = field( + default=False, + metadata={ + "help": ( + "When doing multi-node distributed training, whether to save models and checkpoints on each node, or" + " only on the main one" + ) + }, + ) + + def set_directories(self, project_dir: str = None): + "Sets `self.project_dir` and `self.logging_dir` to the appropriate values." + self.project_dir = project_dir + if self.logging_dir is None: + self.logging_dir = project_dir + + def __post_init__(self): + self.set_directories(self.project_dir) + + +@dataclass +class GradientAccumulationPlugin(KwargsHandler): + """ + A plugin to configure gradient accumulation behavior. You can only pass one of `gradient_accumulation_plugin` or + `gradient_accumulation_steps` to [`Accelerator`]. Passing both raises an error. + + Parameters: + num_steps (`int`): + The number of steps to accumulate gradients for. + adjust_scheduler (`bool`, *optional*, defaults to `True`): + Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be + `True` if the used scheduler was not adjusted for gradient accumulation. + sync_with_dataloader (`bool`, *optional*, defaults to `True`): + Whether to synchronize setting the gradients when at the end of the dataloader. + sync_each_batch (`bool`, *optional*): + Whether to synchronize setting the gradients at each data batch. Seting to `True` may reduce memory + requirements when using gradient accumulation with distributed training, at expense of speed. + + Example: + + ```python + from accelerate.utils import GradientAccumulationPlugin + + gradient_accumulation_plugin = GradientAccumulationPlugin(num_steps=2) + accelerator = Accelerator(gradient_accumulation_plugin=gradient_accumulation_plugin) + ``` + """ + + num_steps: int = field(default=None, metadata={"help": "The number of steps to accumulate gradients for."}) + adjust_scheduler: bool = field( + default=True, + metadata={ + "help": "Whether to adjust the scheduler steps to account for the number of steps being accumulated. Should be `True` if the used scheduler was not adjusted for gradient accumulation." + }, + ) + sync_with_dataloader: bool = field( + default=True, + metadata={ + "help": "Whether to synchronize setting the gradients when at the end of the dataloader. Should only be set to `False` if you know what you're doing." + }, + ) + sync_each_batch: bool = field( + default=False, + metadata={ + "help": "Whether to synchronize setting the gradients at each data batch. Setting to `True` may reduce memory requirements when using gradient accumulation with distributed training, at expense of speed." + }, + ) + + +@dataclass +class TorchDynamoPlugin(KwargsHandler): + """ + This plugin is used to compile a model with PyTorch 2.0 + """ + + backend: DynamoBackend = field( + default=None, + metadata={"help": f"Possible options are {[b.value.lower() for b in DynamoBackend]}"}, + ) + mode: str = field( + default=None, metadata={"help": "Possible options are 'default', 'reduce-overhead' or 'max-autotune'"} + ) + fullgraph: bool = field(default=None, metadata={"help": "Whether it is ok to break model into several subgraphs"}) + dynamic: bool = field(default=None, metadata={"help": "Whether to use dynamic shape for tracing"}) + options: Any = field(default=None, metadata={"help": "A dictionary of options to pass to the backend."}) + disable: bool = field(default=False, metadata={"help": "Turn torch.compile() into a no-op for testing"}) + + def __post_init__(self): + prefix = "ACCELERATE_DYNAMO_" + if self.backend is None: + self.backend = os.environ.get(prefix + "BACKEND", "no") + self.backend = DynamoBackend(self.backend.upper()) + if self.mode is None: + self.mode = os.environ.get(prefix + "MODE", "default") + if self.fullgraph is None: + self.fullgraph = str_to_bool(os.environ.get(prefix + "USE_FULLGRAPH", "False")) == 1 + if self.dynamic is None: + self.dynamic = str_to_bool(os.environ.get(prefix + "USE_DYNAMIC", "False")) == 1 + + def to_dict(self): + dynamo_config = copy.deepcopy(self.__dict__) + dynamo_config["backend"] = dynamo_config["backend"].value.lower() + return dynamo_config + + +@dataclass +class DeepSpeedPlugin: + """ + This plugin is used to integrate DeepSpeed. + """ + + hf_ds_config: Any = field( + default=None, + metadata={ + "help": "path to DeepSpeed config file or dict or an object of class `accelerate.utils.deepspeed.HfDeepSpeedConfig`." + }, + ) + gradient_accumulation_steps: int = field( + default=None, + metadata={ + "help": "Number of steps to accumulate gradients before updating optimizer states. If not set, will use the value from the `Accelerator` directly." + }, + ) + gradient_clipping: float = field(default=None, metadata={"help": "Enable gradient clipping with value"}) + zero_stage: int = field( + default=None, + metadata={"help": "Possible options are 0,1,2,3; Default will be taken from environment variable"}, + ) + is_train_batch_min: bool = field( + default=True, + metadata={"help": "If both train & eval dataloaders are specified, this will decide the train_batch_size"}, + ) + offload_optimizer_device: str = field( + default=None, + metadata={"help": "Possible options are none|cpu|nvme. Only applicable with ZeRO Stages 2 and 3."}, + ) + offload_param_device: str = field( + default=None, + metadata={"help": "Possible options are none|cpu|nvme. Only applicable with ZeRO Stage 3."}, + ) + offload_optimizer_nvme_path: str = field( + default=None, + metadata={"help": "Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3."}, + ) + offload_param_nvme_path: str = field( + default=None, + metadata={"help": "Possible options are /nvme|/local_nvme. Only applicable with ZeRO Stage 3."}, + ) + zero3_init_flag: bool = field( + default=None, + metadata={ + "help": "Flag to indicate whether to enable `deepspeed.zero.Init` for constructing massive models." + "Only applicable with ZeRO Stage-3." + }, + ) + zero3_save_16bit_model: bool = field( + default=None, + metadata={"help": "Flag to indicate whether to save 16-bit model. Only applicable with ZeRO Stage-3."}, + ) + transformer_moe_cls_names: str = field( + default=None, + metadata={ + "help": "comma-separated list of transformers MoE layer class names (case-sensitive), e.g : " + " `MixtralSparseMoeBlock`, `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` ..." + }, + ) + + def __post_init__(self): + from .deepspeed import HfDeepSpeedConfig + + if self.gradient_accumulation_steps is None: + gas = os.environ.get("ACCELERATE_GRADIENT_ACCUMULATION_STEPS", "auto") + self.gradient_accumulation_steps = int(gas) if gas.isdigit() else gas + + if self.gradient_clipping is None: + gradient_clipping = os.environ.get("ACCELERATE_GRADIENT_CLIPPING", "auto") + self.gradient_clipping = gradient_clipping if gradient_clipping == "auto" else float(gradient_clipping) + + if self.zero_stage is None: + self.zero_stage = int(os.environ.get("ACCELERATE_DEEPSPEED_ZERO_STAGE", 2)) + + if self.offload_optimizer_device is None: + self.offload_optimizer_device = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE", "none") + + if self.offload_param_device is None: + self.offload_param_device = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE", "none") + + if self.offload_optimizer_nvme_path is None: + self.offload_optimizer_nvme_path = os.environ.get( + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH", "none" + ) + + if self.offload_param_nvme_path is None: + self.offload_param_nvme_path = os.environ.get("ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH", "none") + + if self.zero3_save_16bit_model is None: + self.zero3_save_16bit_model = ( + os.environ.get("ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL", "false") == "true" + ) + + if self.hf_ds_config is None: + self.hf_ds_config = os.environ.get("ACCELERATE_DEEPSPEED_CONFIG_FILE", "none") + if ( + isinstance(self.hf_ds_config, dict) + or (isinstance(self.hf_ds_config, str) and self.hf_ds_config != "none") + or isinstance(self.hf_ds_config, HfDeepSpeedConfig) + ): + if not isinstance(self.hf_ds_config, HfDeepSpeedConfig): + self.hf_ds_config = HfDeepSpeedConfig(self.hf_ds_config) + if "gradient_accumulation_steps" not in self.hf_ds_config.config: + self.hf_ds_config.config["gradient_accumulation_steps"] = 1 + if "zero_optimization" not in self.hf_ds_config.config: + raise ValueError("Please specify the ZeRO optimization config in the DeepSpeed config.") + + self._deepspeed_config_checks() + plugin_to_config_mapping = { + "gradient_accumulation_steps": "gradient_accumulation_steps", + "gradient_clipping": "gradient_clipping", + "zero_stage": "zero_optimization.stage", + "offload_optimizer_device": "zero_optimization.offload_optimizer.device", + "offload_param_device": "zero_optimization.offload_param.device", + "offload_param_nvme_path": "zero_optimization.offload_param.nvme_path", + "offload_optimizer_nvme_path": "zero_optimization.offload_optimizer.nvme_path", + "zero3_save_16bit_model": "zero_optimization.stage3_gather_16bit_weights_on_model_save", + } + kwargs = {v: getattr(self, k) for k, v in plugin_to_config_mapping.items() if getattr(self, k) is not None} + for key in kwargs.keys(): + self.fill_match(key, **kwargs, must_match=False) + self.hf_ds_config.set_stage_and_offload() + + # filling the missing values in the class attributes from the DeepSpeed config + # when using the DeepSpeed config file. + for key, value in plugin_to_config_mapping.items(): + config_value = self.hf_ds_config.get_value(value) + if config_value is not None and config_value != "auto": + setattr(self, key, config_value) + else: + config = { + "train_batch_size": "auto", + "train_micro_batch_size_per_gpu": "auto", + "gradient_accumulation_steps": self.gradient_accumulation_steps, + "zero_optimization": { + "stage": self.zero_stage, + "offload_optimizer": { + "device": self.offload_optimizer_device, + "nvme_path": self.offload_optimizer_nvme_path + if self.offload_optimizer_device == "nvme" + else None, + }, + "offload_param": { + "device": self.offload_param_device, + "nvme_path": self.offload_param_nvme_path if self.offload_param_device == "nvme" else None, + }, + "stage3_gather_16bit_weights_on_model_save": self.zero3_save_16bit_model, + }, + } + if self.gradient_clipping: + config["gradient_clipping"] = self.gradient_clipping + self.hf_ds_config = HfDeepSpeedConfig(config) + + self.deepspeed_config = self.hf_ds_config.config + self.deepspeed_config["steps_per_print"] = float("inf") # this will stop deepspeed from logging @ stdout + if self.zero3_init_flag is None: + self.zero3_init_flag = ( + str_to_bool(os.environ.get("ACCELERATE_DEEPSPEED_ZERO3_INIT", str(self.hf_ds_config.is_zero3()))) == 1 + ) + if self.zero3_init_flag and not self.hf_ds_config.is_zero3(): + warnings.warn("DeepSpeed Zero3 Init flag is only applicable for ZeRO Stage 3. Setting it to False.") + self.zero3_init_flag = False + + def fill_match(self, ds_key_long, mismatches=None, must_match=True, **kwargs): + mismatches = [] if mismatches is None else mismatches + config, ds_key = self.hf_ds_config.find_config_node(ds_key_long) + if config is None: + return + + if config.get(ds_key) == "auto": + if ds_key_long in kwargs: + config[ds_key] = kwargs[ds_key_long] + return + else: + raise ValueError( + f"`{ds_key_long}` not found in kwargs. " + f"Please specify `{ds_key_long}` without `auto` (set to correct value) in the DeepSpeed config file or " + "pass it in kwargs." + ) + + if not must_match: + return + + ds_val = config.get(ds_key) + if ds_val is not None and ds_key_long in kwargs: + if ds_val != kwargs[ds_key_long]: + mismatches.append(f"- ds {ds_key_long}={ds_val} vs arg {ds_key_long}={kwargs[ds_key_long]}") + + def is_auto(self, ds_key_long): + val = self.hf_ds_config.get_value(ds_key_long) + if val is None: + return False + else: + return val == "auto" + + def get_value(self, ds_key_long, default=None): + return self.hf_ds_config.get_value(ds_key_long, default) + + def deepspeed_config_process(self, prefix="", mismatches=None, config=None, must_match=True, **kwargs): + """Process the DeepSpeed config with the values from the kwargs.""" + mismatches = [] if mismatches is None else mismatches + if config is None: + config = self.deepspeed_config + for key, value in config.items(): + if isinstance(value, dict): + self.deepspeed_config_process( + prefix=prefix + key + ".", mismatches=mismatches, config=value, must_match=must_match, **kwargs + ) + else: + self.fill_match(prefix + key, mismatches, must_match=must_match, **kwargs) + if len(mismatches) > 0 and prefix == "": + mismatches_msg = "\n".join(mismatches) + raise ValueError( + "Please correct the following DeepSpeed config values that mismatch kwargs " + f" values:\n{mismatches_msg}\nThe easiest method is to set these DeepSpeed config values to 'auto'." + ) + + def set_mixed_precision(self, mixed_precision): + ds_config = self.deepspeed_config + kwargs = { + "fp16.enabled": mixed_precision == "fp16", + # When training in fp8, we still rely on bf16 autocast for the core mixed precision + "bf16.enabled": mixed_precision in ("bf16", "fp8"), + } + if mixed_precision == "fp16": + if "fp16" not in ds_config: + ds_config["fp16"] = {"enabled": True, "auto_cast": True} + elif mixed_precision in ("bf16", "fp8"): + if "bf16" not in ds_config: + ds_config["bf16"] = {"enabled": True} + + if mixed_precision != "no": + diff_dtype = "bf16" if mixed_precision == "fp16" else "fp16" + if str(ds_config.get(diff_dtype, {}).get("enabled", "False")).lower() == "true": + raise ValueError( + f"`--mixed_precision` arg cannot be set to `{mixed_precision}` when `{diff_dtype}` is set in the DeepSpeed config file." + ) + for dtype in ["fp16", "bf16"]: + if dtype not in ds_config: + ds_config[dtype] = {"enabled": False} + self.fill_match("fp16.enabled", must_match=False, **kwargs) + self.fill_match("bf16.enabled", must_match=False, **kwargs) + + def set_deepspeed_weakref(self): + from .imports import is_transformers_available + + if self.zero3_init_flag: + if not is_transformers_available(): + raise Exception( + "When `zero3_init_flag` is set, it requires Transformers to be installed. " + "Please run `pip install transformers`." + ) + ds_config = copy.deepcopy(self.deepspeed_config) + if "gradient_accumulation_steps" not in ds_config or ds_config["gradient_accumulation_steps"] == "auto": + ds_config["gradient_accumulation_steps"] = 1 + if ( + "train_micro_batch_size_per_gpu" not in ds_config + or ds_config["train_micro_batch_size_per_gpu"] == "auto" + ): + ds_config["train_micro_batch_size_per_gpu"] = 1 + if ds_config.get("train_batch_size", None) == "auto": + del ds_config["train_batch_size"] + + if compare_versions("transformers", "<", "4.33"): + from transformers.deepspeed import HfDeepSpeedConfig + else: + from transformers.integrations import HfDeepSpeedConfig + + self.dschf = HfDeepSpeedConfig(ds_config) # keep this object alive # noqa + + def is_zero3_init_enabled(self): + return self.zero3_init_flag + + @contextmanager + def zero3_init_context_manager(self, enable=False): + old = self.zero3_init_flag + if old == enable: + yield + else: + self.zero3_init_flag = enable + self.dschf = None + self.set_deepspeed_weakref() + yield + self.zero3_init_flag = old + self.dschf = None + self.set_deepspeed_weakref() + + def _deepspeed_config_checks(self): + env_variable_names_to_ignore = [ + "ACCELERATE_GRADIENT_ACCUMULATION_STEPS", + "ACCELERATE_GRADIENT_CLIPPING", + "ACCELERATE_DEEPSPEED_ZERO_STAGE", + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_DEVICE", + "ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_DEVICE", + "ACCELERATE_DEEPSPEED_OFFLOAD_PARAM_NVME_PATH", + "ACCELERATE_DEEPSPEED_OFFLOAD_OPTIMIZER_NVME_PATH", + "ACCELERATE_DEEPSPEED_ZERO3_SAVE_16BIT_MODEL", + "ACCELERATE_MIXED_PRECISION", + ] + env_variable_names_to_ignore = [ + name.replace("ACCELERATE_", "").replace("DEEPSPEED_", "").lower() for name in env_variable_names_to_ignore + ] + + deepspeed_fields_from_accelerate_config = os.environ.get("ACCELERATE_CONFIG_DS_FIELDS", "").split(",") + + if any(name in env_variable_names_to_ignore for name in deepspeed_fields_from_accelerate_config): + raise ValueError( + f"When using `deepspeed_config_file`, the following accelerate config variables will be ignored: {env_variable_names_to_ignore}.\n" + "Please specify them appropriately in the DeepSpeed config file.\n" + "If you are using an accelerate config file, remove others config variables mentioned in the above specified list.\n" + "The easiest method is to create a new config following the questionnaire via `accelerate config`.\n" + "It will only ask for the necessary config variables when using `deepspeed_config_file`." + ) + + def set_moe_leaf_modules(self, model): + if self.transformer_moe_cls_names is None: + self.transformer_moe_cls_names = os.environ.get("ACCELERATE_DEEPSPEED_MOE_LAYER_CLS_NAMES", None) + if self.transformer_moe_cls_names is not None: + if compare_versions("deepspeed", "<", "0.14.0"): + raise ImportError("DeepSpeed version must be >= 0.14.0 to use MOE support. Please update DeepSpeed.") + from deepspeed.utils import set_z3_leaf_modules + + class_names = self.transformer_moe_cls_names.split(",") + transformer_moe_cls = [] + for layer_class in class_names: + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise Exception( + f"Could not find a transformer layer class called '{layer_class}' to wrap in the model." + ) + else: + transformer_moe_cls.append(transformer_cls) + set_z3_leaf_modules(model, transformer_moe_cls) # z3_leaf + + +@dataclass +class FullyShardedDataParallelPlugin: + """ + This plugin is used to enable fully sharded data parallelism. + """ + + sharding_strategy: Union[str, "torch.distributed.fsdp.ShardingStrategy"] = field( + default=None, + metadata={ + "help": "Sharding strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.ShardingStrategy`. Defaults to 'FULL_SHARD'" + }, + ) + backward_prefetch: Union[str, "torch.distributed.fsdp.BackwardPrefetch"] = field( + default=None, + metadata={ + "help": "Backward prefetch strategy to use. Should be either a `str` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.BackwardPrefetch`. Defaults to 'NO_PREFETCH'" + }, + ) + mixed_precision_policy: Optional[Union[dict, "torch.distributed.fsdp.MixedPrecision"]] = field( + default=None, + metadata={ + "help": "A config to enable mixed precision training with FullyShardedDataParallel. " + "If passing in a `dict`, it should have the following keys: `param_dtype`, `reduce_dtype`, and `buffer_dtype`." + }, + ) + auto_wrap_policy: Optional[ + Union[Callable, Literal["transformer_based_wrap", "size_based_wrap", "no_wrap"]] + ] = field( + default=None, + metadata={ + "help": "A callable or string specifying a policy to recursively wrap layers with FSDP. If a string, it must be one of `transformer_based_wrap`, `size_based_wrap`, or `no_wrap`. " + "Defaults to `NO_WRAP`. See `torch.distributed.fsdp.wrap.size_based_wrap_policy` for a direction on what it should look like" + }, + ) + cpu_offload: Union[bool, "torch.distributed.fsdp.CPUOffload"] = field( + default=None, + metadata={ + "help": "Whether to offload parameters to CPU. Should be either a `bool` or an instance of `torch.distributed.fsdp.fully_sharded_data_parallel.CPUOffload`. Defaults to `False`" + }, + ) + ignored_modules: Optional[Iterable[torch.nn.Module]] = field( + default=None, + metadata={"help": "A list of modules to ignore when wrapping with FSDP."}, + ) + + state_dict_type: Union[str, "torch.distributed.fsdp.StateDictType"] = field( + default=None, + metadata={ + "help": "State dict type to use. If a string, it must be one of `full_state_dict`, `local_state_dict`, or `sharded_state_dict`. Defaults to `FULL_STATE_DICT`" + }, + ) + state_dict_config: Optional[ + Union[ + "torch.distributed.fsdp.FullStateDictConfig", + "torch.distributed.fsdp.ShardedStateDictConfig", + ] + ] = field( + default=None, + metadata={"help": "State dict config to use. Is determined based on the `state_dict_type` if not passed in."}, + ) + optim_state_dict_config: Optional[ + Union["torch.distributed.fsdp.FullOptimStateDictConfig", "torch.distributed.fsdp.ShardedOptimStateDictConfig"] + ] = field( + default=None, + metadata={ + "help": "Optim state dict config to use. Is determined based on the `state_dict_type` if not passed in." + }, + ) + limit_all_gathers: bool = field( + default=True, + metadata={ + "help": "Whether to have FSDP explicitly synchronizes the CPU thread to prevent " + "too many in-flight all-gathers. This bool only affects the sharded strategies that schedule all-gathers. " + "Enabling this can help lower the number of CUDA malloc retries." + }, + ) + use_orig_params: bool = field( + default=None, + metadata={"help": "Whether to use the original parameters for the optimizer. Defaults to `False`"}, + ) + param_init_fn: Optional[Callable[[torch.nn.Module], None]] = field( + default=None, + metadata={ + "help": "A Callable[torch.nn.Module] -> None that specifies how modules " + "that are currently on the meta device should be initialized onto an actual device. " + "Only applicable when `sync_module_states` is `True`. By default is a `lambda` which calls `to_empty` on the module." + }, + ) + sync_module_states: bool = field( + default=None, + metadata={ + "help": "Whether each individually wrapped FSDP unit should broadcast module parameters from rank 0 " + "to ensure they are the same across all ranks after initialization. Defaults to `False` unless " + "`cpu_ram_efficient_loading` is `True`, then will be forcibly enabled." + }, + ) + forward_prefetch: bool = field( + default=None, + metadata={ + "help": "Whether to have FSDP explicitly prefetches the next upcoming " + "all-gather while executing in the forward pass. only use with Static graphs. Defaults to `False`" + }, + ) + activation_checkpointing: bool = field( + default=None, + metadata={ + "help": "A technique to reduce memory usage by clearing activations of " + "certain layers and recomputing them during a backward pass. Effectively, this trades extra computation time " + "for reduced memory usage. Defaults to `False`" + }, + ) + cpu_ram_efficient_loading: bool = field( + default=None, + metadata={ + "help": "If True, only the first process loads the pretrained model checkoint while all other processes have empty weights. " + "Only applicable for 🤗 Transformers. When using this, `sync_module_states` needs to be `True`. Defaults to `False`." + }, + ) + transformer_cls_names_to_wrap: Optional[List[str]] = field( + default=None, + metadata={ + "help": "A list of transformer layer class names to wrap. Only applicable when `auto_wrap_policy` is `transformer_based_wrap`." + }, + ) + min_num_params: Optional[int] = field( + default=None, + metadata={ + "help": "The minimum number of parameters a module must have to be wrapped. Only applicable when `auto_wrap_policy` is `size_based_wrap`." + }, + ) + + def __post_init__(self): + from torch.distributed.fsdp import ( + BackwardPrefetch, + CPUOffload, + ShardingStrategy, + ) + + env_prefix = "FSDP_" + # Strategy: By default we should always assume that values are passed in, else we check the environment variables + if self.sharding_strategy is None: + self.sharding_strategy = os.environ.get(env_prefix + "SHARDING_STRATEGY", "FULL_SHARD") + if isinstance(self.sharding_strategy, str): + # We need to remap based on custom enum values for user readability + if self.sharding_strategy.upper() in FSDP_SHARDING_STRATEGY: + self.sharding_strategy = FSDP_SHARDING_STRATEGY.index(self.sharding_strategy.upper()) + 1 + if isinstance(self.sharding_strategy, int) or self.sharding_strategy.isdigit(): + self.sharding_strategy = ShardingStrategy(int(self.sharding_strategy)) + else: + self.sharding_strategy = ShardingStrategy[self.sharding_strategy.upper()] + + if self.cpu_offload is None: + self.cpu_offload = str_to_bool(os.environ.get(env_prefix + "OFFLOAD_PARAMS", "False")) == 1 + if isinstance(self.cpu_offload, bool): + self.cpu_offload = CPUOffload(offload_params=self.cpu_offload) + + if self.backward_prefetch is None: + self.backward_prefetch = os.environ.get(env_prefix + "BACKWARD_PREFETCH", None) + if isinstance(self.backward_prefetch, str) and self.backward_prefetch.upper() == "NO_PREFETCH": + self.backward_prefetch = None + if self.backward_prefetch is not None and not isinstance(self.backward_prefetch, BackwardPrefetch): + if isinstance(self.backward_prefetch, str) and self.backward_prefetch.upper() in FSDP_BACKWARD_PREFETCH: + self.backward_prefetch = FSDP_BACKWARD_PREFETCH.index(self.backward_prefetch.upper()) + 1 + if isinstance(self.backward_prefetch, int) or self.backward_prefetch.isdigit(): + self.backward_prefetch = BackwardPrefetch(int(self.backward_prefetch)) + else: + self.backward_prefetch = BackwardPrefetch[self.backward_prefetch.upper()] + + self.set_state_dict_type() + + if self.auto_wrap_policy is None: + self.auto_wrap_policy = os.environ.get(env_prefix + "AUTO_WRAP_POLICY", "NO_WRAP") + if isinstance(self.auto_wrap_policy, str): + if self.auto_wrap_policy.upper() not in FSDP_AUTO_WRAP_POLICY: + raise ValueError( + f"Invalid auto wrap policy: {self.auto_wrap_policy}. Must be one of {list(FSDP_AUTO_WRAP_POLICY.keys())}" + ) + from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy, transformer_auto_wrap_policy + + if self.auto_wrap_policy.upper() == "TRANSFORMER_BASED_WRAP": + self.auto_wrap_policy = transformer_auto_wrap_policy + if self.transformer_cls_names_to_wrap is None: + self.transformer_cls_names_to_wrap = os.environ.get(env_prefix + "TRANSFORMER_CLS_TO_WRAP", None) + if isinstance(self.transformer_cls_names_to_wrap, str): + self.transformer_cls_names_to_wrap = self.transformer_cls_names_to_wrap.split(",") + elif self.auto_wrap_policy.upper() == "SIZE_BASED_WRAP": + self.auto_wrap_policy = size_based_auto_wrap_policy + if self.min_num_params is None: + self.min_num_params = int(os.environ.get(env_prefix + "MIN_NUM_PARAMS", 0)) + elif not isinstance(self.min_num_params, int): + raise ValueError( + f"`min_num_params` must be an integer. Got {self.min_num_params} of type {type(self.min_num_params)}" + ) + elif self.auto_wrap_policy.upper() == "NO_WRAP": + self.auto_wrap_policy = None + + if self.use_orig_params is None: + self.use_orig_params = str_to_bool(os.environ.get(env_prefix + "USE_ORIG_PARAMS", "False")) == 1 + + if self.sync_module_states is None: + self.sync_module_states = str_to_bool(os.environ.get(env_prefix + "SYNC_MODULE_STATES", "False")) == 1 + + if self.forward_prefetch is None: + self.forward_prefetch = str_to_bool(os.environ.get(env_prefix + "FORWARD_PREFETCH", "False")) == 1 + + if self.activation_checkpointing is None: + self.activation_checkpointing = ( + str_to_bool(os.environ.get(env_prefix + "ACTIVATION_CHECKPOINTING", "False")) == 1 + ) + + if self.cpu_ram_efficient_loading is None: + self.cpu_ram_efficient_loading = ( + str_to_bool(os.environ.get(env_prefix + "CPU_RAM_EFFICIENT_LOADING", "False")) == 1 + ) + + if self.cpu_ram_efficient_loading and not self.sync_module_states: + warnings.warn( + "sync_module_states cannot be False since efficient cpu ram loading enabled. " + "Setting sync_module_states to True." + ) + self.sync_module_states = True + + if isinstance(self.mixed_precision_policy, dict): + self.set_mixed_precision(self.mixed_precision_policy) + + if self.sync_module_states: + if is_npu_available(): + device = torch.npu.current_device() + elif is_mlu_available(): + device = torch.mlu.current_device() + elif is_cuda_available(): + device = torch.cuda.current_device() + elif is_xpu_available(): + device = torch.xpu.current_device() + else: + raise RuntimeError( + "There are currently no available devices found, must be one of 'XPU', 'CUDA', or 'NPU'." + ) + # Create a function that will be used to initialize the parameters of the model + # when using `sync_module_states` + self.param_init_fn = lambda x: x.to_empty(device=device, recurse=False) + + def set_state_dict_type(self): + """ + Set the state dict config based on the `StateDictType`. + """ + from torch.distributed.fsdp.fully_sharded_data_parallel import ( + FullOptimStateDictConfig, + FullStateDictConfig, + ShardedOptimStateDictConfig, + ShardedStateDictConfig, + StateDictType, + ) + + if self.state_dict_type is None: + self.state_dict_type = os.environ.get("FSDP_STATE_DICT_TYPE", "FULL_STATE_DICT") + if isinstance(self.state_dict_type, str): + if self.state_dict_type.isdigit(): + self.state_dict_type = StateDictType(int(self.state_dict_type)) + else: + self.state_dict_type = StateDictType[self.state_dict_type.upper()] + + if self.state_dict_type == StateDictType.FULL_STATE_DICT: + if self.state_dict_config is None: + self.state_dict_config = FullStateDictConfig(offload_to_cpu=True, rank0_only=True) + if self.optim_state_dict_config is None: + self.optim_state_dict_config = FullOptimStateDictConfig(offload_to_cpu=True, rank0_only=True) + elif self.state_dict_type == StateDictType.SHARDED_STATE_DICT: + if self.state_dict_config is None: + self.state_dict_config = ShardedStateDictConfig(offload_to_cpu=True) + if self.optim_state_dict_config is None: + self.optim_state_dict_config = ShardedOptimStateDictConfig(offload_to_cpu=True) + + def set_auto_wrap_policy(self, model): + """ + Given `model`, creates an `auto_wrap_policy` baesd on the passed in policy and if we can use the + `transformer_cls_to_wrap` + """ + from torch.distributed.fsdp.wrap import size_based_auto_wrap_policy, transformer_auto_wrap_policy + + # First base off of `_no_split_modules` + no_split_modules = getattr(model, "_no_split_modules", None) + default_transformer_cls_names_to_wrap = list(no_split_modules) if no_split_modules is not None else [] + if self.auto_wrap_policy == transformer_auto_wrap_policy: + if self.transformer_cls_names_to_wrap is None: + self.transformer_cls_names_to_wrap = default_transformer_cls_names_to_wrap + transformer_cls_to_wrap = set() + for layer_class in self.transformer_cls_names_to_wrap: + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise ValueError(f"Could not find the transformer layer class {layer_class} in the model.") + transformer_cls_to_wrap.add(transformer_cls) + # Finally we set the auto_wrap_policy to a callable + self.auto_wrap_policy = functools.partial( + self.auto_wrap_policy, transformer_layer_cls=transformer_cls_to_wrap + ) + + elif self.auto_wrap_policy == size_based_auto_wrap_policy: + # If zero, we silently ignore it. + if self.min_num_params > 0: + self.auto_wrap_policy = functools.partial(self.auto_wrap_policy, min_num_params=self.min_num_params) + else: + self.auto_wrap_policy = None + + def set_mixed_precision(self, mixed_precision, buffer_autocast=False, override=False): + "Sets the mixed precision policy for FSDP" + mixed_precision_mapping = { + "fp8": torch.bfloat16, + "fp16": torch.float16, + "bf16": torch.bfloat16, + "fp32": torch.float32, + } + dtype = mixed_precision + if isinstance(mixed_precision, str): + dtype = mixed_precision_mapping.get(mixed_precision, None) + if dtype is None: + raise ValueError( + f"Invalid mixed precision: {mixed_precision}. Must be one of {list(mixed_precision_mapping.keys())}" + ) + elif isinstance(mixed_precision, torch.dtype) and mixed_precision not in mixed_precision_mapping.values(): + raise ValueError( + f"Invalid mixed precision: {mixed_precision}. Must be one of {list(mixed_precision_mapping.values())}" + ) + + buffer_type = torch.float32 if buffer_autocast else dtype + + from torch.distributed.fsdp.fully_sharded_data_parallel import MixedPrecision + + if override or self.mixed_precision_policy is None: + self.mixed_precision_policy = MixedPrecision( + param_dtype=dtype, reduce_dtype=dtype, buffer_dtype=buffer_type + ) + elif isinstance(self.mixed_precision_policy, dict): + # Check for incompatible types + missing_keys = [ + k for k in ["param_dtype", "reduce_dtype", "buffer_dtype"] if k not in self.mixed_precision_policy + ] + invalid_values = [ + k for k, v in self.mixed_precision_policy.items() if v not in mixed_precision_mapping.values() + ] + if missing_keys or invalid_values: + raise ValueError( + f"Invalid mixed precision policy: {self.mixed_precision_policy}. " + f"Must be a `dict` with keys `param_dtype`, `reduce_dtype`, and `buffer_dtype`. " + f"Values must be one of {list(mixed_precision_mapping.values())}" + ) + self.mixed_precision_policy = MixedPrecision(**self.mixed_precision_policy) + + +@dataclass +class MegatronLMPlugin: + """ + Plugin for Megatron-LM to enable tensor, pipeline, sequence and data parallelism. Also to enable selective + activation recomputation and optimized fused kernels. + """ + + tp_degree: int = field(default=None, metadata={"help": "tensor parallelism degree."}) + pp_degree: int = field(default=None, metadata={"help": "pipeline parallelism degree."}) + num_micro_batches: int = field(default=None, metadata={"help": "number of micro-batches."}) + gradient_clipping: float = field( + default=None, metadata={"help": "gradient clipping value based on global L2 Norm (0 to disable)"} + ) + sequence_parallelism: bool = field( + default=None, + metadata={"help": "enable sequence parallelism"}, + ) + recompute_activations: bool = field( + default=None, + metadata={"help": "enable selective activation recomputation"}, + ) + use_distributed_optimizer: bool = field( + default=None, + metadata={"help": "enable distributed optimizer"}, + ) + pipeline_model_parallel_split_rank: int = field( + default=None, metadata={"help": "Rank where encoder and decoder should be split."} + ) + num_layers_per_virtual_pipeline_stage: int = field( + default=None, metadata={"help": "Number of layers per virtual pipeline stage."} + ) + is_train_batch_min: str = field( + default=True, + metadata={"help": "If both train & eval dataloaders are specified, this will decide the micro_batch_size"}, + ) + train_iters: int = field( + default=None, + metadata={ + "help": "Total number of iterations to train over all training runs. " + "Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`" + }, + ) + train_samples: int = field( + default=None, + metadata={ + "help": "Total number of samples to train over all training runs. " + "Note that either train-iters or train-samples should be provided when using `MegatronLMDummyScheduler`" + }, + ) + weight_decay_incr_style: str = field( + default="constant", + metadata={"help": 'Weight decay increment function. choices=["constant", "linear", "cosine"]. '}, + ) + start_weight_decay: float = field( + default=None, + metadata={"help": "Initial weight decay coefficient for L2 regularization."}, + ) + end_weight_decay: float = field( + default=None, + metadata={"help": "End of run weight decay coefficient for L2 regularization."}, + ) + lr_decay_style: str = field( + default="linear", + metadata={"help": "Learning rate decay function. choices=['constant', 'linear', 'cosine']."}, + ) + lr_decay_iters: int = field( + default=None, + metadata={"help": "Number of iterations for learning rate decay. If None defaults to `train_iters`."}, + ) + lr_decay_samples: int = field( + default=None, + metadata={"help": "Number of samples for learning rate decay. If None defaults to `train_samples`."}, + ) + lr_warmup_iters: int = field( + default=None, + metadata={"help": "number of iterations to linearly warmup learning rate over."}, + ) + lr_warmup_samples: int = field( + default=None, + metadata={"help": "number of samples to linearly warmup learning rate over."}, + ) + lr_warmup_fraction: float = field( + default=None, + metadata={"help": "fraction of lr-warmup-(iters/samples) to linearly warmup learning rate over."}, + ) + min_lr: float = field( + default=0, + metadata={"help": "Minumum value for learning rate. The scheduler clip values below this threshold."}, + ) + consumed_samples: List[int] = field( + default=None, + metadata={ + "help": "Number of samples consumed in the same order as the dataloaders to `accelerator.prepare` call." + }, + ) + no_wd_decay_cond: Optional[Callable] = field(default=None, metadata={"help": "Condition to disable weight decay."}) + scale_lr_cond: Optional[Callable] = field(default=None, metadata={"help": "Condition to scale learning rate."}) + lr_mult: float = field(default=1.0, metadata={"help": "Learning rate multiplier."}) + megatron_dataset_flag: bool = field( + default=False, + metadata={"help": "Whether the format of dataset follows Megatron-LM Indexed/Cached/MemoryMapped format."}, + ) + seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process."}, + ) + encoder_seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process for the encoder."}, + ) + decoder_seq_length: int = field( + default=None, + metadata={"help": "Maximum sequence length to process for the decoder."}, + ) + tensorboard_dir: str = field( + default=None, + metadata={"help": "Path to save tensorboard logs."}, + ) + set_all_logging_options: bool = field( + default=False, + metadata={"help": "Whether to set all logging options."}, + ) + eval_iters: int = field( + default=100, metadata={"help": "Number of iterations to run for evaluation validation/test for."} + ) + eval_interval: int = field( + default=1000, metadata={"help": "Interval between running evaluation on validation set."} + ) + return_logits: bool = field( + default=False, + metadata={"help": "Whether to return logits from the model."}, + ) + + # custom train step args + custom_train_step_class: Optional[Any] = field( + default=None, + metadata={"help": "Custom train step class."}, + ) + custom_train_step_kwargs: Optional[Dict[str, Any]] = field( + default=None, + metadata={"help": "Custom train step kwargs."}, + ) + + # custom model args + custom_model_provider_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom model provider function."}, + ) + custom_prepare_model_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom prepare model function."}, + ) + custom_megatron_datasets_provider_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom megatron train_valid_test datasets provider function."}, + ) + custom_get_batch_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom get batch function."}, + ) + custom_loss_function: Optional[Callable] = field( + default=None, + metadata={"help": "Custom loss function."}, + ) + + # remaining args such as enabling Alibi/ROPE positional embeddings, + # wandb logging, Multi-Query Attention, etc. + other_megatron_args: Optional[Dict[str, Any]] = field( + default=None, + metadata={"help": "Other Megatron-LM arguments. Please refer Megatron-LM"}, + ) + + def __post_init__(self): + prefix = "MEGATRON_LM_" + if self.tp_degree is None: + self.tp_degree = int(os.environ.get(prefix + "TP_DEGREE", 1)) + if self.pp_degree is None: + self.pp_degree = int(os.environ.get(prefix + "PP_DEGREE", 1)) + if self.num_micro_batches is None: + self.num_micro_batches = int(os.environ.get(prefix + "NUM_MICRO_BATCHES", 1)) + if self.gradient_clipping is None: + self.gradient_clipping = float(os.environ.get(prefix + "GRADIENT_CLIPPING", 1.0)) + if self.recompute_activations is None: + self.recompute_activations = str_to_bool(os.environ.get(prefix + "RECOMPUTE_ACTIVATIONS", "False")) == 1 + if self.use_distributed_optimizer is None: + self.use_distributed_optimizer = ( + str_to_bool(os.environ.get(prefix + "USE_DISTRIBUTED_OPTIMIZER", "False")) == 1 + ) + if self.sequence_parallelism is None: + self.sequence_parallelism = str_to_bool(os.environ.get(prefix + "SEQUENCE_PARALLELISM", "False")) == 1 + + if self.pp_degree > 1 or self.use_distributed_optimizer: + self.DDP_impl = "local" + else: + self.DDP_impl = "torch" + + if self.consumed_samples is not None: + if len(self.consumed_samples) == 1: + self.consumed_samples.extend([0, 0]) + elif len(self.consumed_samples) == 2: + self.consumed_samples.append(0) + + self.megatron_lm_default_args = { + "tensor_model_parallel_size": self.tp_degree, + "pipeline_model_parallel_size": self.pp_degree, + "pipeline_model_parallel_split_rank": self.pipeline_model_parallel_split_rank, + "num_layers_per_virtual_pipeline_stage": self.num_layers_per_virtual_pipeline_stage, + "DDP_impl": self.DDP_impl, + "use_distributed_optimizer": self.use_distributed_optimizer, + "sequence_parallel": self.sequence_parallelism, + "clip_grad": self.gradient_clipping, + "num_micro_batches": self.num_micro_batches, + "consumed_samples": self.consumed_samples, + "no_wd_decay_cond": self.no_wd_decay_cond, + "scale_lr_cond": self.scale_lr_cond, + "lr_mult": self.lr_mult, + "megatron_dataset_flag": self.megatron_dataset_flag, + "eval_iters": self.eval_iters, + "eval_interval": self.eval_interval, + } + if self.recompute_activations: + self.megatron_lm_default_args["recompute_granularity"] = "selective" + if self.tensorboard_dir is not None: + self.megatron_lm_default_args["tensorboard_dir"] = self.tensorboard_dir + if self.set_all_logging_options: + self.set_tensorboard_logging_options() + if self.other_megatron_args is not None: + self.megatron_lm_default_args.update(self.other_megatron_args) + + def set_network_size_args(self, model, batch_data=None): + model_config_type = model.config.model_type.lower() + for model_type in MODEL_CONFIGS_TO_MEGATRON_PARSERS.keys(): + if model_type in model_config_type: + MODEL_CONFIGS_TO_MEGATRON_PARSERS[model_type](self, model, batch_data) + return + raise ValueError( + f"Accelerate Megatron-LM integration not supports {model_config_type} model. " + "You can add your own model config parser." + ) + + def set_mixed_precision(self, mixed_precision): + if mixed_precision == "fp16": + self.megatron_lm_default_args["fp16"] = True + elif mixed_precision == "bf16": + self.megatron_lm_default_args["bf16"] = True + self.DDP_impl = "local" + self.megatron_lm_default_args["DDP_impl"] = self.DDP_impl + + def set_training_args(self, micro_batch_size, dp_degree): + self.data_parallel_size = dp_degree + self.micro_batch_size = micro_batch_size + self.global_batch_size = dp_degree * micro_batch_size * self.num_micro_batches + self.megatron_lm_default_args["data_parallel_size"] = self.data_parallel_size + self.megatron_lm_default_args["micro_batch_size"] = self.micro_batch_size + self.megatron_lm_default_args["global_batch_size"] = self.global_batch_size + + def set_optimizer_type(self, optimizer): + optimizer_name = optimizer.__class__.__name__.lower() + if "adam" in optimizer_name: + self.megatron_lm_default_args["optimizer"] = "adam" + self.megatron_lm_default_args["adam_beta1"] = optimizer.defaults["betas"][0] + self.megatron_lm_default_args["adam_beta2"] = optimizer.defaults["betas"][1] + self.megatron_lm_default_args["adam_eps"] = optimizer.defaults["eps"] + elif "sgd" in optimizer_name: + self.megatron_lm_default_args["optimizer"] = "sgd" + self.megatron_lm_default_args["sgd_momentum"] = optimizer.defaults["momentum"] + else: + raise ValueError(f"Optimizer {optimizer_name} is not supported by Megatron-LM") + + self.megatron_lm_default_args["lr"] = optimizer.defaults["lr"] + self.megatron_lm_default_args["weight_decay"] = optimizer.defaults["weight_decay"] + + def set_scheduler_args(self, scheduler): + if self.train_iters is None: + self.train_iters = scheduler.total_num_steps // self.megatron_lm_default_args["data_parallel_size"] + if self.train_samples is not None: + self.train_samples = None + warnings.warn( + "Ignoring `train_samples` as `train_iters` based on scheduler is being used for training." + ) + if self.lr_warmup_iters is None: + self.lr_warmup_iters = scheduler.warmup_num_steps // self.megatron_lm_default_args["data_parallel_size"] + if self.lr_warmup_samples is not None: + warnings.warn( + "Ignoring `lr_warmup_samples` as `lr_warmup_iters` based on scheduler is being used for training." + ) + self.lr_warmup_samples = 0 + + self.megatron_lm_default_args["train_iters"] = self.train_iters + self.megatron_lm_default_args["lr_warmup_iters"] = self.lr_warmup_iters + self.megatron_lm_default_args["train_samples"] = self.train_samples + self.megatron_lm_default_args["lr_warmup_samples"] = self.lr_warmup_samples + self.megatron_lm_default_args["lr_decay_iters"] = self.lr_decay_iters + self.megatron_lm_default_args["lr_decay_samples"] = self.lr_decay_samples + self.megatron_lm_default_args["lr_warmup_fraction"] = self.lr_warmup_fraction + self.megatron_lm_default_args["lr_decay_style"] = self.lr_decay_style + self.megatron_lm_default_args["weight_decay_incr_style"] = self.weight_decay_incr_style + self.megatron_lm_default_args["start_weight_decay"] = self.start_weight_decay + self.megatron_lm_default_args["end_weight_decay"] = self.end_weight_decay + self.megatron_lm_default_args["min_lr"] = self.min_lr + + def set_tensorboard_logging_options(self): + from megatron.arguments import _add_logging_args + + parser = argparse.ArgumentParser() + parser = _add_logging_args(parser) + logging_args = parser.parse_known_args() + self.dataset_args = vars(logging_args[0]) + for key, value in self.dataset_args.items(): + if key.startswith("log_"): + self.megatron_lm_default_args[key] = True + elif key.startswith("no_log_"): + self.megatron_lm_default_args[key.replace("no_", "")] = True + + +MODEL_CONFIGS_TO_MEGATRON_PARSERS = {} + + +def add_model_config_to_megatron_parser(model_type: str): + def add_model_config_parser_helper(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + return func(*args, **kwargs) + + MODEL_CONFIGS_TO_MEGATRON_PARSERS[model_type] = func + return wrapper + + return add_model_config_parser_helper + + +@add_model_config_to_megatron_parser("megatron-bert") +def parse_bert_config(megatron_lm_plugin, model, batch_data): + model_type_name = "bert" + num_layers = model.config.num_hidden_layers + hidden_size = model.config.hidden_size + num_attention_heads = model.config.num_attention_heads + max_position_embeddings = model.config.max_position_embeddings + num_labels = model.config.num_labels + orig_vocab_size = model.config.vocab_size + pretraining_flag = False + if "maskedlm" in model.__class__.__name__.lower(): + pretraining_flag = True + if megatron_lm_plugin.seq_length is not None: + if megatron_lm_plugin.encoder_seq_length is not None: + warnings.warn("Both `seq_length` and `encoder_seq_length` are set. Using `encoder_seq_length`.") + megatron_lm_plugin.seq_length = megatron_lm_plugin.encoder_seq_length + elif megatron_lm_plugin.encoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.encoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + megatron_lm_plugin.megatron_lm_default_args["num_labels"] = num_labels + + +@add_model_config_to_megatron_parser("gpt2") +def parse_gpt2_config(megatron_lm_plugin, model, batch_data): + model_type_name = "gpt" + num_layers = model.config.n_layer + hidden_size = model.config.n_embd + num_attention_heads = model.config.n_head + max_position_embeddings = model.config.n_positions + orig_vocab_size = model.config.vocab_size + pretraining_flag = True + if megatron_lm_plugin.seq_length is not None: + if megatron_lm_plugin.decoder_seq_length is not None: + warnings.warn("Both `seq_length` and `decoder_seq_length` are set. Using `decoder_seq_length`.") + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif megatron_lm_plugin.decoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["return_logits"] = megatron_lm_plugin.return_logits + megatron_lm_plugin.megatron_lm_default_args["tokenizer_type"] = "GPT2BPETokenizer" + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@add_model_config_to_megatron_parser("t5") +def parse_t5_config(megatron_lm_plugin, model, batch_data): + model_type_name = "t5" + num_layers = model.config.num_layers + hidden_size = model.config.d_model + num_attention_heads = model.config.num_heads + max_position_embeddings = model.config.n_positions if hasattr(model.config, "n_positions") else 1024 + orig_vocab_size = model.config.vocab_size + pretraining_flag = True + if megatron_lm_plugin.encoder_seq_length is None: + if batch_data is not None: + megatron_lm_plugin.encoder_seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.encoder_seq_length = max_position_embeddings + if megatron_lm_plugin.decoder_seq_length is None: + if batch_data is not None: + megatron_lm_plugin.decoder_seq_length = batch_data["labels"].shape[1] + else: + megatron_lm_plugin.decoder_seq_length = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["encoder_seq_length"] = megatron_lm_plugin.encoder_seq_length + megatron_lm_plugin.megatron_lm_default_args["decoder_seq_length"] = megatron_lm_plugin.decoder_seq_length + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@add_model_config_to_megatron_parser("llama") +def parse_llama_config(megatron_lm_plugin, model, batch_data): + model_type_name = "gpt" + num_layers = model.config.num_hidden_layers + pretraining_flag = True + hidden_size = model.config.hidden_size + num_attention_heads = model.config.num_attention_heads + orig_vocab_size = model.config.vocab_size + + max_position_embeddings = model.config.max_position_embeddings + seq_length = getattr(model.config, "max_sequence_length", None) + if megatron_lm_plugin.seq_length is None: + if seq_length is not None: + megatron_lm_plugin.seq_length = seq_length + elif megatron_lm_plugin.decoder_seq_length is not None: + megatron_lm_plugin.seq_length = megatron_lm_plugin.decoder_seq_length + elif batch_data is not None: + megatron_lm_plugin.seq_length = batch_data["input_ids"].shape[1] + else: + megatron_lm_plugin.seq_length = max_position_embeddings + + megatron_lm_plugin.megatron_lm_default_args["return_logits"] = megatron_lm_plugin.return_logits + megatron_lm_plugin.megatron_lm_default_args["tokenizer_type"] = "Llama2Tokenizer" + megatron_lm_plugin.megatron_lm_default_args["model_type_name"] = model_type_name + megatron_lm_plugin.megatron_lm_default_args["num_layers"] = num_layers + megatron_lm_plugin.megatron_lm_default_args["pretraining_flag"] = pretraining_flag + megatron_lm_plugin.megatron_lm_default_args["hidden_size"] = hidden_size + megatron_lm_plugin.megatron_lm_default_args["num_attention_heads"] = num_attention_heads + megatron_lm_plugin.megatron_lm_default_args["orig_vocab_size"] = orig_vocab_size + megatron_lm_plugin.megatron_lm_default_args["max_position_embeddings"] = max_position_embeddings + megatron_lm_plugin.megatron_lm_default_args["seq_length"] = megatron_lm_plugin.seq_length + megatron_lm_plugin.megatron_lm_default_args["model_return_dict"] = model.config.return_dict + + +@dataclass +class BnbQuantizationConfig: + """ + A plugin to enable BitsAndBytes 4bit and 8bit quantization + """ + + load_in_8bit: bool = field(default=False, metadata={"help": "enable 8bit quantization."}) + + llm_int8_threshold: float = field( + default=6.0, metadata={"help": "value of the outliner threshold. only relevant when load_in_8bit=True"} + ) + + load_in_4bit: bool = field(default=False, metadata={"help": "enable 4bit quantization."}) + + bnb_4bit_quant_type: str = field( + default="fp4", + metadata={ + "help": "set the quantization data type in the `bnb.nn.Linear4Bit` layers. Options are {'fp4','np4'}." + }, + ) + + bnb_4bit_use_double_quant: bool = field( + default=False, + metadata={ + "help": "enable nested quantization where the quantization constants from the first quantization are quantized again." + }, + ) + + bnb_4bit_compute_dtype: bool = field( + default="fp16", + metadata={ + "help": "This sets the computational type which might be different than the input time. For example, inputs might be " + "fp32, but computation can be set to bf16 for speedups. Options are {'fp32','fp16','bf16'}." + }, + ) + + torch_dtype: torch.dtype = field( + default=None, + metadata={ + "help": "this sets the dtype of the remaining non quantized layers. `bitsandbytes` library suggests to set the value" + "to `torch.float16` for 8 bit model and use the same dtype as the compute dtype for 4 bit model " + }, + ) + + skip_modules: List[str] = field( + default=None, + metadata={ + "help": "an explicit list of the modules that we don't quantize. The dtype of these modules will be `torch_dtype`." + }, + ) + + keep_in_fp32_modules: List[str] = field( + default=None, + metadata={"help": "an explicit list of the modules that we don't quantize. We keep them in `torch.float32`."}, + ) + + def __post_init__(self): + """ + Safety checker that arguments are correct - also replaces some NoneType arguments with their default values. + """ + if not isinstance(self.load_in_8bit, bool): + raise ValueError("load_in_8bit must be a boolean") + + if not isinstance(self.load_in_4bit, bool): + raise ValueError("load_in_4bit must be a boolean") + + if self.load_in_4bit and self.load_in_8bit: + raise ValueError("load_in_4bit and load_in_8 can't be both True") + + if not self.load_in_4bit and not self.load_in_8bit: + raise ValueError("load_in_4bit and load_in_8 can't be both False") + + if not isinstance(self.llm_int8_threshold, (int, float)): + raise ValueError("llm_int8_threshold must be a float or an int") + + if not isinstance(self.bnb_4bit_quant_type, str): + raise ValueError("bnb_4bit_quant_type must be a string") + elif self.bnb_4bit_quant_type not in ["fp4", "nf4"]: + raise ValueError(f"bnb_4bit_quant_type must be in ['fp4','nf4'] but found {self.bnb_4bit_quant_type}") + + if not isinstance(self.bnb_4bit_use_double_quant, bool): + raise ValueError("bnb_4bit_use_double_quant must be a boolean") + + if isinstance(self.bnb_4bit_compute_dtype, str): + if self.bnb_4bit_compute_dtype == "fp32": + self.bnb_4bit_compute_dtype = torch.float32 + elif self.bnb_4bit_compute_dtype == "fp16": + self.bnb_4bit_compute_dtype = torch.float16 + elif self.bnb_4bit_compute_dtype == "bf16": + self.bnb_4bit_compute_dtype = torch.bfloat16 + else: + raise ValueError( + f"bnb_4bit_compute_dtype must be in ['fp32','fp16','bf16'] but found {self.bnb_4bit_compute_dtype}" + ) + elif not isinstance(self.bnb_4bit_compute_dtype, torch.dtype): + raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype") + + if self.skip_modules is not None and not isinstance(self.skip_modules, list): + raise ValueError("skip_modules must be a list of strings") + + if self.keep_in_fp32_modules is not None and not isinstance(self.keep_in_fp32_modules, list): + raise ValueError("keep_in_fp_32_modules must be a list of strings") + + if self.load_in_4bit: + self.target_dtype = CustomDtype.INT4 + + if self.load_in_8bit: + self.target_dtype = torch.int8 + + if self.load_in_4bit and self.llm_int8_threshold != 6.0: + warnings.warn("llm_int8_threshold can only be used for model loaded in 8bit") + + if isinstance(self.torch_dtype, str): + if self.torch_dtype == "fp32": + self.torch_dtype = torch.float32 + elif self.torch_dtype == "fp16": + self.torch_dtype = torch.float16 + elif self.torch_dtype == "bf16": + self.torch_dtype = torch.bfloat16 + else: + raise ValueError(f"torch_dtype must be in ['fp32','fp16','bf16'] but found {self.torch_dtype}") + if self.load_in_8bit and self.torch_dtype is None: + self.torch_dtype = torch.float16 + + if self.load_in_4bit and self.torch_dtype is None: + self.torch_dtype = self.bnb_4bit_compute_dtype + + if not isinstance(self.torch_dtype, torch.dtype): + raise ValueError("torch_dtype must be a torch.dtype") + + +def get_module_class_from_name(module, name): + """ + Gets a class from a module by its name. + + Args: + module (`torch.nn.Module`): The module to get the class from. + name (`str`): The name of the class. + """ + modules_children = list(module.children()) + if module.__class__.__name__ == name: + return module.__class__ + elif len(modules_children) == 0: + return + else: + for child_module in modules_children: + module_class = get_module_class_from_name(child_module, name) + if module_class is not None: + return module_class diff --git a/tasks/tasksmith-5d12db5414d2/solution/solve.sh b/tasks/tasksmith-5d12db5414d2/solution/solve.sh new file mode 100644 index 0000000000000000000000000000000000000000..95e8d642875498579a664c8c6cf86bc6081b241f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/solution/solve.sh @@ -0,0 +1,3 @@ +#!/bin/sh +set -eu +cp /solution/reference/src/accelerate/utils/dataclasses.py /workspace/src/accelerate/utils/dataclasses.py diff --git a/tasks/tasksmith-5d12db5414d2/task.toml b/tasks/tasksmith-5d12db5414d2/task.toml new file mode 100644 index 0000000000000000000000000000000000000000..75f0e2bd3466c04c5f94d23b1969a6f7e1ea9fcb --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/task.toml @@ -0,0 +1,336 @@ +schema_version = "1.3" + +[task] +name = "repo2rlenv/tasksmith-5d12db5414d2" + +[metadata.repo2env] +recipe = "tasksmith" +recipe_version = "1" +source_url = "https://github.com/huggingface/accelerate/pull/3075" +source_head = "f8ff93658f99e46323218af834ecfd8fc30a4581" +source_base = "b5235f21d83c7f714a44d876cfd6fd0b1339dd38" +workspace_strategy = "head_minus_source_patch" +source_diff_sha256 = "4ef90165b1282622cdf955e6ec99206b3138e2d0d502ac40bb5f578b1023b7b0" +acceptance_profile = "practical-generation-v1" +reward_kinds = [ + "test_execution", +] +quality_status = "exported" +fail_to_pass_count = 2 +pass_to_pass_count = 8 +bundle_hash = "sha256:3f28b6de2fdb1ac66016bb3fdf79d635b3eff39a794eee58b6bd16cf32e51f60" + +[metadata.repo2env.evaluation] +schema_version = "1" +status = "verified" +stage = "complete" +reason_codes = [ + "quality_verified", +] +detail = "Reviewed controls, semantic probes and blind rollout passed the quality profile." +checked_at = "2026-09-14T05:39:57.678322Z" +provenance = "assisted" +subject_bundle_hash = "sha256:3f28b6de2fdb1ac66016bb3fdf79d635b3eff39a794eee58b6bd16cf32e51f60" +profile = "practical-generation-v1" +source_task_path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/0c36ef5246b3/candidates/5d12db5414d2/quality/revisions/r0/tasksmith-5d12db5414d2" +source_task_toml_sha256 = "f1b0191c7536b320918ca351fbac1cb4f44dcc920b383ebfc257de53b337462c" + +[[metadata.repo2env.evaluation.evidence]] +kind = "quality_result" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/0c36ef5246b3/candidates/5d12db5414d2/quality/result.json" +sha256 = "a97b089f361f2f4a7750acf23ec8ad07404d6244124da6145b9c3b671f2d146c" +subject_bundle_hash = "sha256:3f28b6de2fdb1ac66016bb3fdf79d635b3eff39a794eee58b6bd16cf32e51f60" + +[[metadata.repo2env.evaluation.evidence]] +kind = "baseline" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/0c36ef5246b3/candidates/5d12db5414d2/quality/trials/r0-baseline/tsbatch-50714e834186-0c36ef5246b3-q-5d12db54-r0-baseline/tasksmith-5d12db5414d2__6s5fTYy/result.json" +sha256 = "1c1697a14bbb5502668dc4333c4ed720dbdbd73de6589aaa25b521a1b41c6069" +subject_bundle_hash = "sha256:3f28b6de2fdb1ac66016bb3fdf79d635b3eff39a794eee58b6bd16cf32e51f60" +harbor_task_checksum = "9d31daf3abc093441556a97c829282dfd9f15b622ca2b8de462e8122e376b5ae" + +[[metadata.repo2env.evaluation.evidence]] +kind = "oracle" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/0c36ef5246b3/candidates/5d12db5414d2/quality/trials/r0-oracle/tsbatch-50714e834186-0c36ef5246b3-q-5d12db54-r0-oracle/tasksmith-5d12db5414d2__8gmKPPN/result.json" +sha256 = "d3b1183feb8a2a31f768cf96d434e49054784a0fb2e7c6d6c09ebf5cc3b8c686" +subject_bundle_hash = "sha256:3f28b6de2fdb1ac66016bb3fdf79d635b3eff39a794eee58b6bd16cf32e51f60" +harbor_task_checksum = "9d31daf3abc093441556a97c829282dfd9f15b622ca2b8de462e8122e376b5ae" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/0c36ef5246b3/candidates/5d12db5414d2/quality/trials/r0-probe0/tsbatch-50714e834186-0c36ef5246b3-q-5d12db54-r0-probe0/tasksmith-5d12db5414d2__TgPVPt8/result.json" +sha256 = "5e61220023866e8b20ad03bc2fe7c6377ab3238f552df25008e86f49266bc2c2" +subject_bundle_hash = "sha256:687278925c550dc73529865ca9457759fb28417f1fca23d146493e925f40755e" +harbor_task_checksum = "9fb402307af62c573fae1e23bae53bfb96b79e199e604b34fe02312d3b111747" + +[[metadata.repo2env.evaluation.evidence]] +kind = "probe" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/0c36ef5246b3/candidates/5d12db5414d2/quality/trials/r0-probe1/tsbatch-50714e834186-0c36ef5246b3-q-5d12db54-r0-probe1/tasksmith-5d12db5414d2__iCdHqgw/result.json" +sha256 = "86f9179d52ea9f72fd081d2d787488ef742634814940ad5767ccd06886455ab5" +subject_bundle_hash = "sha256:12ac263fd7fb0ad075c2bd41ce698af452f146e00aa36933c7640aaab5809239" +harbor_task_checksum = "e822281205b32d0c21923daa28b4690860854ef93973fa65a94a130d12a38d6c" + +[[metadata.repo2env.evaluation.evidence]] +kind = "rollout" +path = "/Users/adithya/projects/Repo2RLEnv-tasksmith/workspace/tasksmith-scale50/batch-v14/candidates/0c36ef5246b3/candidates/5d12db5414d2/quality/trials/r0-rollout/tsbatch-50714e834186-0c36ef5246b3-q-5d12db54-r0-rollout/tasksmith-5d12db5414d2__Jofc9Ew/result.json" +sha256 = "5b71f78d0ad60d7552da61e49ada644e75ce28e65af6f0f256c96c3e6886032b" +subject_bundle_hash = "sha256:3f28b6de2fdb1ac66016bb3fdf79d635b3eff39a794eee58b6bd16cf32e51f60" +harbor_task_checksum = "9d31daf3abc093441556a97c829282dfd9f15b622ca2b8de462e8122e376b5ae" + +[environment] +cpus = 1 +memory_mb = 2048 +build_timeout_sec = 600 +network_mode = "no-network" + +[agent] +timeout_sec = 600 +user = "learner" +network_mode = "no-network" + +[verifier] +timeout_sec = 150 +user = "root" +network_mode = "no-network" +environment_mode = "separate" + +[verifier.environment] +network_mode = "no-network" +cpus = 1 +memory_mb = 2048 + +[[artifacts]] +source = "/workspace/src/accelerate/__init__.py" + +[[artifacts]] +source = "/workspace/src/accelerate/accelerator.py" + +[[artifacts]] +source = "/workspace/src/accelerate/big_modeling.py" + +[[artifacts]] +source = "/workspace/src/accelerate/checkpointing.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/__init__.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/accelerate_cli.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/config/__init__.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/config/cluster.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/config/config.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/config/config_args.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/config/config_utils.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/config/default.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/config/sagemaker.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/config/update.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/env.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/estimate.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/launch.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/menu/__init__.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/menu/cursor.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/menu/helpers.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/menu/input.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/menu/keymap.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/menu/selection_menu.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/merge.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/test.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/tpu.py" + +[[artifacts]] +source = "/workspace/src/accelerate/commands/utils.py" + +[[artifacts]] +source = "/workspace/src/accelerate/data_loader.py" + +[[artifacts]] +source = "/workspace/src/accelerate/hooks.py" + +[[artifacts]] +source = "/workspace/src/accelerate/inference.py" + +[[artifacts]] +source = "/workspace/src/accelerate/launchers.py" + +[[artifacts]] +source = "/workspace/src/accelerate/local_sgd.py" + +[[artifacts]] +source = "/workspace/src/accelerate/logging.py" + +[[artifacts]] +source = "/workspace/src/accelerate/memory_utils.py" + +[[artifacts]] +source = "/workspace/src/accelerate/optimizer.py" + +[[artifacts]] +source = "/workspace/src/accelerate/scheduler.py" + +[[artifacts]] +source = "/workspace/src/accelerate/state.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/__init__.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/examples.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/__init__.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/external_deps/__init__.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/external_deps/test_metrics.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/external_deps/test_performance.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/external_deps/test_pippy.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/test_cli.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/test_ddp_comm_hook.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/test_distributed_data_loop.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/test_merge_weights.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/test_notebook.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/test_ops.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/test_script.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/scripts/test_sync.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/testing.py" + +[[artifacts]] +source = "/workspace/src/accelerate/test_utils/training.py" + +[[artifacts]] +source = "/workspace/src/accelerate/tracking.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/__init__.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/bnb.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/constants.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/dataclasses.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/deepspeed.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/environment.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/fsdp_utils.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/imports.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/launch.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/megatron_lm.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/memory.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/modeling.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/offload.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/operations.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/other.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/random.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/rich.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/torch_xla.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/tqdm.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/transformer_engine.py" + +[[artifacts]] +source = "/workspace/src/accelerate/utils/versions.py" diff --git a/tasks/tasksmith-5d12db5414d2/tests/Dockerfile b/tasks/tasksmith-5d12db5414d2/tests/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..fcaa882f8cb6f1e7e151216548bf17a32203f047 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/Dockerfile @@ -0,0 +1,9 @@ +FROM python:3.12-slim-bookworm +WORKDIR /workspace +RUN python -m pip install --no-cache-dir certifi==2026.7.22 charset-normalizer==3.5.1 click==8.5.0 filelock==3.32.3 fsspec==2026.7.0 hf-xet==1.6.0 huggingface_hub==0.36.2 idna==3.19 iniconfig==2.3.0 Jinja2==3.1.6 MarkupSafe==3.0.3 mpmath==1.3.0 networkx==3.6.1 numpy==2.5.3 packaging==26.3 parameterized==0.9.0 pluggy==1.6.0 psutil==7.2.2 Pygments==2.21.0 pytest==8.4.2 PyYAML==6.0.3 regex==2024.11.6 requests==2.32.3 safetensors==0.8.0 setuptools==78.1.0 sympy==1.14.0 tokenizers==0.21.4 torch==2.11.0+cpu transformers==4.47.0 tqdm==4.70.1 typing_extensions==4.16.0 urllib3==2.4.0 wheel==0.48.0 --extra-index-url https://download.pytorch.org/whl/cpu +COPY source /workspace +RUN python -m pip install --no-cache-dir -e . +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 +RUN useradd -m -u 1001 grader +COPY grade.py test_driver.py test_results.py contract.json test.sh /tests/ +RUN chmod 755 /tests && chmod 644 /tests/* diff --git a/tasks/tasksmith-5d12db5414d2/tests/contract.json b/tasks/tasksmith-5d12db5414d2/tests/contract.json new file mode 100644 index 0000000000000000000000000000000000000000..aecadb6b6780f9b5ba70026d16d94d98ed5718f9 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/contract.json @@ -0,0 +1 @@ +{"expected_passes": ["tests.tasksmith_behavior::test_no_split_modules_multiple_entries", "tests.tasksmith_behavior::test_no_split_modules_whole_names_not_characters", "tests.tasksmith_behavior::test_explicit_cls_names_not_overridden_by_no_split_modules", "tests.tasksmith_behavior::test_no_split_modules_absent_gives_empty_default", "tests.test_utils.UtilsTester::test_find_device", "tests.test_utils.UtilsTester::test_listify", "tests.test_utils.UtilsTester::test_patch_environment", "tests.test_utils.UtilsTester::test_patch_environment_key_exists", "tests.test_utils.UtilsTester::test_patch_environment_restores_on_error", "tests.test_utils.UtilsTester::test_send_to_device"], "submitted_files": ["src/accelerate/__init__.py", "src/accelerate/accelerator.py", "src/accelerate/big_modeling.py", "src/accelerate/checkpointing.py", "src/accelerate/commands/__init__.py", "src/accelerate/commands/accelerate_cli.py", "src/accelerate/commands/config/__init__.py", "src/accelerate/commands/config/cluster.py", "src/accelerate/commands/config/config.py", "src/accelerate/commands/config/config_args.py", "src/accelerate/commands/config/config_utils.py", "src/accelerate/commands/config/default.py", "src/accelerate/commands/config/sagemaker.py", "src/accelerate/commands/config/update.py", "src/accelerate/commands/env.py", "src/accelerate/commands/estimate.py", "src/accelerate/commands/launch.py", "src/accelerate/commands/menu/__init__.py", "src/accelerate/commands/menu/cursor.py", "src/accelerate/commands/menu/helpers.py", "src/accelerate/commands/menu/input.py", "src/accelerate/commands/menu/keymap.py", "src/accelerate/commands/menu/selection_menu.py", "src/accelerate/commands/merge.py", "src/accelerate/commands/test.py", "src/accelerate/commands/tpu.py", "src/accelerate/commands/utils.py", "src/accelerate/data_loader.py", "src/accelerate/hooks.py", "src/accelerate/inference.py", "src/accelerate/launchers.py", "src/accelerate/local_sgd.py", "src/accelerate/logging.py", "src/accelerate/memory_utils.py", "src/accelerate/optimizer.py", "src/accelerate/scheduler.py", "src/accelerate/state.py", "src/accelerate/test_utils/__init__.py", "src/accelerate/test_utils/examples.py", "src/accelerate/test_utils/scripts/__init__.py", "src/accelerate/test_utils/scripts/external_deps/__init__.py", "src/accelerate/test_utils/scripts/external_deps/test_checkpointing.py", "src/accelerate/test_utils/scripts/external_deps/test_metrics.py", "src/accelerate/test_utils/scripts/external_deps/test_peak_memory_usage.py", "src/accelerate/test_utils/scripts/external_deps/test_performance.py", "src/accelerate/test_utils/scripts/external_deps/test_pippy.py", "src/accelerate/test_utils/scripts/external_deps/test_zero3_integration.py", "src/accelerate/test_utils/scripts/test_cli.py", "src/accelerate/test_utils/scripts/test_ddp_comm_hook.py", "src/accelerate/test_utils/scripts/test_distributed_data_loop.py", "src/accelerate/test_utils/scripts/test_merge_weights.py", "src/accelerate/test_utils/scripts/test_notebook.py", "src/accelerate/test_utils/scripts/test_ops.py", "src/accelerate/test_utils/scripts/test_script.py", "src/accelerate/test_utils/scripts/test_sync.py", "src/accelerate/test_utils/testing.py", "src/accelerate/test_utils/training.py", "src/accelerate/tracking.py", "src/accelerate/utils/__init__.py", "src/accelerate/utils/bnb.py", "src/accelerate/utils/constants.py", "src/accelerate/utils/dataclasses.py", "src/accelerate/utils/deepspeed.py", "src/accelerate/utils/environment.py", "src/accelerate/utils/fsdp_utils.py", "src/accelerate/utils/imports.py", "src/accelerate/utils/launch.py", "src/accelerate/utils/megatron_lm.py", "src/accelerate/utils/memory.py", "src/accelerate/utils/modeling.py", "src/accelerate/utils/offload.py", "src/accelerate/utils/operations.py", "src/accelerate/utils/other.py", "src/accelerate/utils/random.py", "src/accelerate/utils/rich.py", "src/accelerate/utils/torch_xla.py", "src/accelerate/utils/tqdm.py", "src/accelerate/utils/transformer_engine.py", "src/accelerate/utils/versions.py"], "test_paths": ["tests/fsdp/test_fsdp.py::FSDPPluginIntegration::test_sharding_strategy", "tests/fsdp/test_fsdp.py::FSDPPluginIntegration::test_backward_prefetch", "tests/fsdp/test_fsdp.py::FSDPPluginIntegration::test_state_dict_type", "tests/fsdp/test_fsdp.py::FSDPPluginIntegration::test_auto_wrap_policy", "tests/test_utils.py::UtilsTester::test_patch_environment", "tests/test_utils.py::UtilsTester::test_patch_environment_key_exists", "tests/test_utils.py::UtilsTester::test_patch_environment_restores_on_error", "tests/test_utils.py::UtilsTester::test_listify", "tests/test_utils.py::UtilsTester::test_send_to_device", "tests/test_utils.py::UtilsTester::test_find_device", "tests/tasksmith_behavior.py"], "timeout_sec": 120} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/grade.py b/tasks/tasksmith-5d12db5414d2/tests/grade.py new file mode 100644 index 0000000000000000000000000000000000000000..a2eead39a559d14821a1955325a6682abe622a16 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/grade.py @@ -0,0 +1,112 @@ +"""Standalone trusted entry point; copied into each separate verifier image. + +No Repo2RLEnv installation is needed to grade an exported task. Submitted Python +runs as an unprivileged user; this parent owns the result parser and reward file. +""" + +from __future__ import annotations + +import importlib.util +import json +import os +import signal +import stat +import subprocess +import sys +import tempfile +from pathlib import Path + + +def main() -> None: + directory = Path("/tests") + parser_spec = importlib.util.spec_from_file_location( + "test_results", directory / "test_results.py" + ) + parser = importlib.util.module_from_spec(parser_spec) + sys.modules[parser_spec.name] = parser + parser_spec.loader.exec_module(parser) + contract = json.loads((directory / "contract.json").read_text()) + logs = Path("/logs/verifier") + logs.mkdir(parents=True, exist_ok=True) + logs.chmod(0o755) + reward = logs / "reward.txt" + reward.write_text("0\n") + reward.chmod(0o644) + for relative in contract["submitted_files"]: + path = Path("/workspace") / relative + # Artifact uploads are data. Refuse link traversal and special files + # before the child imports any learner-controlled code. + for component in (path, *path.parents): + if component.is_symlink(): + raise ValueError("Submitted source contains a symlink") + if not stat.S_ISREG(path.stat().st_mode) or path.stat().st_size > 8 * 1024 * 1024: + raise ValueError("Submitted source is not a bounded regular file") + os.chown(path, 0, 0) + path.chmod(0o644) + with tempfile.TemporaryDirectory(prefix="r2e-grade-") as temporary: + working = Path(temporary) + os.chown(working, 1001, 1001) + working.chmod(0o700) + report = working / "results.xml" + command = [ + "/usr/local/bin/python", + "-I", + "/tests/test_driver.py", + *contract["test_paths"], + "-q", + "--tb=short", + "-p", + "no:cacheprovider", + f"--junitxml={report}", + ] + with (logs / "stdout.txt").open("w") as stdout, (logs / "stderr.txt").open("w") as stderr: + process = subprocess.Popen( + command, + cwd="/workspace", + stdout=stdout, + stderr=stderr, + user=1001, + group=1001, + extra_groups=[], + start_new_session=True, + env={ + "PATH": "/usr/local/bin:/usr/bin:/bin", + "HOME": temporary, + "PYTHONDONTWRITEBYTECODE": "1", + "PYTEST_DISABLE_PLUGIN_AUTOLOAD": "1", + }, + ) + try: + code = process.wait(timeout=contract["timeout_sec"]) + finally: + # Terminate descendants too: they must not keep modifying the + # child-owned report while the trusted parent checks it. + try: + os.killpg(process.pid, signal.SIGKILL) + except ProcessLookupError: + pass + process.wait() + if report.is_symlink() or not report.is_file() or report.stat().st_size > 16 * 1024 * 1024: + (logs / "result.json").write_text( + json.dumps({"passed": False, "returncode": code, "reason": "invalid_report"}) + ) + return + text = report.read_text() + (logs / "results.xml").write_text(text) + try: + parsed = parser.parse_junit(text, returncode=code) + except ValueError as exc: + (logs / "result.json").write_text( + json.dumps({"passed": False, "returncode": code, "reason": str(exc)}) + ) + return + expected = set(contract["expected_passes"]) + passed = code == 0 and bool(expected) and parsed.passed == expected + (logs / "result.json").write_text( + json.dumps({"passed": passed, "returncode": code, "statuses": parsed.statuses}) + ) + reward.write_text("1\n" if passed else "0\n") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.devcontainer/devcontainer.json b/tasks/tasksmith-5d12db5414d2/tests/source/.devcontainer/devcontainer.json new file mode 100644 index 0000000000000000000000000000000000000000..7a0da2404899e9335e4ccd7559d7af36f825be37 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.devcontainer/devcontainer.json @@ -0,0 +1,29 @@ +// File only needed for VSCode users to have proper Docker based interpreters +{ + "name": "accelerate_dev_environment", + "build": { + // ACTION NEEDED: comment/uncomment the relevant line depending on whether you are in a CPU/GPU environment + "dockerfile": "../docker/accelerate-cpu/Dockerfile" +// "dockerfile": "../docker/accelerate-gpu/Dockerfile" + }, + "runArgs": [ + // ACTION NEEDED: uncomment the next line if your local machine has GPUs available +// "--gpus", "all", + // Enable the docker container to access system resources + "--ipc", "host" + ], + "remoteEnv": { + "PYTHONPATH": "${containerEnv:PATH}:${containerWorkspaceFolder}" + }, + "customizations": { + "vscode": { + "extensions": [ + // Ensure we have IntelliSense in VSCode when running inside container + "ms-python.python" + ] + } + }, + "workspaceFolder": "/workspaces/accelerate", + // Need git for VSCode to color code modifications. Only runs when building environment. + "onCreateCommand": "apt-get update && apt-get install -y git && pip install -e '.[dev]'" +} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml new file mode 100644 index 0000000000000000000000000000000000000000..16111314f4f733d0551f3ce917a58e4ff74bda0e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/ISSUE_TEMPLATE/bug-report.yml @@ -0,0 +1,63 @@ +name: "\U0001F41B Bug Report" +description: Submit a bug report to help us improve Accelerate +body: + - type: markdown + attributes: + value: | + Thanks for taking the time to submit a bug report! 🐛 + If this is not a bug related to the Accelerate library directly, but instead a general question about your code or the library specifically please use the [forums](https://discuss.huggingface.co/c/accelerate/18). + + - type: textarea + id: system-info + attributes: + label: System Info + description: Please share your accelerate configuration with us. You can run the command `accelerate env` and copy-paste its outputs below + render: Shell + placeholder: accelerate version, OS, python version, numpy version, torch version, and accelerate's configuration + validations: + required: true + + - type: checkboxes + id: information-scripts-examples + attributes: + label: Information + description: 'The problem arises when using:' + options: + - label: "The official example scripts" + - label: "My own modified scripts" + + - type: checkboxes + id: information-tasks + attributes: + label: Tasks + description: "The tasks I am working on are:" + options: + - label: "One of the scripts in the examples/ folder of Accelerate or an officially supported `no_trainer` script in the `examples` folder of the `transformers` repo (such as `run_no_trainer_glue.py`)" + - label: "My own task or dataset (give details below)" + + - type: textarea + id: reproduction + validations: + required: true + attributes: + label: Reproduction + description: | + Please provide a code sample that reproduces the problem you ran into. It can be a Colab link or just a code snippet. + If you have code snippets, error messages, stack traces please provide them here as well. + Important! Use code tags to correctly format your code. See https://help.github.com/en/github/writing-on-github/creating-and-highlighting-code-blocks#syntax-highlighting + Do not use screenshots, as they are hard to read and (more importantly) don't allow others to copy-and-paste your code. + + placeholder: | + Steps to reproduce the behavior: + + 1. + 2. + 3. + + - type: textarea + id: expected-behavior + validations: + required: true + attributes: + label: Expected behavior + description: "A clear and concise description of what you would expect to happen." diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/PULL_REQUEST_TEMPLATE.md b/tasks/tasksmith-5d12db5414d2/tests/source/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000000000000000000000000000000000000..6ec3b6498f7093951e1a49e93f22b7984c05551d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,47 @@ +# What does this PR do? + + + + + +Fixes # (issue) + + +## Before submitting +- [ ] This PR fixes a typo or improves the docs (you can dismiss the other checks if that's the case). +- [ ] Did you read the [contributor guideline](https://github.com/huggingface/accelerate/blob/main/CONTRIBUTING.md#submitting-a-pull-request-pr), + Pull Request section? +- [ ] Was this discussed/approved via a Github issue or the [forum](https://discuss.huggingface.co/)? Please add a link + to it if that's the case. +- [ ] Did you make sure to update the documentation with your changes? Here are the + [documentation guidelines](https://github.com/huggingface/accelerate/tree/main/docs), and + [here are tips on formatting docstrings](https://github.com/huggingface/accelerate/tree/main/docs#writing-documentation---specification). +- [ ] Did you write any new necessary tests? + + +## Who can review? + +Anyone in the community is free to review the PR once the tests have passed. Feel free to tag +members/contributors who may be interested in your PR. + + \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build-docker-images-release.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build-docker-images-release.yml new file mode 100644 index 0000000000000000000000000000000000000000..3a5c5052fac608a72a55c66af9414f200d18bb1c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build-docker-images-release.yml @@ -0,0 +1,104 @@ +name: Build Docker images (releases) + +on: + workflow_dispatch: + release: + types: [published] + +concurrency: + group: docker-image-builds + cancel-in-progress: false + +jobs: + get-version: + runs-on: ubuntu-latest + outputs: + version: ${{ steps.step1.outputs.version }} + steps: + - uses: actions/checkout@v3.1.0 + - id: step1 + run: echo "version=$(python setup.py --version)" >> $GITHUB_OUTPUT + + version-cpu: + name: "Latest Accelerate CPU [version]" + runs-on: + group: aws-general-8-plus + needs: get-version + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push CPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-cpu/Dockerfile + push: true + tags: huggingface/accelerate:cpu-release-${{ needs.get-version.outputs.version }} + + version-cuda: + name: "Latest Accelerate GPU [version]" + runs-on: + group: aws-g6-4xlarge-plus + needs: get-version + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu/Dockerfile + push: true + tags: huggingface/accelerate:gpu-release-${{needs.get-version.outputs.version}} + + version-cuda-deepspeed: + name: "Latest Accelerate GPU DeepSpeed [version]" + runs-on: + group: aws-g6-4xlarge-plus + needs: get-version + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu-deepspeed/Dockerfile + push: true + tags: huggingface/accelerate:gpu-deepspeed-release-${{needs.get-version.outputs.version}} + + version-cuda-fp8-transformerengine: + name: "Latest Accelerate GPU FP8 TransformerEngine [version]" + runs-on: + group: aws-g6-4xlarge-plus + needs: get-version + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu/Dockerfile + push: true + tags: huggingface/accelerate:gpu-fp8-transformerengine-release-${{needs.get-version.outputs.version}} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_and_run_tests.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_and_run_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..3169e8546128ff643660891599c2217f413a2e5e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_and_run_tests.yml @@ -0,0 +1,50 @@ +name: Trigger docker images and run tests + +on: + push: + branches: + - main + workflow_dispatch: + +env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + +jobs: + check-for-source: + runs-on: ubuntu-latest + name: Check if setup was changed + outputs: + changed: ${{ steps.was_changed.outputs.changed }} + steps: + - uses: actions/checkout@v3.1.0 + with: + fetch-depth: "2" + + - name: Get changed files + id: changed-files + uses: tj-actions/changed-files@v41 + + - name: Was setup changed + id: was_changed + run: | + for file in ${{ steps.changed-files.outputs.all_changed_files }}; do + if [ `basename "${file}"` == "setup.py" ]; then + echo "changed=1" >> $GITHUB_OUTPUT + fi + done + + build-docker-containers: + needs: check-for-source + if: (github.event_name == 'push') && (needs.check-for-source.outputs.changed == '1') + uses: ./.github/workflows/build_docker_images.yml + secrets: inherit + + run-merge-tests: + needs: build-docker-containers + if: always() + uses: ./.github/workflows/run_merge_tests.yml + + run-integration-tests: + needs: build-docker-containers + if: always() + uses: ./.github/workflows/self_hosted_integration_tests.yml \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_docker_images.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_docker_images.yml new file mode 100644 index 0000000000000000000000000000000000000000..2050bbba7147827c07b51264002b611d6383abc5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_docker_images.yml @@ -0,0 +1,110 @@ +name: Build Docker images (scheduled) + +on: + workflow_dispatch: + workflow_call: + schedule: + - cron: "0 1 * * *" + +concurrency: + group: docker-image-builds + cancel-in-progress: false + +jobs: + latest-cpu: + name: "Latest Accelerate CPU [dev]" + runs-on: + group: aws-general-8-plus + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - name: Get current date + id: date + run: | + echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV + - name: Build and Push CPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-cpu/Dockerfile + push: true + tags: | + huggingface/accelerate:cpu-nightly + huggingface/accelerate:cpu-nightly-${{ env.date }} + + latest-cuda: + name: "Latest Accelerate GPU [dev]" + runs-on: + group: aws-g6-4xlarge-plus + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - name: Get current date + id: date + run: | + echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu/Dockerfile + push: true + tags: | + huggingface/accelerate:gpu-nightly + huggingface/accelerate:gpu-nightly-${{ env.date }} + + latest-cuda-deepspeed: + name: "Latest Accelerate GPU DeepSpeed [dev]" + runs-on: + group: aws-g6-4xlarge-plus + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - name: Get current date + id: date + run: | + echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: docker/accelerate-gpu-deepspeed/Dockerfile + push: true + tags: | + huggingface/accelerate:gpu-deepspeed-nightly + huggingface/accelerate:gpu-deepspeed-nightly-${{ env.date }} + + latest-cuda-fp8-transformerengine: + name: "Latest Accelerate GPU FP8 TransformerEngine [dev]" + runs-on: + group: aws-g6-4xlarge-plus + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v2 + - name: Login to DockerHub + uses: docker/login-action@v2 + with: + username: ${{ secrets.DOCKERHUB_USERNAME }} + password: ${{ secrets.DOCKERHUB_PASSWORD }} + - name: Get current date + id: date + run: | + echo "date=$(date '+%Y-%m-%d')" >> $GITHUB_ENV + - name: Build and Push GPU + uses: docker/build-push-action@v4 + with: + file: benchmarks/fp8/Dockerfile + push: true + tags: huggingface/accelerate:gpu-fp8-transformerengine-nightly-${{ env.date }} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_documentation.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..dc529d9dbfad72b24184ceb7f34a6b2da7dc9512 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_documentation.yml @@ -0,0 +1,18 @@ +name: Build documentation + +on: + push: + branches: + - main + - doc-builder* + - v*-release + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_main_documentation.yml@main + with: + commit_sha: ${{ github.sha }} + package: accelerate + custom_container: huggingface/transformers-doc-builder + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_pr_documentation.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..7b8463e20b3e212d29eacbd31f5c5ae609029b2d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/build_pr_documentation.yml @@ -0,0 +1,17 @@ +name: Build PR Documentation + +on: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.head_ref || github.run_id }} + cancel-in-progress: true + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/build_pr_documentation.yml@main + with: + commit_sha: ${{ github.event.pull_request.head.sha }} + pr_number: ${{ github.event.number }} + package: accelerate + custom_container: huggingface/transformers-doc-builder diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/integration_tests.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/integration_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..59aeb66b6a5c3868e00400806f3a3954f20d19a6 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/integration_tests.yml @@ -0,0 +1,58 @@ +# CI for specifically ensuring integrations work fine (`transformers` mainly) +# Useful tips: +# - New integrations to test should have its own job, and follow a strategy method where we check both +# the pypi and github versions. +# - When checking the latest release of the integration, use +# git checkout $(git describe --tags `git rev-list --tags --max-count=1`) to get the latest release. + +name: Integration Tests + +on: + pull_request: + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "examples/**" + - "setup.py" + types: [opened, synchronize, reopened] + +env: + HF_HOME: ~/hf_cache + +jobs: + run-trainer-tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + steps: + - uses: actions/checkout@v3.1.0 + - name: Set up python 3.8 + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + + - name: Install Accelerate from source + run: | + pip install --upgrade pip + pip install -e . + + - name: Clone and install transformers + run: | + cd .. + git clone https://github.com/huggingface/transformers + cd transformers + pip install .[torch,testing] + + - name: Show installed libraries + run: | + pip freeze + + - name: Run Trainer tests + env: + WANDB_DISABLED: true + run: | + cd ../transformers + pytest -sv tests/trainer diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/nightly.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/nightly.yml new file mode 100644 index 0000000000000000000000000000000000000000..c1eb49e952bfdb930699c34d4c5911a5813e40b0 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/nightly.yml @@ -0,0 +1,233 @@ +name: Self-hosted runner with slow tests (scheduled) + +on: + workflow_dispatch: + schedule: + - cron: "0 2 * * *" + +env: + RUN_SLOW: "yes" + IS_GITHUB_CI: "1" + SLACK_API_TOKEN: ${{ secrets.SLACK_API_TOKEN }} + + +jobs: + run_core_tests_single_gpu: + runs-on: + group: aws-g6-4xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0" + TEST_TYPE: "single_gpu" + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone & pip install + run: | + source activate accelerate + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e . --no-deps + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + run: | + source activate accelerate + make test + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + pip uninstall comet_ml -y + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install slack_sdk tabulate + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_deepspeed_tests_single_gpu: + runs-on: + group: aws-g6-4xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0" + TEST_TYPE: "single_gpu_deepspeed" + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone & pip install + run: | + source activate accelerate + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e . --no-deps + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + run: | + source activate accelerate + make test_deepspeed + + - name: Run Integration tests on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + make test_integrations + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + pip uninstall comet_ml -y + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install slack_sdk tabulate + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_core_tests_multi_gpu: + runs-on: + group: aws-g6-12xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0,1" + TEST_TYPE: "multi_gpu" + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone + run: | + source activate accelerate + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e . --no-deps + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run core and big modeling tests on GPUs + working-directory: accelerate + run: | + source activate accelerate + make test_core + make test_big_modeling + make test_cli + + - name: Run Integration tests on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + make test_integrations + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + pip uninstall comet_ml -y + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install slack_sdk tabulate + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_deepspeed_tests_multi_gpu: + runs-on: + group: aws-g6-12xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0,1" + TEST_TYPE: "multi_gpu_deepspeed" + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone + run: | + source activate accelerate + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e . --no-deps + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run DeepSpeed tests + working-directory: accelerate + run: | + source activate accelerate + make test_deepspeed + + - name: Run Integration tests on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + make test_integrations + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate + pip uninstall comet_ml -y + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install slack_sdk tabulate + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + + run-integration-tests: + if: always() + uses: ./.github/workflows/self_hosted_integration_tests.yml diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/quality.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/quality.yml new file mode 100644 index 0000000000000000000000000000000000000000..bb590777fb42a14264487557351daa264c429050 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/quality.yml @@ -0,0 +1,24 @@ +name: Quality Check + +on: [pull_request] + +jobs: + quality: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3.1.0 + - name: Set up Python 3.8 + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + - name: Install Python dependencies + run: pip install -e .[quality] + - name: Run Quality check + run: make quality + - name: Check if failure + if: ${{ failure() }} + run: | + echo "Quality check failed. Please ensure the right dependency versions are installed with 'pip install -e .[quality]' and rerun 'make style; make quality;'" >> $GITHUB_STEP_SUMMARY + diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/run_merge_tests.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/run_merge_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..92a193a19c6017d9a005bafc3909341e5dde76aa --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/run_merge_tests.yml @@ -0,0 +1,188 @@ +name: Self-hosted runner tests (push to "main") + +on: + workflow_call: + workflow_dispatch: + +env: + TESTING_MOCKED_DATALOADERS: "1" + IS_GITHUB_CI: "1" + +jobs: + run_core_tests_single_gpu: + runs-on: + group: aws-g6-4xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0" + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Install accelerate + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing,test_trackers] -U; + pip install pytest-reportlog tabulate ; + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run CLI tests (use make cli) + working-directory: accelerate + run: | + source activate accelerate; + make test_cli + + - name: Run test on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + make test + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + pip uninstall comet_ml -y; + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install tabulate; + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_deepspeed_tests_single_gpu: + runs-on: + group: aws-g6-4xlarge-plus + env: + CUDA_VISIBLE_DEVICES: "0" + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Install accelerate + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing,test_trackers] -U; + pip install pytest-reportlog tabulate ; + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + make test_deepspeed + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install tabulate; + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_core_tests_multi_gpu: + runs-on: + group: aws-g6-12xlarge-plus + env: + CUDA_VISIBLE_DEVICES: 0,1 + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Update clone + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing,test_trackers] -U; + pip install pytest-reportlog tabulate + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + run: | + source activate accelerate; + make test + + - name: Run examples on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + pip uninstall comet_ml -y; + make test_examples + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + source activate accelerate; + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY + + run_deepspeed_tests_multi_gpu: + runs-on: + group: aws-g6-12xlarge-plus + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + defaults: + run: + shell: bash + steps: + - name: Install accelerate + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing,test_trackers] -U; + pip install pytest-reportlog tabulate ; + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run test on GPUs + working-directory: accelerate + if: always() + run: | + source activate accelerate; + make test_deepspeed + + - name: Generate Report + working-directory: accelerate + if: always() + run: | + pip install tabulate; + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/self_hosted_integration_tests.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/self_hosted_integration_tests.yml new file mode 100644 index 0000000000000000000000000000000000000000..9939c4b826fd2589bcfc7ae5e146534c6fa38e4f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/self_hosted_integration_tests.yml @@ -0,0 +1,127 @@ +# CI for specifically ensuring integrations work fine (`transformers` mainly) on GPUs +# Useful tips: +# - `working-directory` should be set to the root of the repo, which is cloned on the actual CI runner. +# It follows the directory structure of `actions-runner/_work/{repo_name}/{repo_name}/{cloned_repo} on +# prem, but in Actions setting `working-directory` looks just in the `{repo_name}` level. +# - New integrations to test should have its own job, and follow a strategy method where we check both +# the pypi and github versions. +# - Workflow call lets this be called from `build_and_run_tests.yml` +# - When using a docker container, it's recommended to set `--shm-size`, we use 16gb. +name: Integration Tests (push to "main") + +on: + workflow_call: + workflow_dispatch: + +env: + HF_HOME: ~/hf_cache + +defaults: + run: + shell: bash + +jobs: + run-trainer-tests: + container: + image: huggingface/accelerate:gpu-deepspeed-nightly + options: --gpus all --shm-size "16gb" + runs-on: + group: aws-g6-12xlarge-plus + strategy: + fail-fast: false + matrix: + cuda_visible_devices: [ + "0", + "0,1" + ] + steps: + - name: Install transformers + run: | + source activate accelerate; + git clone https://github.com/huggingface/transformers --depth 1; + cd transformers; + pip install .[torch,deepspeed-testing]; + cd ..; + + - name: Install accelerate + run: | + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }} ; + pip install -e .[testing]; + pip uninstall comet_ml wandb dvclive -y + cd ..; + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run trainer tests + working-directory: transformers/ + env: + CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }} + WANDB_DISABLED: true + run: | + source activate accelerate; + pytest -sv tests/trainer + + - name: Run deepspeed tests + working-directory: transformers/ + env: + CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }} + WANDB_DISABLED: true + if: always() + run: | + source activate accelerate; + pytest -sv tests/deepspeed + + - name: Run transformers examples tests + working-directory: transformers/ + env: + CUDA_VISIBLE_DEVICES: ${{ matrix.cuda_visible_devices }} + WANDB_DISABLED: true + run: | + source activate accelerate + pip install -r examples/pytorch/_tests_requirements.txt + pytest -sv examples/pytorch/test_accelerate_examples.py examples/pytorch/test_pytorch_examples.py + + run-skorch-tests: + container: + image: huggingface/accelerate:gpu-nightly + options: --gpus all --shm-size "16gb" + runs-on: + group: aws-g6-12xlarge-plus + strategy: + fail-fast: false + steps: + - name: Install accelerate + run: + source activate accelerate; + git clone https://github.com/huggingface/accelerate; + cd accelerate; + git checkout ${{ github.sha }}; + pip install -e .[testing]; + cd .. + + - name: Install skorch + run: | + source activate accelerate + git clone https://github.com/skorch-dev/skorch; + cd skorch; + git config --global --add safe.directory '*' + git checkout master && git pull + pip install .[testing] + pip install flaky + + - name: Show installed libraries + run: | + source activate accelerate; + pip freeze + + - name: Run skorch tests + working-directory: skorch/ + run: | + source activate accelerate; + pytest -sv -k TestAccelerate diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/stale.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/stale.yml new file mode 100644 index 0000000000000000000000000000000000000000..b91d320141fc8627a7fdf6d77f2c1de42314f613 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/stale.yml @@ -0,0 +1,30 @@ +name: Stale Bot + +on: + schedule: + - cron: "0 15 * * *" + workflow_dispatch: + +jobs: + close_stale_issues: + name: Close Stale Issues + if: github.repository == 'huggingface/accelerate' + runs-on: ubuntu-latest + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + steps: + - uses: actions/checkout@v3.1.0 + + - name: Setup Python + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + + - name: Install requirements + run: | + pip install PyGithub + - name: Close stale issues + run: | + python utils/stale.py diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/test.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/test.yml new file mode 100644 index 0000000000000000000000000000000000000000..9940caac264f62a31762f463f3eef5c630b6bea5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/test.yml @@ -0,0 +1,70 @@ +name: Run Tests + +on: + pull_request: + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "examples/**" + - "setup.py" + types: [opened, synchronize, reopened] + +env: + HF_HOME: ~/hf_cache + TESTING_MOCKED_DATALOADERS: "1" + IS_GITHUB_CI: "1" + +jobs: + run-tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + pytorch-version: [ + latest, + minimum, + ] + test-kind: [ + test_prod, + test_core, + test_cli, + test_big_modeling, + test_deepspeed, + test_fsdp, + test_example_differences, + test_checkpoint_step, + test_checkpoint_epoch, + test_rest + ] + steps: + - uses: actions/checkout@v3.1.0 + - name: Set up python 3.8 + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + + - name: Install the library + run: | + if [[ ${{ matrix.test-kind }} = test_prod ]]; then pip install -e .[test_prod]; fi + if [[ ${{ matrix.test-kind }} != test_prod ]]; then pip install -e .[testing,test_trackers]; fi + if [[ ${{ matrix.test-kind }} = test_rest ]]; then pip uninstall comet_ml -y; fi + if [[ ${{ matrix.pytorch-version }} = minimum ]]; then pip install torchvision==0.18.1 torch==2.3.1; fi + pip install pytest-reportlog tabulate setuptools + + - name: Show installed libraries + run: | + pip freeze + + - name: Run Tests + env: + PYTORCH_VERSION: ${{ matrix.pytorch-version }} + run: | + make ${{ matrix.test-kind }} + + - name: Generate Report + if: always() + run: | + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/test_imports.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/test_imports.yml new file mode 100644 index 0000000000000000000000000000000000000000..90e5229bc860249d9887e635b535b8f0c73e7af8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/test_imports.yml @@ -0,0 +1,55 @@ +name: Run Import Tests + +on: + pull_request: + paths: + - "src/**" + - "tests/**" + - ".github/**" + - "examples/**" + - "setup.py" + types: [opened, synchronize, reopened] + +env: + HF_HOME: ~/hf_cache + TESTING_MOCKED_DATALOADERS: "1" + IS_GITHUB_CI: "1" + +jobs: + run-tests: + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + pytorch-version: [ + latest, + minimum, + ] + steps: + - uses: actions/checkout@v3.1.0 + - name: Set up python 3.8 + uses: actions/setup-python@v3 + with: + python-version: 3.8 + cache: 'pip' + cache-dependency-path: 'setup.py' + + - name: Install the library + run: | + pip install -e . + pip install pytest-reportlog tabulate setuptools git+https://github.com/muellerzr/import-timer + + - name: Show installed libraries + run: | + pip freeze + + - name: Run Import Tests + env: + PYTORCH_VERSION: ${{ matrix.pytorch-version }} + run: | + pytest -sv tests/test_imports.py + + - name: Generate Report + if: always() + run: | + python utils/log_reports.py >> $GITHUB_STEP_SUMMARY diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/trufflehog.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/trufflehog.yml new file mode 100644 index 0000000000000000000000000000000000000000..9cbbf6803724dacc4759b69d7002bb34831e5937 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/trufflehog.yml @@ -0,0 +1,15 @@ +on: + push: + +name: Secret Leaks + +jobs: + trufflehog: + runs-on: ubuntu-latest + steps: + - name: Checkout code + uses: actions/checkout@v4 + with: + fetch-depth: 0 + - name: Secret Scanning + uses: trufflesecurity/trufflehog@main diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/upload_pr_documentation.yml b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/upload_pr_documentation.yml new file mode 100644 index 0000000000000000000000000000000000000000..fd6ed29f9f87a1e6e8364aead9740cf8a059e6a4 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.github/workflows/upload_pr_documentation.yml @@ -0,0 +1,16 @@ +name: Upload PR Documentation + +on: + workflow_run: + workflows: ["Build PR Documentation"] + types: + - completed + +jobs: + build: + uses: huggingface/doc-builder/.github/workflows/upload_pr_documentation.yml@main + with: + package_name: accelerate + secrets: + hf_token: ${{ secrets.HF_DOC_BUILD_PUSH }} + comment_bot_token: ${{ secrets.COMMENT_BOT_TOKEN }} \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.gitignore b/tasks/tasksmith-5d12db5414d2/tests/source/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..ff24394ddad2419878db4f3c27b44b2d8fb686ab --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.gitignore @@ -0,0 +1,144 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# VSCode +.vscode + +# IntelliJ +.idea + +# Mac .DS_Store +.DS_Store + +# More test things +wandb + +# ruff +.ruff_cache diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/.pre-commit-config.yaml b/tasks/tasksmith-5d12db5414d2/tests/source/.pre-commit-config.yaml new file mode 100644 index 0000000000000000000000000000000000000000..1563cffda8f500200924130ddf1e57497f6f2750 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/.pre-commit-config.yaml @@ -0,0 +1,13 @@ +repos: + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.2.1 + hooks: + - id: ruff + args: + - --fix + - id: ruff-format + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: check-merge-conflict + - id: check-yaml diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/CODE_OF_CONDUCT.md b/tasks/tasksmith-5d12db5414d2/tests/source/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000000000000000000000000000000000..c8ad966288a9faeeb71b2fad3ba12f6048e1a03f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/CODE_OF_CONDUCT.md @@ -0,0 +1,129 @@ + +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, religion, or sexual identity +and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best not just for us as individuals, but for the + overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or + advances of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email + address, without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official e-mail address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +feedback@huggingface.co. +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series +of actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or +permanent ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within +the community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.0, available at +https://www.contributor-covenant.org/version/2/0/code_of_conduct.html. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder](https://github.com/mozilla/diversity). + +[homepage]: https://www.contributor-covenant.org + +For answers to common questions about this code of conduct, see the FAQ at +https://www.contributor-covenant.org/faq. Translations are available at +https://www.contributor-covenant.org/translations. diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/CONTRIBUTING.md b/tasks/tasksmith-5d12db5414d2/tests/source/CONTRIBUTING.md new file mode 100644 index 0000000000000000000000000000000000000000..78ad064bd86b39a9f69c3bbd5be3910db1a93d8d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/CONTRIBUTING.md @@ -0,0 +1,249 @@ + + +# How to contribute to 🤗 Accelerate? + +Everyone is welcome to contribute, and we value everybody's contribution. Code +is thus not the only way to help the community. Answering questions, helping +others, reaching out and improving the documentations are immensely valuable to +the community. + +It also helps us if you spread the word: reference the library from blog posts +on the awesome projects it made possible, shout out on Twitter every time it has +helped you, or simply star the repo to say "thank you". + +Whichever way you choose to contribute, please be mindful to respect our +[code of conduct](https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md). + +## You can contribute in so many ways! + +Some of the ways you can contribute to Accelerate: +* Fixing outstanding issues with the existing code; +* Contributing to the examples or to the documentation; +* Submitting issues related to bugs or desired new features. + +## Submitting a new issue or feature request + +Do your best to follow these guidelines when submitting an issue or a feature +request. It will make it easier for us to come back to you quickly and with good +feedback. + +### Did you find a bug? + +The 🤗 Accelerate library is robust and reliable thanks to the users who notify us of +the problems they encounter. So thank you for reporting an issue. + +First, we would really appreciate it if you could **make sure the bug was not +already reported** (use the search bar on Github under Issues). + +Did not find it? :( So we can act quickly on it, please follow these steps: + +* Include your **OS type and version**, the versions of **Python** and **PyTorch**. +* A short, self-contained, code snippet that allows us to reproduce the bug in + less than 30s; +* Provide the with your Accelerate configuration (located by default in `~/.cache/huggingface/accelerate/default_config.yaml`) + +### Do you want a new feature? + +A good feature request addresses the following points: + +1. Motivation first: +* Is it related to a problem/frustration with the library? If so, please explain + why. Providing a code snippet that demonstrates the problem is best. +* Is it related to something you would need for a project? We'd love to hear + about it! +* Is it something you worked on and think could benefit the community? + Awesome! Tell us what problem it solved for you. +2. Write a *full paragraph* describing the feature; +3. Provide a **code snippet** that demonstrates its future use; +4. In case this is related to a paper, please attach a link; +5. Attach any additional information (drawings, screenshots, etc.) you think may help. + +If your issue is well written we're already 80% of the way there by the time you +post it. + +## Submitting a pull request (PR) + +Before writing code, we strongly advise you to search through the existing PRs or +issues to make sure that nobody is already working on the same thing. If you are +unsure, it is always a good idea to open an issue to get some feedback. + +You will need basic `git` proficiency to be able to contribute to +🤗 Accelerate. `git` is not the easiest tool to use but it has the greatest +manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro +Git](https://git-scm.com/book/en/v2) is a very good reference. + +Follow these steps to start contributing: + +1. Fork the [repository](https://github.com/huggingface/accelerate) by + clicking on the 'Fork' button on the repository's page. This creates a copy of the code + under your GitHub user account. + +2. Clone your fork to your local disk, and add the base repository as a remote. The following command + assumes you have your public SSH key uploaded to GitHub. See the following guide for more + [information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository). + + ```bash + $ git clone git@github.com:/accelerate.git + $ cd accelerate + $ git remote add upstream https://github.com/huggingface/accelerate.git + ``` + +3. Create a new branch to hold your development changes, and do this for every new PR you work on. + + Start by synchronizing your `main` branch with the `upstream/main` branch (ore details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)): + + ```bash + $ git checkout main + $ git fetch upstream + $ git merge upstream/main + ``` + + Once your `main` branch is synchronized, create a new branch from it: + + ```bash + $ git checkout -b a-descriptive-name-for-my-changes + ``` + + **Do not** work on the `main` branch. + +4. Set up a development environment by running the following command in a conda or a virtual environment you've created for working on this library: + + ```bash + $ pip install -e ".[dev]" + ``` + + This will install all testing and linting/code quality dependencies for the library (see `quality`, `test_dev`, + `test_prod` targets in [`setup.py`](./setup.py)). + + (If accelerate was already installed in the virtual environment, remove + it with `pip uninstall accelerate` before reinstalling it in editable + mode with the `-e` flag). + + Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using + the provided Dev Container. Documentation on how to get started with dev containers is available [here](https://code.visualstudio.com/docs/remote/containers). + +5. Develop the features on your branch. + + As you work on the features, you should make sure that the test suite + passes. You should run the tests impacted by your changes like this (see + below an explanation regarding the environment variable): + + ```bash + $ pytest tests/.py + ``` + + > For the following commands leveraging the `make` utility, we recommend using the WSL system when running on + > Windows. More information [here](https://docs.microsoft.com/en-us/windows/wsl/about). + + You can also run the full suite with the following command. + + ```bash + $ make test + ``` + + `accelerate` relies on `ruff` to format its source code + consistently. After you make changes, apply automatic style corrections and code verifications + that can't be automated in one go with: + + This target is also optimized to only work with files modified by the PR you're working on. + + If you prefer to run the checks one after the other, the following command apply the + style corrections: + + ```bash + $ make style + ``` + + `accelerate` also uses a few custom scripts to check for coding mistakes. Quality + control runs in CI, however you can also run the same checks with: + + ```bash + $ make quality + ``` + + You can also set up [`pre-commit`](https://pre-commit.com/) to run these checks + automatically as Git commit hooks. + + ```bash + $ pip install pre-commit + $ pre-commit install + ``` + + Once you're happy with your changes, add changed files using `git add` and + make a commit with `git commit` to record your changes locally: + + ```bash + $ git add modified_file.py + $ git commit + ``` + + Please write [good commit messages](https://chris.beams.io/posts/git-commit/). + + It is a good idea to sync your copy of the code with the original + repository regularly. This way you can quickly account for changes: + + ```bash + $ git fetch upstream + $ git rebase upstream/main + ``` + + Push the changes to your account using: + + ```bash + $ git push -u origin a-descriptive-name-for-my-changes + ``` + +6. Once you are satisfied (**and the checklist below is happy too**), go to the + webpage of your fork on GitHub. Click on 'Pull request' to send your changes + to the project maintainers for review. + +7. It's ok if maintainers ask you for changes. It happens to core contributors + too! So everyone can see the changes in the Pull request, work in your local + branch and push the changes to your fork. They will automatically appear in + the pull request. + + +### Checklist + +1. The title of your pull request should be a summary of its contribution; +2. If your pull request addresses an issue, please mention the issue number in + the pull request description to make sure they are linked (and people + consulting the issue know you are working on it); +3. To indicate a work in progress please prefix the title with `[WIP]`, or mark + the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate + it from PRs ready to be merged; +4. Make sure existing tests pass; +5. Add high-coverage tests. No quality testing = no merge. + +See an example of a good PR here: https://github.com/huggingface/accelerate/pull/255 + +### Tests + +An extensive test suite is included to test the library behavior and several examples. Library tests can be found in +the [tests folder](https://github.com/huggingface/accelerate/tree/main/tests). + +We use `pytest` in order to run the tests. From the root of the +repository, here's how to run tests with `pytest` for the library: + +```bash +$ python -m pytest -sv ./tests +``` + +In fact, that's how `make test` is implemented (sans the `pip install` line)! + +You can specify a smaller set of tests in order to test only the feature +you're working on. diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/Dockerfile b/tasks/tasksmith-5d12db5414d2/tests/source/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..5a3c922d33c43968d2d0ca57a1547b27e1bb5016 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/Dockerfile @@ -0,0 +1,7 @@ +FROM python:3.12-slim-bookworm +WORKDIR /workspace +RUN python -m pip install --no-cache-dir certifi==2026.7.22 charset-normalizer==3.5.1 click==8.5.0 filelock==3.32.3 fsspec==2026.7.0 hf-xet==1.6.0 huggingface_hub==0.36.2 idna==3.19 iniconfig==2.3.0 Jinja2==3.1.6 MarkupSafe==3.0.3 mpmath==1.3.0 networkx==3.6.1 numpy==2.5.3 packaging==26.3 parameterized==0.9.0 pluggy==1.6.0 psutil==7.2.2 Pygments==2.21.0 pytest==8.4.2 PyYAML==6.0.3 regex==2024.11.6 requests==2.32.3 safetensors==0.8.0 setuptools==78.1.0 sympy==1.14.0 tokenizers==0.21.4 torch==2.11.0+cpu transformers==4.47.0 tqdm==4.70.1 typing_extensions==4.16.0 urllib3==2.4.0 wheel==0.48.0 --extra-index-url https://download.pytorch.org/whl/cpu +COPY . /workspace +RUN python -m pip install --no-cache-dir -e . +RUN rm -rf /workspace/.git /root/.cache/pip +ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/LICENSE b/tasks/tasksmith-5d12db5414d2/tests/source/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..261eeb9e9f8b2b4b0d119366dda99c6fd7d35c64 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + 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. diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/Makefile b/tasks/tasksmith-5d12db5414d2/tests/source/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..7d01bb8873fb02ddda383aa01608d5219a473d78 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/Makefile @@ -0,0 +1,72 @@ +.PHONY: quality style test docs utils + +check_dirs := . + +# Check that source code meets quality standards + +extra_quality_checks: + python utils/check_copies.py + python utils/check_dummies.py + python utils/check_repo.py + doc-builder style src/accelerate docs/source --max_len 119 + +# this target runs checks on all files +quality: + ruff check $(check_dirs) + ruff format --check $(check_dirs) + doc-builder style src/accelerate docs/source --max_len 119 --check_only + +# Format source code automatically and check is there are any problems left that need manual fixing +style: + ruff check $(check_dirs) --fix + ruff format $(check_dirs) + doc-builder style src/accelerate docs/source --max_len 119 + +# Run tests for the library +test_big_modeling: + python -m pytest -s -v ./tests/test_big_modeling.py ./tests/test_modeling_utils.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_big_modeling.log",) + +test_core: + python -m pytest -s -v ./tests/ --ignore=./tests/test_examples.py --ignore=./tests/deepspeed --ignore=./tests/test_big_modeling.py \ + --ignore=./tests/fsdp --ignore=./tests/test_cli.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_core.log",) + +test_cli: + python -m pytest -s -v ./tests/test_cli.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_cli.log",) + +test_deepspeed: + python -m pytest -s -v ./tests/deepspeed $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_deepspeed.log",) + +test_fsdp: + python -m pytest -s -v ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_fsdp.log",) + +# Since the new version of pytest will *change* how things are collected, we need `deepspeed` to +# run after test_core and test_cli +test: + $(MAKE) test_core + $(MAKE) test_cli + $(MAKE) test_big_modeling + $(MAKE) test_deepspeed + $(MAKE) test_fsdp + +test_examples: + python -m pytest -s -v ./tests/test_examples.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_examples.log",) + +# Broken down example tests for the CI runners +test_integrations: + python -m pytest -s -v ./tests/deepspeed ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_integrations.log",) + +test_example_differences: + python -m pytest -s -v ./tests/test_examples.py::ExampleDifferenceTests $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_example_diff.log",) + +test_checkpoint_epoch: + python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_epoch.log",) + +test_checkpoint_step: + python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_step" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_step.log",) + +# Same as test but used to install only the base dependencies +test_prod: + $(MAKE) test_core + +test_rest: + python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "not by_step and not by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_rest.log",) diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/README.md b/tasks/tasksmith-5d12db5414d2/tests/source/README.md new file mode 100644 index 0000000000000000000000000000000000000000..fc64f02e4fe4f570b155472720320cf165d1ede7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/README.md @@ -0,0 +1,277 @@ + + +

+
+ +
+

+ +

+ + License + Documentation + GitHub release + Contributor Covenant +

+ +

+

Run your *raw* PyTorch training script on any kind of device +

+ +

+ +

+ +## Easy to integrate + +🤗 Accelerate was created for PyTorch users who like to write the training loop of PyTorch models but are reluctant to write and maintain the boilerplate code needed to use multi-GPUs/TPU/fp16. + +🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged. + +Here is an example: + +```diff + import torch + import torch.nn.functional as F + from datasets import load_dataset ++ from accelerate import Accelerator + ++ accelerator = Accelerator() +- device = 'cpu' ++ device = accelerator.device + + model = torch.nn.Transformer().to(device) + optimizer = torch.optim.Adam(model.parameters()) + + dataset = load_dataset('my_dataset') + data = torch.utils.data.DataLoader(dataset, shuffle=True) + ++ model, optimizer, data = accelerator.prepare(model, optimizer, data) + + model.train() + for epoch in range(10): + for source, targets in data: + source = source.to(device) + targets = targets.to(device) + + optimizer.zero_grad() + + output = model(source) + loss = F.cross_entropy(output, targets) + +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() +``` + +As you can see in this example, by adding 5-lines to any standard PyTorch training script you can now run on any kind of single or distributed node setting (single CPU, single GPU, multi-GPUs and TPUs) as well as with or without mixed precision (fp8, fp16, bf16). + +In particular, the same code can then be run without modification on your local machine for debugging or your training environment. + +🤗 Accelerate even handles the device placement for you (which requires a few more changes to your code, but is safer in general), so you can even simplify your training loop further: + +```diff + import torch + import torch.nn.functional as F + from datasets import load_dataset ++ from accelerate import Accelerator + +- device = 'cpu' ++ accelerator = Accelerator() + +- model = torch.nn.Transformer().to(device) ++ model = torch.nn.Transformer() + optimizer = torch.optim.Adam(model.parameters()) + + dataset = load_dataset('my_dataset') + data = torch.utils.data.DataLoader(dataset, shuffle=True) + ++ model, optimizer, data = accelerator.prepare(model, optimizer, data) + + model.train() + for epoch in range(10): + for source, targets in data: +- source = source.to(device) +- targets = targets.to(device) + + optimizer.zero_grad() + + output = model(source) + loss = F.cross_entropy(output, targets) + +- loss.backward() ++ accelerator.backward(loss) + + optimizer.step() +``` + +Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples). + +## Launching script + +🤗 Accelerate also provides an optional CLI tool that allows you to quickly configure and test your training environment before launching the scripts. No need to remember how to use `torch.distributed.run` or to write a specific launcher for TPU training! +On your machine(s) just run: + +```bash +accelerate config +``` + +and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing + +```bash +accelerate launch my_script.py --args_to_my_script +``` + +For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo): + +```bash +accelerate launch examples/nlp_example.py +``` + +This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience. + +You can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`. + +For example, here is how to launch on two GPUs: + +```bash +accelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py +``` + +To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli). + +Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/) + +## Launching multi-CPU run using MPI + +🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well. +Once you have MPI setup on your cluster, just run: +```bash +accelerate config +``` +Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun. +Then, use `accelerate launch` with your script like: +```bash +accelerate launch examples/nlp_example.py +``` +Alternatively, you can use mpirun directly, without using the CLI like: +```bash +mpirun -np 2 python examples/nlp_example.py +``` + +## Launching training using DeepSpeed + +🤗 Accelerate supports training on single/multiple GPUs using DeepSpeed. To use it, you don't need to change anything in your training code; you can set everything using just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`. + +```python +from accelerate import Accelerator, DeepSpeedPlugin + +# deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it +# Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed +deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2) +accelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin) + +# How to save your 🤗 Transformer? +accelerator.wait_for_everyone() +unwrapped_model = accelerator.unwrap_model(model) +unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model)) +``` + +Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue. + +## Launching your training from a notebook + +🤗 Accelerate also provides a `notebook_launcher` function you can use in a notebook to launch a distributed training. This is especially useful for Colab or Kaggle notebooks with a TPU backend. Just define your training loop in a `training_function` then in your last cell, add: + +```python +from accelerate import notebook_launcher + +notebook_launcher(training_function) +``` + +An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [![Open In Colab](https://colab.research.google.com/assets/colab-badge.svg)](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb) + +## Why should I use 🤗 Accelerate? + +You should use 🤗 Accelerate when you want to easily run your training scripts in a distributed environment without having to renounce full control over your training loop. This is not a high-level framework above PyTorch, just a thin wrapper so you don't have to learn a new library. In fact, the whole API of 🤗 Accelerate is in one class, the `Accelerator` object. + +## Why shouldn't I use 🤗 Accelerate? + +You shouldn't use 🤗 Accelerate if you don't want to write a training loop yourself. There are plenty of high-level libraries above PyTorch that will offer you that, 🤗 Accelerate is not one of them. + +## Frameworks using 🤗 Accelerate + +If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around its capabilities, some frameworks and libraries that are built on top of 🤗 Accelerate are listed below: + +* [Amphion](https://github.com/open-mmlab/Amphion) is a toolkit for Audio, Music, and Speech Generation. Its purpose is to support reproducible research and help junior researchers and engineers get started in the field of audio, music, and speech generation research and development. +* [Animus](https://github.com/Scitator/animus) is a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them within [IExperiment](https://github.com/Scitator/animus/blob/main/animus/core.py#L76). +* [Catalyst](https://github.com/catalyst-team/catalyst#getting-started) is a PyTorch framework for Deep Learning Research and Development. It focuses on reproducibility, rapid experimentation, and codebase reuse so you can create something new rather than write yet another train loop. Catalyst provides a [Runner](https://catalyst-team.github.io/catalyst/api/core.html#runner) to connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic. +* [fastai](https://github.com/fastai/fastai#installing) is a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides a [Learner](https://docs.fast.ai/learner.html#Learner) to handle the training, fine-tuning, and inference of deep learning algorithms. +* [Finetuner](https://github.com/jina-ai/finetuner) is a service that enables models to create higher-quality embeddings for semantic search, visual similarity search, cross-modal text<->image search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses. +* [InvokeAI](https://github.com/invoke-ai/InvokeAI) is a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products. +* [Kornia](https://kornia.readthedocs.io/en/latest/get-started/introduction.html) is a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides a [Trainer](https://kornia.readthedocs.io/en/latest/x.html#kornia.x.Trainer) with the specific purpose to train and fine-tune the supported deep learning algorithms within the library. +* [Open Assistant](https://projects.laion.ai/Open-Assistant/) is a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so. +* [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centered around a general-purpose [Trainer](https://pytorch-accelerated.readthedocs.io/en/latest/trainer.html), that places a huge emphasis on simplicity and transparency; enabling users to understand exactly what is going on under the hood, but without having to write and maintain the boilerplate themselves! +* [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion. +* [torchkeras](https://github.com/lyhue1991/torchkeras) is a simple tool for training pytorch model just in a keras style, a dynamic and beautiful plot is provided in notebook to monitor your loss or metric. +* [transformers](https://github.com/huggingface/transformers) as a tool for helping train state-of-the-art machine learning models in PyTorch, Tensorflow, and JAX. (Accelerate is the backend for the PyTorch side). + + +## Installation + +This repository is tested on Python 3.8+ and PyTorch 1.10.0+ + +You should install 🤗 Accelerate in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/). + +First, create a virtual environment with the version of Python you're going to use and activate it. + +Then, you will need to install PyTorch: refer to the [official installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows: + +```bash +pip install accelerate +``` + +## Supported integrations + +- CPU only +- multi-CPU on one node (machine) +- multi-CPU on several nodes (machines) +- single GPU +- multi-GPU on one node (machine) +- multi-GPU on several nodes (machines) +- TPU +- FP16/BFloat16 mixed precision +- FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/) +- DeepSpeed support (Experimental) +- PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental) +- Megatron-LM support (Experimental) + +## Citing 🤗 Accelerate + +If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry. + +```bibtex +@Misc{accelerate, + title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.}, + author = {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan}, + howpublished = {\url{https://github.com/huggingface/accelerate}}, + year = {2022} +} +``` diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/README.md b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/README.md new file mode 100644 index 0000000000000000000000000000000000000000..0a2381ac4182437151c1840847970bb6ade6bcbe --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/README.md @@ -0,0 +1,5 @@ +# Benchmarks + +The folders below contain suites to test various functionalities in Accelerate. + +See their relevant README.md's for more information. diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/README.md b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/README.md new file mode 100644 index 0000000000000000000000000000000000000000..243e9df58ea92bc4148101a5fcf399978cbf07f3 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/README.md @@ -0,0 +1,46 @@ +# Big model inference benchmarks + +Running inference with Accelerate on big models. + +## Setup + +These benchmarks use the `transformers` library: + +```bash +pip install transformers +``` + +To reproduce or test a new setup, run + +```py +python inference_acc.py model_name +``` + +This script supports `gpt-j-6b`, `gpt-neox`, `opt` (30B version) and `T0pp` out of the box, but you can specify any valid checkpoint for `model_name`. + +To force a different `torch_dtype` than the one in the config: `--torch_dtype xxx`. + +If you get an error linked to disk offload, you need to add the option `--disk-offload` + +## Results + +On a setup with two Titan RTXs (24GB of RAM) and 32GB of RAM, we get the following benchmarks (T0pp does not run in float16, which is why it's not included). + +| Model | Model load time | Generation time | dtype | GPU 0 use | GPU 1 use | CPU use | Disk offload | +|:-----:|:---------------:|:---------------:|:-----:|:---------:|:---------:|:-------:|:------------:| +| GPT-J-6B | 8.7s | 0.05s per token | float16 | 11.7GB | 0GB | 0GB | no | +| GPT-J-6B | 12.4s | 0.06s per token | float32 | 21.9GB | 1.5GB | 0GB | no | +| GPT-Neo-X-20B | 30.9s | 0.08s per token | float16 | 21.5GB | 18GB | 0GB | no | +| GPT-Neo-X-20B | 78.2s | 10.72s per token | float32 | 20.3GB | 22.7 GB | 24.4GB | yes | +| T0pp (11B) | 29.4s | 0.05s per token | float32 | 21.1GB | 21.3GB | 0GB | no | +| OPT-30B | 34.5s | 2.37s per token | float16 | 20.7GB | 22.3GB | 14.1GB | no | +| OPT-30B | 112.3s | 33.9s per token | float32 | 20.2GB | 21.2GB | 23.5GB | yes | + +Note on the results: +- using two GPUs instead of one does not slow down generation +- using CPU offload slows down a bit (see OPT-30b) +- using disk offload slows down a lot (need to implement prefetching) + +You will also note that Accelerate does not use anymore GPU and CPU RAM than necessary: +- peak GPU memory is exactly the size of the model put on a given GPU +- peak CPU memory is either the size of the biggest checkpoint shard or the part of the model offloaded on CPU, whichever is bigger. \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/big_model_inference.py b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/big_model_inference.py new file mode 100644 index 0000000000000000000000000000000000000000..d7874e625805c5f9581508dbe69f4456adfdae4a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/big_model_inference.py @@ -0,0 +1,143 @@ +# 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. + +import argparse +import time + +import torch +import transformers +from measures_util import end_measure, log_measures, start_measure +from transformers import AutoConfig, AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer + +from accelerate.utils import compute_module_sizes + + +DEFAULT_MODELS = { + "gpt-j-6b": {"is_causal": True, "model": "sgugger/sharded-gpt-j-6B", "tokenizer": "EleutherAI/gpt-j-6B"}, + "gpt-neox": {"is_causal": True, "model": "EleutherAI/gpt-neox-20b"}, + "opt": {"is_causal": True, "model": "facebook/opt-30b"}, + "T0pp": {"is_causal": False, "model": "bigscience/T0pp", "model_revision": "sharded"}, +} + +PROMPTS = [ + "Hello, my name is", + "Are unicorns real? Unicorns are", + "For the first time in several years,", + "My name is Julien and I am", + "The goal of life is", + "Whenever I'm sad, I like to", +] + + +def parse_args(): + parser = argparse.ArgumentParser(description="Run and time generations on a big model using Accelerate.") + parser.add_argument("model_name", type=str, default=None, help="The name of the model to try.") + parser.add_argument( + "--tokenizer_name", type=str, default=None, help="The name of the tokenizer (if different from the model." + ) + parser.add_argument("--is_causal", type=bool, default=None, help="Whether or not the model is causal.") + parser.add_argument( + "--model_revision", type=str, default=None, help="The revision to use for the model checkpoint." + ) + parser.add_argument("--torch_dtype", type=str, default=None, help="The dtype for the model.") + parser.add_argument("--disk_offload", action="store_true") + + args = parser.parse_args() + + # Sanitize args + if args.model_name in DEFAULT_MODELS: + defaults = DEFAULT_MODELS[args.model_name] + args.model_name = defaults["model"] + if args.tokenizer_name is None: + args.tokenizer_name = defaults.get("tokenizer", args.model_name) + if args.is_causal is None: + args.is_causal = defaults["is_causal"] + if args.model_revision is None: + args.model_revision = defaults.get("model_revision", "main") + + if args.is_causal is None: + raise ValueError("Could not infer the default for `--is_causal`, pass either True or False for it.") + if args.tokenizer_name is None: + args.tokenizer_name = args.model_name + if args.model_revision is None: + args.model_revision = "main" + + return args + + +def main(): + transformers.utils.logging.set_verbosity_error() + args = parse_args() + + if args.torch_dtype is None: + config = AutoConfig.from_pretrained(args.model_name) + torch_dtype = getattr(config, "torch_dtype", torch.float32) + else: + torch_dtype = getattr(torch, args.torch_dtype) + model_cls = AutoModelForCausalLM if args.is_causal else AutoModelForSeq2SeqLM + kwargs = { + "torch_dtype": torch_dtype, + "revision": args.model_revision, + } + if args.disk_offload: + kwargs["offload_folder"] = "tmp_offload" + kwargs["offload_state_dict"] = True + + start_measures = start_measure() + model = model_cls.from_pretrained(args.model_name, device_map="auto", **kwargs) + end_measures = end_measure(start_measures) + log_measures(end_measures, "Model loading") + + module_sizes = compute_module_sizes(model) + device_size = {v: 0 for v in model.hf_device_map.values()} + for module, device in model.hf_device_map.items(): + device_size[device] += module_sizes[module] + message = "\n".join([f"- {device}: {size // 2**20}MiB" for device, size in device_size.items()]) + print(f"\nTheoretical use:\n{message}") + + tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name) + + start_measures = start_measure() + generation_times = [] + gen_tokens = [] + texts_outs = [] + for prompt in PROMPTS: + inputs = tokenizer(prompt, return_tensors="pt").to(0) + tokens = inputs["input_ids"][0].tolist() + before_generate = time.time() + outputs = model.generate(inputs["input_ids"]) + after_generate = time.time() + outputs = outputs[0].tolist() + num_gen_tokens = len(outputs) if outputs[: len(tokens)] != tokens else len(outputs) - len(tokens) + generation_time = after_generate - before_generate + + text_out = tokenizer.decode(outputs, skip_special_tokens=True) + texts_outs.append(text_out) + generation_times.append(generation_time) + gen_tokens.append(num_gen_tokens) + print(f"Prompt: {prompt}\nGeneration {text_out}\nIn {generation_time:.2f}s for {num_gen_tokens} tokens\n") + + end_measures = end_measure(start_measures) + log_measures(end_measures, "Model generation") + + generation_times_per_token = [gen / tok for gen, tok in zip(generation_times, gen_tokens)] + avg_gen = sum(generation_times_per_token) / len(generation_times) + print(f"Average time of generation per token: {avg_gen:.2f}s") + print(f"First generation (avg time per token): {generation_times_per_token[0]:.2f}s") + avg_gen = sum(generation_times_per_token[1:]) / (len(generation_times_per_token) - 1) + print(f"Average time of generation per token (excluding the first): {avg_gen:.2f}s") + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/measures_util.py b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/measures_util.py new file mode 100644 index 0000000000000000000000000000000000000000..f22c0792f45f98c7719eb5a3314865020515658e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/big_model_inference/measures_util.py @@ -0,0 +1,98 @@ +# 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. +import gc +import threading +import time + +import psutil +import torch + + +class PeakCPUMemory: + def __init__(self): + self.process = psutil.Process() + self.peak_monitoring = False + + def peak_monitor(self): + self.cpu_memory_peak = -1 + + while True: + self.cpu_memory_peak = max(self.process.memory_info().rss, self.cpu_memory_peak) + + # can't sleep or will not catch the peak right (this comment is here on purpose) + if not self.peak_monitoring: + break + + def start(self): + self.peak_monitoring = True + self.thread = threading.Thread(target=self.peak_monitor) + self.thread.daemon = True + self.thread.start() + + def stop(self): + self.peak_monitoring = False + self.thread.join() + return self.cpu_memory_peak + + +cpu_peak_tracker = PeakCPUMemory() + + +def start_measure(): + # Time + measures = {"time": time.time()} + + gc.collect() + torch.cuda.empty_cache() + + # CPU mem + measures["cpu"] = psutil.Process().memory_info().rss + cpu_peak_tracker.start() + + # GPU mem + for i in range(torch.cuda.device_count()): + measures[str(i)] = torch.cuda.memory_allocated(i) + torch.cuda.reset_peak_memory_stats() + + return measures + + +def end_measure(start_measures): + # Time + measures = {"time": time.time() - start_measures["time"]} + + gc.collect() + torch.cuda.empty_cache() + + # CPU mem + measures["cpu"] = (psutil.Process().memory_info().rss - start_measures["cpu"]) / 2**20 + measures["cpu-peak"] = (cpu_peak_tracker.stop() - start_measures["cpu"]) / 2**20 + + # GPU mem + for i in range(torch.cuda.device_count()): + measures[str(i)] = (torch.cuda.memory_allocated(i) - start_measures[str(i)]) / 2**20 + measures[f"{i}-peak"] = (torch.cuda.max_memory_allocated(i) - start_measures[str(i)]) / 2**20 + + return measures + + +def log_measures(measures, description): + print(f"{description}:") + print(f"- Time: {measures['time']:.2f}s") + for i in range(torch.cuda.device_count()): + print(f"- GPU {i} allocated: {measures[str(i)]:.2f}MiB") + peak = measures[f"{i}-peak"] + print(f"- GPU {i} peak: {peak:.2f}MiB") + print(f"- CPU RAM allocated: {measures['cpu']:.2f}MiB") + print(f"- CPU RAM peak: {measures['cpu-peak']:.2f}MiB") diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/Dockerfile b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..88c21934d4eb435565916376997fe16811057fb6 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/Dockerfile @@ -0,0 +1,12 @@ +FROM nvcr.io/nvidia/pytorch:24.07-py3 + +RUN pip install transformers evaluate datasets +RUN git clone https://github.com/huggingface/accelerate.git + +RUN cd accelerate && \ + pip install -e . && \ + cd benchmarks/fp8 + +RUN /bin/bash + + diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/README.md b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/README.md new file mode 100644 index 0000000000000000000000000000000000000000..71fb42dbdc192d4493d92c265fdaa62ec4eb5b34 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/README.md @@ -0,0 +1,32 @@ +# FP8 Benchmarks + +Comparing and running [TransformerEngine](https://github.com/NVIDIA/TransformerEngine) FP8 with accelerate + +## Overview + +This repo provides scripts which compare native TransformerEngine model training against `accelerate`'s own integration. Each modeling type is segmented out via a script, supporting the following: + +* Single GPU training (`non_distributed.py`) +* Multi-GPU training via DistributedDataParallelism (`ddp.py`) +* Fully Sharded Data Parallelism (`fsdp.py`) +* DeepSpeed ZeRO 1-3 (`deepspeed.py`) + +To run them, it's recommended to use a docker image (see the attached `Dockerfile`) and not install `TransformerEngine` manually. + +## Running: + +There are official Docker images located at `huggingface/accelerate:gpu-fp8-transformerengine-nightly` which can be used. + +You can run all scripts using the core `accelerate launch` command without any `accelerate config` being needed. + +For single GPU, run it via `python`: + +```bash +python non_distributed.py +``` + +For the rest, run it via `accelerate launch`: + +```bash +accelerate launch ddp.py # or distrib_deepspeed.py, ddp.py +``` \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/ddp.py b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/ddp.py new file mode 100644 index 0000000000000000000000000000000000000000..d14e086ce71845f38d3b8a349f00822510cb6bc3 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/ddp.py @@ -0,0 +1,143 @@ +# Copyright 2024 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. + +""" +This script tests to ensure that `accelerate` performs at the same level as raw `TransformersEngine`. + +This particular script verifies this for DDP training. +""" +import evaluate +import torch +import transformer_engine.common.recipe as te_recipe +import transformer_engine.pytorch as te +from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities +from torch.nn.parallel import DistributedDataParallel as DDP +from transformer_engine.common.recipe import DelayedScaling + +from accelerate import Accelerator +from accelerate.state import AcceleratorState +from accelerate.utils import FP8RecipeKwargs, set_seed +from accelerate.utils.transformer_engine import convert_model + + +MODEL_NAME = "bert-base-cased" +METRIC = evaluate.load("glue", "mrpc") + + +def train_baseline(): + set_seed(42) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME) + accelerator = Accelerator() + device = accelerator.device + model.to(device) + + # Convert the model to TE + old_named_params = get_named_parameters(model) + + with torch.no_grad(): + convert_model(model) + + FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"} + fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS) + + new_named_params = get_named_parameters(model) + + # Convert the model to DDP + device_ids, output_device = [accelerator.local_process_index], accelerator.local_process_index + model = DDP(model, device_ids=device_ids, output_device=output_device) + + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + for param_group in optimizer.param_groups: + param_group["params"] = [mapping[p] for p in param_group["params"]] + + base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + model.train() + + for _ in range(2): + for batch in train_dataloader: + with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe): + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + batch = batch.to(device) + outputs = model(**batch) + loss = outputs.loss + loss.backward() + optimizer.step() + optimizer.zero_grad() + lr_scheduler.step() + + trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + + assert ( + trained_model_results["accuracy"] > base_model_results["accuracy"] + ), f'Accuracy should be higher for the trained model: {trained_model_results["accuracy"]} > {base_model_results["accuracy"]}' + assert ( + trained_model_results["f1"] > base_model_results["f1"] + ), f'F1 score should be higher for the trained model: {trained_model_results["f1"]} > {base_model_results["f1"]}' + + return base_model_results, trained_model_results + + +def train_integration(): + FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"} + kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)] + AcceleratorState()._reset_state(True) + accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=kwargs_handlers) + set_seed(42) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( + MODEL_NAME, accelerator=accelerator + ) + + model, optimizer = accelerator.prepare(model, optimizer) + base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + model.train() + + for _ in range(2): + for batch in train_dataloader: + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() + lr_scheduler.step() + + trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + + assert ( + trained_model_results["accuracy"] > base_model_results["accuracy"] + ), f'Accuracy should be higher for the trained model: {trained_model_results["accuracy"]} > {base_model_results["accuracy"]}' + assert ( + trained_model_results["f1"] > base_model_results["f1"] + ), f'F1 score should be higher for the trained model: {trained_model_results["f1"]} > {base_model_results["f1"]}' + + return base_model_results, trained_model_results + + +if __name__ == "__main__": + baseline_not_trained, baseline_trained = train_baseline() + accelerator_not_trained, accelerator_trained = train_integration() + + assert ( + baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"] + ), f'Accuracy should be the same for the baseline and accelerator: {baseline_not_trained["accuracy"]} == {accelerator_not_trained["accuracy"]}' + assert ( + baseline_not_trained["f1"] == accelerator_not_trained["f1"] + ), f'F1 score should be the same for the baseline and accelerator: {baseline_not_trained["f1"]} == {accelerator_not_trained["f1"]}' + assert ( + baseline_trained["accuracy"] == accelerator_trained["accuracy"] + ), f'Accuracy should be the same for the baseline and accelerator: {baseline_trained["accuracy"]} == {accelerator_trained["accuracy"]}' + assert ( + baseline_trained["f1"] == accelerator_trained["f1"] + ), f'F1 score should be the same for the baseline and accelerator: {baseline_trained["f1"]} == {accelerator_trained["f1"]}' + + torch.distributed.destroy_process_group() diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/distrib_deepspeed.py b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/distrib_deepspeed.py new file mode 100644 index 0000000000000000000000000000000000000000..291d09ec103b2697846af600583099b4e86bd74e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/distrib_deepspeed.py @@ -0,0 +1,189 @@ +# Copyright 2024 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. + +""" +This script tests to ensure that `accelerate` performs at the same level as raw `TransformersEngine`. + +This particular script verifies this for DDP training. +""" +from unittest.mock import patch + +import deepspeed +import evaluate +import torch +import transformer_engine.common.recipe as te_recipe +import transformer_engine.pytorch as te +from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities +from transformer_engine.common.recipe import DelayedScaling + +from accelerate import Accelerator, DeepSpeedPlugin +from accelerate.state import AcceleratorState +from accelerate.utils import FP8RecipeKwargs, set_seed +from accelerate.utils.transformer_engine import convert_model + + +MODEL_NAME = "bert-base-cased" +METRIC = evaluate.load("glue", "mrpc") + + +def train_baseline(zero_stage: int = 1): + # This forces transformers to think Zero-3 Init should be used + with patch("transformers.integrations.deepspeed.is_deepspeed_zero3_enabled") as mock: + mock.return_value = zero_stage == 3 + set_seed(42) + + accelerator = Accelerator() + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( + MODEL_NAME, accelerator=accelerator + ) + + # Convert the model to TE + old_named_params = get_named_parameters(model) + + with torch.no_grad(): + convert_model(model) + new_named_params = get_named_parameters(model) + + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + for param_group in optimizer.param_groups: + param_group["params"] = [mapping[p] for p in param_group["params"]] + + FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"} + fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS) + + import numpy as np + + config = { + "train_batch_size": 32, + "train_micro_batch_size_per_gpu": 16, + "gradient_accumulation_steps": 1, + "zero_optimization": { + "stage": zero_stage, + "offload_optimizer": {"device": "none", "nvme_path": None}, + "offload_param": {"device": "none", "nvme_path": None}, + "stage3_gather_16bit_weights_on_model_save": False, + }, + "gradient_clipping": 1.0, + "steps_per_print": np.inf, + "bf16": {"enabled": True}, + "fp16": {"enabled": False}, + "zero_allow_untested_optimizer": True, + } + + ( + model, + optimizer, + _, + _, + ) = deepspeed.initialize( + model=model, + optimizer=optimizer, + config_params=config, + ) + + base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + model.train() + + model_outputs = [] + data = [] + + for _ in range(2): + for batch in train_dataloader: + with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe): + outputs = model(**batch) + data.append(batch.to("cpu")) + model_outputs.append(outputs.logits.to("cpu")) + loss = outputs.loss + model.backward(loss) + model.step() + for _ in range(accelerator.num_processes): + lr_scheduler.step() + + trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + model.destroy() + assert ( + trained_model_results["accuracy"] > base_model_results["accuracy"] + ), f'Accuracy should be higher for the trained model: {trained_model_results["accuracy"]} > {base_model_results["accuracy"]}' + assert ( + trained_model_results["f1"] > base_model_results["f1"] + ), f'F1 score should be higher for the trained model: {trained_model_results["f1"]} > {base_model_results["f1"]}' + + return base_model_results, trained_model_results, model_outputs, data + + +def train_integration(zero_stage: int = 1): + set_seed(42) + FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"} + kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)] + AcceleratorState()._reset_state(True) + deepspeed_plugin = DeepSpeedPlugin( + zero_stage=zero_stage, + zero3_init_flag=zero_stage == 3, + ) + accelerator = Accelerator( + mixed_precision="fp8", kwargs_handlers=kwargs_handlers, deepspeed_plugin=deepspeed_plugin + ) + accelerator.state.deepspeed_plugin.deepspeed_config["train_micro_batch_size_per_gpu"] = 16 + + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( + MODEL_NAME, accelerator=accelerator + ) + + model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) + base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + model.train() + model_outputs = [] + data = [] + for _ in range(2): + for batch in train_dataloader: + outputs = model(**batch) + data.append(batch.to("cpu")) + model_outputs.append(outputs.logits.to("cpu")) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + model.destroy() + assert ( + trained_model_results["accuracy"] > base_model_results["accuracy"] + ), f'Accuracy should be higher for the trained model: {trained_model_results["accuracy"]} > {base_model_results["accuracy"]}' + assert ( + trained_model_results["f1"] > base_model_results["f1"] + ), f'F1 score should be higher for the trained model: {trained_model_results["f1"]} > {base_model_results["f1"]}' + + return base_model_results, trained_model_results, model_outputs, data + + +if __name__ == "__main__": + # for zero_stage in [1, 2, 3]: + zero_stage = 1 + baseline_not_trained, baseline_trained, baseline_outputs, baseline_data = train_baseline(zero_stage) + accelerator_not_trained, accelerator_trained, accelerator_outputs, accelerator_data = train_integration(zero_stage) + assert ( + baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"] + ), f'ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_not_trained["accuracy"]} == {accelerator_not_trained["accuracy"]}' + assert ( + baseline_not_trained["f1"] == accelerator_not_trained["f1"] + ), f'ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_not_trained["f1"]} == {accelerator_not_trained["f1"]}' + assert ( + baseline_trained["accuracy"] == accelerator_trained["accuracy"] + ), f'ZERO stage {zero_stage}: Accuracy should be the same for the baseline and accelerator: {baseline_trained["accuracy"]} == {accelerator_trained["accuracy"]}' + assert ( + baseline_trained["f1"] == accelerator_trained["f1"] + ), f'ZERO stage {zero_stage}: F1 score should be the same for the baseline and accelerator: {baseline_trained["f1"]} == {accelerator_trained["f1"]}' + + torch.distributed.destroy_process_group() diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/fp8_utils.py b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/fp8_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..d28702e05ff0bbd77d0a51428082336fb5314181 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/fp8_utils.py @@ -0,0 +1,116 @@ +# Copyright 2024 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. +import torch + + +def get_dataloaders(model_name: str, batch_size: int = 16): + from datasets import load_dataset + from torch.utils.data import DataLoader + from transformers import AutoTokenizer + + tokenizer = AutoTokenizer.from_pretrained(model_name) + datasets = load_dataset("glue", "mrpc") + + def tokenize_function(examples): + # max_length=None => use the model max length (it's actually the default) + outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None) + return outputs + + # Apply the method we just defined to all the examples in all the splits of the dataset + # starting with the main process first: + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) + + # We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the + # transformers library + tokenized_datasets = tokenized_datasets.rename_column("label", "labels") + + def collate_fn(examples): + return tokenizer.pad( + examples, + padding="longest", + pad_to_multiple_of=16, # Specific for FP8 + return_tensors="pt", + ) + + # Instantiate dataloaders. + train_dataloader = DataLoader( + tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True + ) + eval_dataloader = DataLoader( + tokenized_datasets["validation"], + shuffle=False, + collate_fn=collate_fn, + batch_size=16, + drop_last=True, + ) + + return train_dataloader, eval_dataloader + + +def get_training_utilities(model_name: str, batch_size: int = 16, accelerator=None): + """ + Returns a tuple of: + - Model + - Optimizer + - Train dataloader (prepared) + - Eval dataloader (prepared) + - LR Scheduler + Suitable for training on the MRPC dataset + """ + from torch.optim import AdamW + from transformers import AutoModelForSequenceClassification, get_linear_schedule_with_warmup + + from accelerate import Accelerator + + if accelerator is None: + accelerator = Accelerator() + model = AutoModelForSequenceClassification.from_pretrained(model_name) + train_dataloader, eval_dataloader = get_dataloaders(model_name, batch_size) + optimizer = AdamW(model.parameters(), lr=0.0001) + lr_scheduler = get_linear_schedule_with_warmup( + optimizer=optimizer, + num_warmup_steps=100, + num_training_steps=len(train_dataloader) * 2, + ) + train_dataloader, eval_dataloader = accelerator.prepare(train_dataloader, eval_dataloader) + return model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + + +def get_named_parameters(model): + """ + Same thing as `Accelerator.get_named_parameters` Returns a list of the named parameters of the model (extracted + from parallel) + """ + from accelerate.utils import extract_model_from_parallel + + model = extract_model_from_parallel(model) + return {n: p for n, p in model.named_parameters()} + + +def evaluate_model(model, dataloader, metric, accelerator=None): + "Turns model to .eval(), runs dataloader, calculates metric, then turns eval back on" + model.eval() + for step, batch in enumerate(dataloader): + with torch.no_grad(): + outputs = model(**batch) + predictions = outputs.logits.argmax(dim=-1) + references = batch["labels"] + if accelerator is not None and accelerator.num_processes > 1: + predictions, references = accelerator.gather_for_metrics((predictions, references)) + metric.add_batch(predictions=predictions, references=references) + return metric.compute() diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/fsdp.py b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/fsdp.py new file mode 100644 index 0000000000000000000000000000000000000000..42d35e0dd5eb51e132e0dbb42d659730a5593eb5 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/fsdp.py @@ -0,0 +1,160 @@ +# Copyright 2024 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. + +""" +This script tests to ensure that `accelerate` performs at the same level as raw `TransformersEngine`. + +This particular script verifies this for FSDP training. +""" +from functools import partial + +import evaluate +import torch +import transformer_engine.common.recipe as te_recipe +import transformer_engine.pytorch as te +from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities +from torch.distributed.fsdp import FullyShardedDataParallel as FSDP +from torch.distributed.fsdp import MixedPrecision +from torch.distributed.fsdp.wrap import transformer_auto_wrap_policy +from transformer_engine.common.recipe import DelayedScaling +from transformers.models.bert import BertLayer + +from accelerate import Accelerator +from accelerate import FullyShardedDataParallelPlugin as FSDPPlugin +from accelerate.state import AcceleratorState +from accelerate.utils import FP8RecipeKwargs, set_seed +from accelerate.utils.transformer_engine import convert_model + + +MODEL_NAME = "bert-base-cased" +METRIC = evaluate.load("glue", "mrpc") + +FSDP_WRAP_POLICY = partial(transformer_auto_wrap_policy, transformer_layer_cls={BertLayer}) + + +def train_baseline(): + set_seed(42) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME) + accelerator = Accelerator() + device = accelerator.device + model.to(device) + + # Convert the model to TE + old_named_params = get_named_parameters(model) + + with torch.no_grad(): + convert_model(model) + + FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"} + fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS) + + new_named_params = get_named_parameters(model) + + # Convert the model to FSDP + model = FSDP( + model, + use_orig_params=True, + mixed_precision=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32), + auto_wrap_policy=FSDP_WRAP_POLICY, + ) + + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + for param_group in optimizer.param_groups: + param_group["params"] = [mapping[p] for p in param_group["params"]] + + base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + model.train() + + for _ in range(2): + for batch in train_dataloader: + with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe): + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + batch = batch.to(device) + outputs = model(**batch) + loss = outputs.loss + loss.backward() + optimizer.step() + optimizer.zero_grad() + lr_scheduler.step() + + trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + + assert ( + trained_model_results["accuracy"] > base_model_results["accuracy"] + ), f'Accuracy should be higher for the trained model: {trained_model_results["accuracy"]} > {base_model_results["accuracy"]}' + assert ( + trained_model_results["f1"] > base_model_results["f1"] + ), f'F1 score should be higher for the trained model: {trained_model_results["f1"]} > {base_model_results["f1"]}' + + return base_model_results, trained_model_results + + +def train_integration(): + FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"} + kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)] + AcceleratorState()._reset_state(True) + fsdp_plugin = FSDPPlugin( + auto_wrap_policy=FSDP_WRAP_POLICY, + use_orig_params=True, + mixed_precision_policy=MixedPrecision(param_dtype=torch.bfloat16, reduce_dtype=torch.float32), + ) + accelerator = Accelerator(mixed_precision="fp8", fsdp_plugin=fsdp_plugin, kwargs_handlers=kwargs_handlers) + set_seed(42) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( + MODEL_NAME, accelerator=accelerator + ) + + model, optimizer = accelerator.prepare(model, optimizer) + base_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + model.train() + + for _ in range(2): + for batch in train_dataloader: + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() + lr_scheduler.step() + + trained_model_results = evaluate_model(model, eval_dataloader, METRIC, accelerator=accelerator) + + assert ( + trained_model_results["accuracy"] > base_model_results["accuracy"] + ), f'Accuracy should be higher for the trained model: {trained_model_results["accuracy"]} > {base_model_results["accuracy"]}' + assert ( + trained_model_results["f1"] > base_model_results["f1"] + ), f'F1 score should be higher for the trained model: {trained_model_results["f1"]} > {base_model_results["f1"]}' + + return base_model_results, trained_model_results + + +if __name__ == "__main__": + baseline_not_trained, baseline_trained = train_baseline() + accelerator_not_trained, accelerator_trained = train_integration() + + assert ( + baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"] + ), f'Accuracy should be the same for the baseline and accelerator: {baseline_not_trained["accuracy"]} == {accelerator_not_trained["accuracy"]}' + assert ( + baseline_not_trained["f1"] == accelerator_not_trained["f1"] + ), f'F1 score should be the same for the baseline and accelerator: {baseline_not_trained["f1"]} == {accelerator_not_trained["f1"]}' + assert ( + baseline_trained["accuracy"] == accelerator_trained["accuracy"] + ), f'Accuracy should be the same for the baseline and accelerator: {baseline_trained["accuracy"]} == {accelerator_trained["accuracy"]}' + assert ( + baseline_trained["f1"] == accelerator_trained["f1"] + ), f'F1 score should be the same for the baseline and accelerator: {baseline_trained["f1"]} == {accelerator_trained["f1"]}' + + torch.distributed.destroy_process_group() diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/non_distributed.py b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/non_distributed.py new file mode 100644 index 0000000000000000000000000000000000000000..e7acf1c3dbc546cfbc08348b2d24bb16ef74dc06 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/benchmarks/fp8/non_distributed.py @@ -0,0 +1,131 @@ +# Copyright 2024 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. + +""" +This script tests to ensure that `accelerate` performs at the same level as raw `TransformersEngine`. + +This particular script verifies this for single GPU training. +""" +import evaluate +import torch +import transformer_engine.common.recipe as te_recipe +import transformer_engine.pytorch as te +from fp8_utils import evaluate_model, get_named_parameters, get_training_utilities +from transformer_engine.common.recipe import DelayedScaling + +from accelerate import Accelerator +from accelerate.state import AcceleratorState +from accelerate.utils import FP8RecipeKwargs, set_seed +from accelerate.utils.transformer_engine import convert_model + + +MODEL_NAME = "bert-base-cased" +METRIC = evaluate.load("glue", "mrpc") + + +def train_baseline(): + set_seed(42) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities(MODEL_NAME) + + # Convert the model to TE + old_named_params = get_named_parameters(model) + + with torch.no_grad(): + convert_model(model) + + new_named_params = get_named_parameters(model) + mapping = {p: new_named_params[n] for n, p in old_named_params.items()} + for param_group in optimizer.param_groups: + param_group["params"] = [mapping[p] for p in param_group["params"]] + + FP8_RECIPE_KWARGS = {"fp8_format": te_recipe.Format.HYBRID, "amax_history_len": 32, "amax_compute_algo": "max"} + fp8_recipe = DelayedScaling(**FP8_RECIPE_KWARGS) + + model.to("cuda") + base_model_results = evaluate_model(model, eval_dataloader, METRIC) + model.train() + + for batch in train_dataloader: + with te.fp8_autocast(enabled=True, fp8_recipe=fp8_recipe): + with torch.autocast(device_type="cuda", dtype=torch.bfloat16): + batch = batch.to("cuda") + outputs = model(**batch) + loss = outputs.loss + loss.backward() + optimizer.step() + optimizer.zero_grad() + lr_scheduler.step() + + trained_model_results = evaluate_model(model, eval_dataloader, METRIC) + + assert ( + trained_model_results["accuracy"] > base_model_results["accuracy"] + ), f'Accuracy should be higher for the trained model: {trained_model_results["accuracy"]} > {base_model_results["accuracy"]}' + assert ( + trained_model_results["f1"] > base_model_results["f1"] + ), f'F1 score should be higher for the trained model: {trained_model_results["f1"]} > {base_model_results["f1"]}' + + return base_model_results, trained_model_results + + +def train_integration(): + FP8_RECIPE_KWARGS = {"fp8_format": "HYBRID", "amax_history_len": 32, "amax_compute_algo": "max"} + kwargs_handlers = [FP8RecipeKwargs(backend="TE", **FP8_RECIPE_KWARGS)] + AcceleratorState()._reset_state(True) + accelerator = Accelerator(mixed_precision="fp8", kwargs_handlers=kwargs_handlers) + set_seed(42) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = get_training_utilities( + MODEL_NAME, accelerator=accelerator + ) + + model, optimizer, lr_scheduler = accelerator.prepare(model, optimizer, lr_scheduler) + base_model_results = evaluate_model(model, eval_dataloader, METRIC) + model.train() + + for batch in train_dataloader: + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() + lr_scheduler.step() + + trained_model_results = evaluate_model(model, eval_dataloader, METRIC) + + assert ( + trained_model_results["accuracy"] > base_model_results["accuracy"] + ), f'Accuracy should be higher for the trained model: {trained_model_results["accuracy"]} > {base_model_results["accuracy"]}' + assert ( + trained_model_results["f1"] > base_model_results["f1"] + ), f'F1 score should be higher for the trained model: {trained_model_results["f1"]} > {base_model_results["f1"]}' + + return base_model_results, trained_model_results + + +if __name__ == "__main__": + baseline_not_trained, baseline_trained = train_baseline() + accelerator_not_trained, accelerator_trained = train_integration() + + assert ( + baseline_not_trained["accuracy"] == accelerator_not_trained["accuracy"] + ), f'Accuracy should be the same for the baseline and accelerator: {baseline_not_trained["accuracy"]} == {accelerator_not_trained["accuracy"]}' + assert ( + baseline_not_trained["f1"] == accelerator_not_trained["f1"] + ), f'F1 score should be the same for the baseline and accelerator: {baseline_not_trained["f1"]} == {accelerator_not_trained["f1"]}' + assert ( + baseline_trained["accuracy"] == accelerator_trained["accuracy"] + ), f'Accuracy should be the same for the baseline and accelerator: {baseline_trained["accuracy"]} == {accelerator_trained["accuracy"]}' + assert ( + baseline_trained["f1"] == accelerator_trained["f1"] + ), f'F1 score should be the same for the baseline and accelerator: {baseline_trained["f1"]} == {accelerator_trained["f1"]}' diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docker/README.md b/tasks/tasksmith-5d12db5414d2/tests/source/docker/README.md new file mode 100644 index 0000000000000000000000000000000000000000..2e19e6caa4ae26b61dec7602f02199d3a4daf036 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docker/README.md @@ -0,0 +1,74 @@ + + +# Official Hugging Face Accelerate Docker Images + +Accelerate publishes a variety of docker versions as part of our CI that users can also use. These are stable images that Accelerate can run off of which comes with a variety of different setup configurations, all of which are officially hosted on [Docker Hub](https://hub.docker.com/r/huggingface/accelerate). + +A breakdown of each are given below + +## Naming Conventions + +Accelerate docker images follow a tagging convention of: + +```bash +huggingface/accelerate:{accelerator}-{nightly,release} +``` + +`accelerator` in this instance is one of many applical pre-configured backend supports: +* `gpu`: Comes compiled off of the `nvidia/cuda` image and includes core parts like `bitsandbytes`. Runs off python 3.9. +* `cpu`: Comes compiled off of `python:3.9-slim` and is designed for non-CUDA based workloads. +* More to come soon +* `gpu-deepspeed`: Comes compiled off of the `nvidia/cuda` image and includes core parts like `bitsandbytes` as well as the latest `deepspeed` version. Runs off python 3.10. +* `gpu-fp8-transformerengine`: Comes compiled off of `nvcr.io/nvidia/pytorch` and is specifically for running the `benchmarks/fp8` scripts on devices which support FP8 operations using the `TransformerEngine` library (RTX 4090, H100, etc) + +## Nightlies vs Releases + +Each release a new build is pushed with a version number included in the name. For a GPU-supported image of version 0.28.0 for instance, it would look like the following: + +```bash +huggingface/accelerate:gpu-release-0.28.0 +``` + +Nightlies contain two different image tags. There is a general `nightly` tag which is built each night, and a `nightly-YYYY-MM-DD` which corresponds to a build from a particular date. + +For instance, here is an example nightly CPU image from 3/14/2024 + +```bash +huggingface/accelerate:cpu-nightly-2024-03-14 +``` + +## Running the images + +Each image comes compiled with `conda` and an `accelerate` environment contains all of the installed dependencies. + +To pull down the latest nightly run: + +```bash +docker pull huggingface/accelerate:gpu-nightly +``` + +To then run it in interactive mode with GPU-memory available, run: + +```bash +docker container run --gpus all -it huggingface/accelerate:gpu-nightly +``` + +## DEPRECATED IMAGES + +CPU and GPU docker images were hosted at `huggingface/accelerate-gpu` and `huggingface/accelerate-cpu`. These builds are now outdated and will not receive updates. + +The builds at the corresponding `huggingface/accelerate:{gpu,cpu}` contain the same `Dockerfile`, so it's as simple as changing the docker image to the desired ones from above. We will not be deleting these images for posterity, but they will not be receiving updates going forward. \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-cpu/Dockerfile b/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-cpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..ac4176342151a2800971dec660a1465137d72769 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-cpu/Dockerfile @@ -0,0 +1,35 @@ +# Builds CPU-only Docker image of PyTorch +# Uses multi-staged approach to reduce size +# Stage 1 +FROM python:3.8-slim as compile-image + +ARG DEBIAN_FRONTEND=noninteractive + +RUN apt update +RUN apt-get install -y --no-install-recommends \ + build-essential \ + git \ + gcc + +# Setup virtual environment for Docker +ENV VIRTUAL_ENV=/opt/venv +RUN python3 -m venv ${VIRTUAL_ENV} +# Make sure we use the virtualenv +ENV PATH="${VIRTUAL_ENV}/bin:$PATH" +WORKDIR /workspace +# Install specific CPU torch wheel to save on space +RUN python3 -m pip install --upgrade --no-cache-dir pip +RUN python3 -m pip install --no-cache-dir \ + jupyter \ + git+https://github.com/huggingface/accelerate#egg=accelerate[testing,test_trackers] \ + --extra-index-url https://download.pytorch.org/whl/cpu + +# Stage 2 +FROM python:3.8-slim AS build-image +COPY --from=compile-image /opt/venv /opt/venv +RUN useradd -ms /bin/bash user +USER user + +# Make sure we use the virtualenv +ENV PATH="/opt/venv/bin:$PATH" +CMD ["/bin/bash"] \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-gpu-deepspeed/Dockerfile b/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-gpu-deepspeed/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..d35fc1b5c5beedabc7b205f00655554bc366292d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-gpu-deepspeed/Dockerfile @@ -0,0 +1,46 @@ +# Builds GPU docker image of PyTorch specifically +# Uses multi-staged approach to reduce size +# Stage 1 +# Use base conda image to reduce time +FROM continuumio/miniconda3:latest AS compile-image +# Specify py version +# Note: DeepSpeed beyond v0.12.6 requires py 3.10 +ENV PYTHON_VERSION=3.10 +# Install apt libs +RUN apt-get update && \ + apt-get install -y curl git wget && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists* + +# Create our conda env +RUN conda create --name accelerate python=${PYTHON_VERSION} ipython jupyter pip +# We don't install pytorch here yet since CUDA isn't available +# instead we use the direct torch wheel +ENV PATH /opt/conda/envs/accelerate/bin:$PATH +# Activate our bash shell +RUN chsh -s /bin/bash +SHELL ["/bin/bash", "-c"] +# Activate the conda env, install mpy4pi, and install torch + accelerate +RUN source activate accelerate && conda install -c conda-forge mpi4py +RUN source activate accelerate && \ + python3 -m pip install --no-cache-dir \ + git+https://github.com/huggingface/accelerate#egg=accelerate[testing,test_trackers,deepspeed] \ + --extra-index-url https://download.pytorch.org/whl/cu117 + +RUN python3 -m pip install --no-cache-dir bitsandbytes + +# Stage 2 +FROM nvidia/cuda:12.1.0-cudnn8-devel-ubuntu20.04 AS build-image +COPY --from=compile-image /opt/conda /opt/conda +ENV PATH /opt/conda/bin:$PATH + +# Install apt libs +RUN apt-get update && \ + apt-get install -y curl git wget && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists* + +RUN echo "source activate accelerate" >> ~/.profile + +# Activate the virtualenv +CMD ["/bin/bash"] \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-gpu/Dockerfile b/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-gpu/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..e5aae6b528b5419f101e3d1bfa75ea58dbe1bca8 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docker/accelerate-gpu/Dockerfile @@ -0,0 +1,45 @@ +# Builds GPU docker image of PyTorch specifically +# Uses multi-staged approach to reduce size +# Stage 1 +# Use base conda image to reduce time +FROM continuumio/miniconda3:latest AS compile-image +# Specify py version +ENV PYTHON_VERSION=3.9 +# Install apt libs +RUN apt-get update && \ + apt-get install -y curl git wget && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists* + +# Create our conda env +RUN conda create --name accelerate python=${PYTHON_VERSION} ipython jupyter pip +# We don't install pytorch here yet since CUDA isn't available +# instead we use the direct torch wheel +ENV PATH /opt/conda/envs/accelerate/bin:$PATH +# Activate our bash shell +RUN chsh -s /bin/bash +SHELL ["/bin/bash", "-c"] +# Activate the conda env, install mpy4pi, and install torch + accelerate +RUN source activate accelerate && conda install -c conda-forge mpi4py +RUN source activate accelerate && \ + python3 -m pip install --no-cache-dir \ + git+https://github.com/huggingface/accelerate#egg=accelerate[testing,test_trackers] \ + --extra-index-url https://download.pytorch.org/whl/cu117 + +RUN python3 -m pip install --no-cache-dir bitsandbytes + +# Stage 2 +FROM nvidia/cuda:12.1.0-cudnn8-devel-ubuntu20.04 AS build-image +COPY --from=compile-image /opt/conda /opt/conda +ENV PATH /opt/conda/bin:$PATH + +# Install apt libs +RUN apt-get update && \ + apt-get install -y curl git wget && \ + apt-get clean && \ + rm -rf /var/lib/apt/lists* + +RUN echo "source activate accelerate" >> ~/.profile + +# Activate the virtualenv +CMD ["/bin/bash"] \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/Makefile b/tasks/tasksmith-5d12db5414d2/tests/source/docs/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..8879933e6cda150267451c9e7d07dd22b7b0d3f1 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/Makefile @@ -0,0 +1,19 @@ +# Minimal makefile for Sphinx documentation +# + +# You can set these variables from the command line. +SPHINXOPTS = +SPHINXBUILD = sphinx-build +SOURCEDIR = source +BUILDDIR = _build + +# Put it first so that "make" without argument is like "make help". +help: + @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) + +.PHONY: help Makefile + +# Catch-all target: route all unknown targets to Sphinx using the new +# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). +%: Makefile + @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/README.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/README.md new file mode 100644 index 0000000000000000000000000000000000000000..4c089297dfc6f0ae4cf6022d17b4694b81db288a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/README.md @@ -0,0 +1,267 @@ + + +# 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 ".[docs]" +``` + +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 accelerate docs/source/ --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 accelerate docs/source/ +``` + +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/accelerate/blob/main/docs/source/_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: + +[ Section A ] +``` +and of course, if you moved it to another file, then: + +``` +Sections that were moved: + +[ Section A ] +``` + +Use the relative style to link to the new file so that the versioned docs continue to work. + + +## Writing Documentation - Specification + +The `huggingface/accelerate` 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. + +### 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.gather\`\]. This will be converted into a link with +`utils.gather` 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.gather\`\] will generate a link with `gather` 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 (more than 119 characters in total), another indentation is necessary +before writing the description after the argument. + +Finally, to maintain uniformity if any *one* description is too long to fit on one line, the +rest of the parameters should follow suit and have an indention before their description. + +Here's an example showcasing everything so far: + +``` + Args: + gradient_accumulation_steps (`int`, *optional*, default to 1): + The number of steps that should pass before gradients are accumulated. A number > 1 should be combined with `Accelerator.accumulate`. + cpu (`bool`, *optional*): + Whether or not to force the script to execute on CPU. Will ignore GPU available if set to `True` and force the execution on one process only. +``` + +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 ... and has a description longer than 119 chars. + a (`float`, *optional*, defaults to 1): + This argument is used to ... and has a description longer than 119 chars. +``` + +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: + + +```` +```python +# first line of code +# second line +# etc +``` +```` + +#### 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: + +``` + 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: + +``` + 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). +``` + +## 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. + +## Writing documentation examples + +The syntax for Example docstrings can look as follows: + +``` + Example: + + ```python + >>> import time + >>> from accelerate import Accelerator + >>> accelerator = Accelerator() + >>> if accelerator.is_main_process: + ... time.sleep(2) + >>> else: + ... print("I'm waiting for the main process to finish its sleep...") + >>> accelerator.wait_for_everyone() + >>> # Should print on every process at the same time + >>> print("Everyone is here") + ``` +``` + +The docstring should give a minimal, clear example of how the respective function +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. \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/_toctree.yml b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/_toctree.yml new file mode 100644 index 0000000000000000000000000000000000000000..14955def60dd2a87de04a560b72cf32ad15a4582 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/_toctree.yml @@ -0,0 +1,123 @@ +- sections: + - local: index + title: 🤗 Accelerate + - local: basic_tutorials/install + title: Installation + - local: quicktour + title: Quicktour + title: Getting started +- sections: + - local: basic_tutorials/overview + title: Overview + - local: basic_tutorials/migration + title: Add Accelerate to your code + - local: basic_tutorials/execution + title: Execution process + - local: basic_tutorials/tpu + title: TPU training + - local: basic_tutorials/launch + title: Launching distributed code + - local: basic_tutorials/notebook + title: Launching distributed training from Jupyter Notebooks + title: Tutorials +- sections: + - isExpanded: true + sections: + - local: usage_guides/explore + title: Start Here! + - local: usage_guides/model_size_estimator + title: Model memory estimator + - local: usage_guides/quantization + title: Model quantization + - local: usage_guides/tracking + title: Experiment trackers + - local: usage_guides/profiler + title: Profiler + - local: usage_guides/checkpoint + title: Save and load training states + - local: basic_tutorials/troubleshooting + title: Troubleshoot + - local: usage_guides/training_zoo + title: Example Zoo + title: Accelerate + - isExpanded: true + sections: + - local: usage_guides/gradient_accumulation + title: Gradient accumulation + - local: usage_guides/local_sgd + title: Local SGD + - local: usage_guides/low_precision_training + title: Low precision (FP8) training + - local: usage_guides/deepspeed + title: DeepSpeed + - local: usage_guides/ddp_comm_hook + title: DDP Communication Hooks + - local: usage_guides/fsdp + title: Fully Sharded Data Parallelism + - local: usage_guides/megatron_lm + title: Megatron-LM + - local: usage_guides/sagemaker + title: Amazon SageMaker + - local: usage_guides/mps + title: Apple M1 GPUs + - local: usage_guides/ipex + title: IPEX training with CPU + title: Training + - isExpanded: true + sections: + - local: usage_guides/big_modeling + title: Big Model Inference + - local: usage_guides/distributed_inference + title: Distributed inference + title: Inference + title: How to guides +- sections: + - local: concept_guides/internal_mechanism + title: 🤗 Accelerate's internal mechanism + - local: concept_guides/big_model_inference + title: Loading big models into memory + - local: concept_guides/performance + title: Comparing performance across distributed setups + - local: concept_guides/deferring_execution + title: Executing and deferring jobs + - local: concept_guides/gradient_synchronization + title: Gradient synchronization + - local: concept_guides/fsdp_and_deepspeed + title: FSDP vs DeepSpeed + - local: concept_guides/low_precision_training + title: How training in low-precision environments is possible (FP8) + - local: concept_guides/training_tpu + title: TPU best practices + title: Concepts and fundamentals +- sections: + - local: package_reference/accelerator + title: Accelerator + - local: package_reference/state + title: Stateful configuration classes + - local: package_reference/cli + title: The Command Line + - local: package_reference/torch_wrappers + title: Torch wrapper classes + - local: package_reference/tracking + title: Experiment trackers + - local: package_reference/launchers + title: Distributed launchers + - local: package_reference/deepspeed + title: DeepSpeed utilities + - local: package_reference/logging + title: Logging + - local: package_reference/big_modeling + title: Working with large models + - local: package_reference/inference + title: Distributed inference with big models + - local: package_reference/kwargs + title: Kwargs handlers + - local: package_reference/fp8 + title: FP8 Functionality + - local: package_reference/utilities + title: Utility functions and classes + - local: package_reference/megatron_lm + title: Megatron-LM Utilities + - local: package_reference/fsdp + title: Fully Sharded Data Parallelism Utilities + title: "Reference" diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/execution.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/execution.md new file mode 100644 index 0000000000000000000000000000000000000000..4874f4439938ef18997f2cfb78f55c83fae70965 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/execution.md @@ -0,0 +1,128 @@ + + +# Execution process + +When working with distributed training systems, it is important to manage how and when processes are executed across GPUs. Some processes are completed faster than others, and some processes shouldn't begin if others haven't finished yet. Accelerate provides tools for orchestrating when processes are executed to ensure everything remains synchronized across all devices. + +This tutorial will teach you how to execute a process on only one machine and how to delay execution until all processes have reached a certain point. + +## Execute on one process + +Certain code only needs to be run once on a given machine, such as printing a log statement or only displaying one progress bar on the local main process. + + + + +You should use `accelerator.is_local_main_process` to indicate code that should only be executed once. + +```py +from tqdm.auto import tqdm + +progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process) +``` + +You could also wrap a statement with `accelerator.is_local_main_process`. + +> [!TIP] +> For standalone `print` statements that aren't wrapped in `accelerator.is_local_main_process`, replace `print` with Accelerate's [`~Accelerator.print`] method to only print once per process. + +```py +if accelerator.is_local_main_process: + print("Accelerate is the best") +``` + + + + +For a function that should only be executed once, use [`~Accelerator.on_local_main_process`]. + +```py +@accelerator.on_local_main_process +def do_my_thing(): + "Something done once per server" + do_thing_once_per_server() +``` + + + + +You could also direct Accelerate to execute code once across *all processes* regardless of the number of machines. This is useful if you're uploading a final model to the Hub. + + + + +You should use `accelerator.is_main_process` to indicate code that should only be executed once across all processes. + +```py +if accelerator.is_main_process: + repo.push_to_hub() +``` + + + + +For a function that should only be executed once across all processes, use [`~Accelerator.on_main_process`]. + +```py +@accelerator.on_main_process +def do_my_thing(): + "Something done once per server" + do_thing_once() +``` + + + + +## Execute on a specific process + +Accelerate can also help you execute functions that should only be executed on a specific process or a local process index. + + + + +Use the [`~Accelerator.on_process`] method and specify the process index to execute a function on. + +```py +@accelerator.on_process(process_index=0) +def do_my_thing(): + "Something done on process index 0" + do_thing_on_index_zero() +``` + + + + +Use the [`~Accelerator.on_local_process`] method and specify the local process index to execute a function on. + +```py +@accelerator.on_local_process(local_process_idx=0) +def do_my_thing(): + "Something done on process index 0 on each server" + do_thing_on_index_zero_on_each_server() +``` + + + + +## Defer execution + +When you run your script on several GPUs at the same time, some code may be executed faster than others. You might need to wait for all processes to reach a certain point before executing the next set of instructions. For instance, you shouldn’t save a model before making sure every process is done with training. + +To do this, add [`~Accelerator.wait_for_everyone`] in your code. This blocks all processes that have finished first from continuing until all remaining processes have reached the same point (this has no effect if you're running on a single GPU or CPU). + +```py +accelerator.wait_for_everyone() +``` diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/install.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/install.md new file mode 100644 index 0000000000000000000000000000000000000000..d3e59516886add081d2e27121a08a26ed5874dad --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/install.md @@ -0,0 +1,102 @@ + + +# Installation and Configuration + +Before you start, you will need to setup your environment, install the appropriate packages, and configure 🤗 Accelerate. 🤗 Accelerate is tested on **Python 3.8+**. + +## Installing 🤗 Accelerate + +🤗 Accelerate is available on pypi and conda, as well as on GitHub. Details to install from each are below: + +### pip + +To install 🤗 Accelerate from pypi, perform: + +```bash +pip install accelerate +``` + +### conda + +🤗 Accelerate can also be installed with conda with: + +```bash +conda install -c conda-forge accelerate +``` + +### Source + +New features are added every day that haven't been released yet. To try them out yourself, install +from the GitHub repository: + +```bash +pip install git+https://github.com/huggingface/accelerate +``` + +If you're working on contributing to the library or wish to play with the source code and see live +results as you run the code, an editable version can be installed from a locally-cloned version of the +repository: + +```bash +git clone https://github.com/huggingface/accelerate +cd accelerate +pip install -e . +``` + +## Configuring 🤗 Accelerate + +After installing, you need to configure 🤗 Accelerate for how the current system is setup for training. +To do so run the following and answer the questions prompted to you: + +```bash +accelerate config +``` + +To write a barebones configuration that doesn't include options such as DeepSpeed configuration or running on TPUs, you can quickly run: + +```bash +python -c "from accelerate.utils import write_basic_config; write_basic_config(mixed_precision='fp16')" +``` +🤗 Accelerate will automatically utilize the maximum number of GPUs available and set the mixed precision mode. + +To check that your configuration looks fine, run: + +```bash +accelerate env +``` + +An example output is shown below, which describes two GPUs on a single machine with no mixed precision being used: + +```bash +- `Accelerate` version: 0.11.0.dev0 +- Platform: Linux-5.10.0-15-cloud-amd64-x86_64-with-debian-11.3 +- Python version: 3.7.12 +- Numpy version: 1.19.5 +- PyTorch version (GPU?): 1.12.0+cu102 (True) +- `Accelerate` default config: + - compute_environment: LOCAL_MACHINE + - distributed_type: MULTI_GPU + - mixed_precision: no + - use_cpu: False + - num_processes: 2 + - machine_rank: 0 + - num_machines: 1 + - main_process_ip: None + - main_process_port: None + - main_training_function: main + - deepspeed_config: {} + - fsdp_config: {} +``` \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/launch.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/launch.md new file mode 100644 index 0000000000000000000000000000000000000000..dfcab07b7b47ccbcc2a326a31e835fd963638f7e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/launch.md @@ -0,0 +1,232 @@ + + +# Launching your 🤗 Accelerate scripts + +In the previous tutorial, you were introduced to how to modify your current training script to use 🤗 Accelerate. +The final version of that code is shown below: + +```python +from accelerate import Accelerator + +accelerator = Accelerator() + +model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler +) + +for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() +``` + +But how do you run this code and have it utilize the special hardware available to it? + +First, you should rewrite the above code into a function, and make it callable as a script. For example: + +```diff + from accelerate import Accelerator + ++ def main(): + accelerator = Accelerator() + + model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler + ) + + for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() + ++ if __name__ == "__main__": ++ main() +``` + +Next, you need to launch it with `accelerate launch`. + + + + It's recommended you run `accelerate config` before using `accelerate launch` to configure your environment to your liking. + Otherwise 🤗 Accelerate will use very basic defaults depending on your system setup. + + + + +## Using accelerate launch + +🤗 Accelerate has a special CLI command to help you launch your code in your system through `accelerate launch`. +This command wraps around all of the different commands needed to launch your script on various platforms, without you having to remember what each of them is. + + + + If you are familiar with launching scripts in PyTorch yourself such as with `torchrun`, you can still do this. It is not required to use `accelerate launch`. + + + +You can launch your script quickly by using: + +```bash +accelerate launch {script_name.py} --arg1 --arg2 ... +``` + +Just put `accelerate launch` at the start of your command, and pass in additional arguments and parameters to your script afterward like normal! + +Since this runs the various torch spawn methods, all of the expected environment variables can be modified here as well. +For example, here is how to use `accelerate launch` with a single GPU: + +```bash +CUDA_VISIBLE_DEVICES="0" accelerate launch {script_name.py} --arg1 --arg2 ... +``` + +You can also use `accelerate launch` without performing `accelerate config` first, but you may need to manually pass in the right configuration parameters. +In this case, 🤗 Accelerate will make some hyperparameter decisions for you, e.g., if GPUs are available, it will use all of them by default without the mixed precision. +Here is how you would use all GPUs and train with mixed precision disabled: + +```bash +accelerate launch --multi_gpu {script_name.py} {--arg1} {--arg2} ... +``` + +Or by specifying a number of GPUs to use: + +```bash +accelerate launch --num_processes=2 {script_name.py} {--arg1} {--arg2} ... +``` + +To get more specific you should pass in the needed parameters yourself. For instance, here is how you +would also launch that same script on two GPUs using mixed precision while avoiding all of the warnings: + +```bash +accelerate launch --multi_gpu --mixed_precision=fp16 --num_processes=2 {script_name.py} {--arg1} {--arg2} ... +``` + +For a complete list of parameters you can pass in, run: + +```bash +accelerate launch -h +``` + + + + Even if you are not using 🤗 Accelerate in your code, you can still use the launcher for starting your scripts! + + + +For a visualization of this difference, that earlier `accelerate launch` on multi-gpu would look something like so with `torchrun`: + +```bash +MIXED_PRECISION="fp16" torchrun --nproc_per_node=2 --num_machines=1 {script_name.py} {--arg1} {--arg2} ... +``` + +You can also launch your script utilizing the launch CLI as a python module itself, enabling the ability to pass in other python-specific +launching behaviors. To do so, use `accelerate.commands.launch` instead of `accelerate launch`: + +```bash +python -m accelerate.commands.launch --num_processes=2 {script_name.py} {--arg1} {--arg2} +``` + +If you want to execute the script with any other python flags, you can pass them in as well similar to `-m`, such as +the below example enabling unbuffered stdout and stderr: + +```bash +python -u -m accelerate.commands.launch --num_processes=2 {script_name.py} {--arg1} {--arg2} +``` + + + + You can run your code on CPU as well! This is helpful for debugging and testing purposes on toy models and datasets. + +```bash +accelerate launch --cpu {script_name.py} {--arg1} {--arg2} +``` + + + +## Why you should always use `accelerate config` + +Why is it useful to the point you should **always** run `accelerate config`? + +Remember that earlier call to `accelerate launch` as well as `torchrun`? +Post configuration, to run that script with the needed parts you just need to use `accelerate launch` outright, without passing anything else in: + +```bash +accelerate launch {script_name.py} {--arg1} {--arg2} ... +``` + + +## Custom Configurations + +As briefly mentioned earlier, `accelerate launch` should be mostly used through combining set configurations +made with the `accelerate config` command. These configs are saved to a `default_config.yaml` file in your cache folder for 🤗 Accelerate. +This cache folder is located at (with decreasing order of priority): + +- The content of your environment variable `HF_HOME` suffixed with `accelerate`. +- If it does not exist, the content of your environment variable `XDG_CACHE_HOME` suffixed with + `huggingface/accelerate`. +- If this does not exist either, the folder `~/.cache/huggingface/accelerate`. + +To have multiple configurations, the flag `--config_file` can be passed to the `accelerate launch` command paired +with the location of the custom yaml. + +An example yaml may look something like the following for two GPUs on a single machine using `fp16` for mixed precision: +```yaml +compute_environment: LOCAL_MACHINE +deepspeed_config: {} +distributed_type: MULTI_GPU +fsdp_config: {} +machine_rank: 0 +main_process_ip: null +main_process_port: null +main_training_function: main +mixed_precision: fp16 +num_machines: 1 +num_processes: 2 +use_cpu: false +``` + +Launching a script from the location of that custom yaml file looks like the following: +```bash +accelerate launch --config_file {path/to/config/my_config_file.yaml} {script_name.py} {--arg1} {--arg2} ... +``` + +## Multi-node training +Multi-node training with 🤗Accelerate is similar to [multi-node training with torchrun](https://pytorch.org/tutorials/intermediate/ddp_series_multinode.html). The simplest way to launch a multi-node training run is to do the following: + +- Copy your codebase and data to all nodes. (or place them on a shared filesystem) +- Setup your python packages on all nodes. +- Run `accelerate config` on the main single node first. After specifying the number of nodes, you will be asked to specify the rank of each node (this will be 0 for the main/master node), along with the IP address and port for the main process. This is required for the worker nodes to communicate with the main process. Afterwards, you can copy or send this config file across all of your nodes, changing the `machine_rank` to 1, 2,3, etc. to avoid having to run the command (or just follow their directions directly for launching with `torchrun` as well) + +Once you have done this, you can start your multi-node training run by running `accelerate launch` (or `torchrun`) on all nodes. + + + It is required that the command be ran on all nodes for everything to start, not just running it from the main node. You can use something like SLURM or a different process executor to wrap around this requirement and call everything from a single command. + + + + + It is recommended to use the intranet IP of your main node over the public IP for better latency. This is the `192.168.x.x` or the `172.x.x.x` address you see when you run `hostname -I` on the main node. + + + +To get a better idea about multi-node training, check out our example for [multi-node training with FSDP](https://huggingface.co/blog/ram-efficient-pytorch-fsdp). diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/migration.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/migration.md new file mode 100644 index 0000000000000000000000000000000000000000..8fb2c32f981caa08170f2eb773fdbdcc428aff04 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/migration.md @@ -0,0 +1,227 @@ + + +# Add Accelerate to your code + +Each distributed training framework has their own way of doing things which can require writing a lot of custom code to adapt it to your PyTorch training code and training environment. Accelerate offers a friendly way to interface with these distributed training frameworks without having to learn the specific details of each one. Accelerate takes care of those details for you, so you can focus on the training code and scale it to any distributed training environment. + +In this tutorial, you'll learn how to adapt your existing PyTorch code with Accelerate and get you on your way toward training on distributed systems with ease! You'll start with a basic PyTorch training loop (it assumes all the training objects like `model` and `optimizer` have been setup already) and progressively integrate Accelerate into it. + +```python +device = "cuda" +model.to(device) + +for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) + loss.backward() + optimizer.step() + scheduler.step() +``` + +## Accelerator + +The [`Accelerator`] is the main class for adapting your code to work with Accelerate. It knows about the distributed setup you're using such as the number of different processes and your hardware type. This class also provides access to many of the necessary methods for enabling your PyTorch code to work in any distributed training environment and for managing and executing processes across devices. + +That's why you should always start by importing and creating an [`Accelerator`] instance in your script. + +```python +from accelerate import Accelerator + +accelerator = Accelerator() +``` + +The [`Accelerator`] also knows which device to move your PyTorch objects to, so it is recommended to let Accelerate handle this for you. + +```diff +- device = "cuda" ++ device = accelerator.device + model.to(device) +``` + +## Prepare PyTorch objects + +Next, you need to prepare your PyTorch objects (model, optimizer, scheduler, etc.) for distributed training. The [`~Accelerator.prepare`] method takes care of placing your model in the appropriate container (like single GPU or multi-GPU) for your training setup, adapting the optimizer and scheduler to use Accelerate's [`~optimizer.AcceleratedOptimizer`] and [`~scheduler.AcceleratedScheduler`], and creating a new dataloader that can be sharded across processes. + +> [!TIP] +> Accelerate only prepares objects that inherit from their respective PyTorch classes such as `torch.optim.Optimizer`. + +The PyTorch objects are returned in the same order they're sent. + +```py +model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler +) +``` + +## Training loop + +Finally, remove the `to(device)` calls to the inputs and targets in the training loop because Accelerate's DataLoader classes automatically places them on the right device. You should also replace the usual `backward()` pass with Accelerate's [`~Accelerator.backward`] method which scales the gradients for you and uses the appropriate `backward()` method depending on your distributed setup (for example, DeepSpeed or Megatron). + +```diff +- inputs = inputs.to(device) +- targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) +- loss.backward() ++ accelerator.backward(loss) +``` + +Put everything together and your new Accelerate training loop should now look like this! + +```python +from accelerate import Accelerator +accelerator = Accelerator() + +device = accelerator.device +model, optimizer, training_dataloader, scheduler = accelerator.prepare( + model, optimizer, training_dataloader, scheduler +) + +for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + scheduler.step() +``` + +## Training features + +Accelerate offers additional features - like gradient accumulation, gradient clipping, mixed precision training and more - you can add to your script to improve your training run. Let's explore these three features. + +### Gradient accumulation + +Gradient accumulation enables you to train on larger batch sizes by accumulating the gradients over multiple batches before updating the weights. This can be useful for getting around memory limitations. To enable this feature in Accelerate, specify the `gradient_accumulation_steps` parameter in the [`Accelerator`] class and add the [`~Accelerator.accumulate`] context manager to your script. + +```diff ++ accelerator = Accelerator(gradient_accumulation_steps=2) + model, optimizer, training_dataloader = accelerator.prepare(model, optimizer, training_dataloader) + + for input, label in training_dataloader: ++ with accelerator.accumulate(model): + predictions = model(input) + loss = loss_function(predictions, label) + accelerator.backward(loss) + optimizer.step() + scheduler.step() + optimizer.zero_grad() +``` + +### Gradient clipping + +Gradient clipping is a technique to prevent "exploding gradients", and Accelerate offers: + +* [`~Accelerator.clip_grad_value_`] to clip gradients to a minimum and maximum value +* [`~Accelerator.clip_grad_norm_`] for normalizing gradients to a certain value + +### Mixed precision + +Mixed precision accelerates training by using a lower precision data type like fp16 (half-precision) to calculate the gradients. For the best performance with Accelerate, the loss should be computed inside your model (like in Transformers models) because computations outside of the model are computed in full precision. + +Set the mixed precision type to use in the [`Accelerator`], and then use the [`~Accelerator.autocast`] context manager to automatically cast the values to the specified data type. + +> [!WARNING] +> Accelerate enables automatic mixed precision, so [`~Accelerator.autocast`] is only needed if there are other mixed precision operations besides those performed on loss by [`~Accelerator.backward`] which already handles the scaling. + +```diff ++ accelerator = Accelerator(mixed_precision="fp16") ++ with accelerator.autocast(): + loss = complex_loss_function(outputs, target): +``` + +## Save and load + +Accelerate can also save and load a *model* once training is complete or you can also save the model and optimizer *state* which could be useful for resuming training. + +### Model + +Once all processes are complete, unwrap the model with the [`~Accelerator.unwrap_model`] method before saving it because the [`~Accelerator.prepare`] method wrapped your model into the proper interface for distributed training. If you don't unwrap the model, saving the model state dictionary also saves any potential extra layers from the larger model and you won't be able to load the weights back into your base model. + +You should use the [`~Accelerator.save_model`] method to unwrap and save the model state dictionary. This method can also save a model into sharded checkpoints or into the [safetensors](https://hf.co/docs/safetensors/index) format. + + + + +```py +accelerator.wait_for_everyone() +accelerator.save_model(model, save_directory) +``` + + + +For models from the [Transformers](https://hf.co/docs/transformers/index) library, save the model with the [`~transformers.PreTrainedModel.save_pretrained`] method so that it can be reloaded with the [`~transformers.PreTrainedModel.from_pretrained`] method. + +```py +from transformers import AutoModel + +unwrapped_model = accelerator.unwrap_model(model) +unwrapped_model.save_pretrained( + "path/to/my_model_directory", + is_main_process=accelerator.is_main_process, + save_function=accelerator.save, +) + +model = AutoModel.from_pretrained("path/to/my_model_directory") +``` + + + +To load your weights, use the [`~Accelerator.unwrap_model`] method to unwrap the model first before loading the weights. All model parameters are references to tensors, so this loads your weights inside `model`. + +```py +unwrapped_model = accelerator.unwrap_model(model) +path_to_checkpoint = os.path.join(save_directory,"pytorch_model.bin") +unwrapped_model.load_state_dict(torch.load(path_to_checkpoint)) +``` + + + + +Set `safe_serialization=True` to save the model in the safetensor format. + +```py +accelerator.wait_for_everyone() +accelerator.save_model(model, save_directory, max_shard_size="1GB", safe_serialization=True) +``` + +To load a sharded checkpoint or a safetensor formatted checkpoint, use the [`~accelerate.load_checkpoint_in_model`] method. This method allows you to load a checkpoint onto a specific device. + +```py +load_checkpoint_in_model(unwrapped_model, save_directory, device_map={"":device}) +``` + + + + +### State + +During training, you may want to save the current state of the model, optimizer, random generators, and potentially learning rate schedulers so they can be restored in the *same script*. You should add the [`~Accelerator.save_state`] and [`~Accelerator.load_state`] methods to your script to save and load states. + +To further customize where and how states are saved through [`~Accelerator.save_state`], use the [`~utils.ProjectConfiguration`] class. For example, if `automatic_checkpoint_naming` is enabled, each saved checkpoint is stored at `Accelerator.project_dir/checkpoints/checkpoint_{checkpoint_number}`. + +Any other stateful items to be stored should be registered with the [`~Accelerator.register_for_checkpointing`] method so they can be saved and loaded. Every object passed to this method to be stored must have a `load_state_dict` and `state_dict` function. + + + +If you have [`torchdata>=0.8.0`](https://github.com/pytorch/data/tree/main) installed, you can additionally pass `use_stateful_dataloader=True` into your [`~utils.DataLoaderConfiguration`]. This extends Accelerate's DataLoader classes with a `load_state_dict` and `state_dict` function, and makes it so `Accelerator.save_state` and `Accelerator.load_state` also track how far into the training dataset it has read when persisting the model. + + diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/notebook.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/notebook.md new file mode 100644 index 0000000000000000000000000000000000000000..805704116f39a61abd4fdf12f792243947026c9c --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/notebook.md @@ -0,0 +1,476 @@ + + +# Launching Multi-GPU Training from a Jupyter Environment + +This tutorial teaches you how to fine tune a computer vision model with 🤗 Accelerate from a Jupyter Notebook on a distributed system. +You will also learn how to setup a few requirements needed for ensuring your environment is configured properly, your data has been prepared properly, and finally how to launch training. + + + + This tutorial is also available as a Jupyter Notebook [here](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_cv_example.ipynb) + + + +## Configuring the Environment + +Before any training can be performed, a 🤗 Accelerate config file must exist in the system. Usually this can be done by running the following in a terminal and answering the prompts: + +```bash +accelerate config +``` + +However, if general defaults are fine and you are *not* running on a TPU, 🤗Accelerate has a utility to quickly write your GPU configuration into a config file via [`utils.write_basic_config`]. + +The following code will restart Jupyter after writing the configuration, as CUDA code was called to perform this. + + + + CUDA can't be initialized more than once on a multi-GPU system. It's fine to debug in the notebook and have calls to CUDA, but in order to finally train a full cleanup and restart will need to be performed. + + + +```python +import os +from accelerate.utils import write_basic_config + +write_basic_config() # Write a config file +os._exit(00) # Restart the notebook +``` + +## Preparing the Dataset and Model + +Next you should prepare your dataset. As mentioned at earlier, great care should be taken when preparing the `DataLoaders` and model to make sure that **nothing** is put on *any* GPU. + +If you do, it is recommended to put that specific code into a function and call that from within the notebook launcher interface, which will be shown later. + +Make sure the dataset is downloaded based on the directions [here](https://github.com/huggingface/accelerate/tree/main/examples#simple-vision-example) + +```python +import os, re, torch, PIL +import numpy as np + +from torch.optim.lr_scheduler import OneCycleLR +from torch.utils.data import DataLoader, Dataset +from torchvision.transforms import Compose, RandomResizedCrop, Resize, ToTensor + +from accelerate import Accelerator +from accelerate.utils import set_seed +from timm import create_model +``` + +First you need to create a function to extract the class name based on a filename: + +```python +import os + +data_dir = "../../images" +fnames = os.listdir(data_dir) +fname = fnames[0] +print(fname) +``` + +```python out +beagle_32.jpg +``` + +In the case here, the label is `beagle`. Using regex you can extract the label from the filename: + +```python +import re + + +def extract_label(fname): + stem = fname.split(os.path.sep)[-1] + return re.search(r"^(.*)_\d+\.jpg$", stem).groups()[0] +``` + +```python +extract_label(fname) +``` + +And you can see it properly returned the right name for our file: + +```python out +"beagle" +``` + +Next a `Dataset` class should be made to handle grabbing the image and the label: + +```python +class PetsDataset(Dataset): + def __init__(self, file_names, image_transform=None, label_to_id=None): + self.file_names = file_names + self.image_transform = image_transform + self.label_to_id = label_to_id + + def __len__(self): + return len(self.file_names) + + def __getitem__(self, idx): + fname = self.file_names[idx] + raw_image = PIL.Image.open(fname) + image = raw_image.convert("RGB") + if self.image_transform is not None: + image = self.image_transform(image) + label = extract_label(fname) + if self.label_to_id is not None: + label = self.label_to_id[label] + return {"image": image, "label": label} +``` + +Now to build the dataset. Outside the training function you can find and declare all the filenames and labels and use them as references inside the +launched function: + +```python +fnames = [os.path.join("../../images", fname) for fname in fnames if fname.endswith(".jpg")] +``` + +Next gather all the labels: + +```python +all_labels = [extract_label(fname) for fname in fnames] +id_to_label = list(set(all_labels)) +id_to_label.sort() +label_to_id = {lbl: i for i, lbl in enumerate(id_to_label)} +``` + +Next, you should make a `get_dataloaders` function that will return your built dataloaders for you. As mentioned earlier, if data is automatically +sent to the GPU or a TPU device when building your `DataLoaders`, they must be built using this method. + +```python +def get_dataloaders(batch_size: int = 64): + "Builds a set of dataloaders with a batch_size" + random_perm = np.random.permutation(len(fnames)) + cut = int(0.8 * len(fnames)) + train_split = random_perm[:cut] + eval_split = random_perm[cut:] + + # For training a simple RandomResizedCrop will be used + train_tfm = Compose([RandomResizedCrop((224, 224), scale=(0.5, 1.0)), ToTensor()]) + train_dataset = PetsDataset([fnames[i] for i in train_split], image_transform=train_tfm, label_to_id=label_to_id) + + # For evaluation a deterministic Resize will be used + eval_tfm = Compose([Resize((224, 224)), ToTensor()]) + eval_dataset = PetsDataset([fnames[i] for i in eval_split], image_transform=eval_tfm, label_to_id=label_to_id) + + # Instantiate dataloaders + train_dataloader = DataLoader(train_dataset, shuffle=True, batch_size=batch_size, num_workers=4) + eval_dataloader = DataLoader(eval_dataset, shuffle=False, batch_size=batch_size * 2, num_workers=4) + return train_dataloader, eval_dataloader +``` + +Finally, you should import the scheduler to be used later: + +```python +from torch.optim.lr_scheduler import CosineAnnealingLR +``` + +## Writing the Training Function + +Now you can build the training loop. [`notebook_launcher`] works by passing in a function to call that will be ran across the distributed system. + +Here is a basic training loop for the animal classification problem: + + + + The code has been split up to allow for explanations on each section. A full version that can be copy and pasted will be available at the end + + + + +```python +def training_loop(mixed_precision="fp16", seed: int = 42, batch_size: int = 64): + set_seed(seed) + accelerator = Accelerator(mixed_precision=mixed_precision) +``` + +First you should set the seed and create an [`Accelerator`] object as early in the training loop as possible. + + + + If training on the TPU, your training loop should take in the model as a parameter and it should be instantiated + outside of the training loop function. See the [TPU best practices](../concept_guides/training_tpu) + to learn why + + + +Next you should build your dataloaders and create your model: + +```python + train_dataloader, eval_dataloader = get_dataloaders(batch_size) + model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) +``` + + + + You build the model here so that the seed also controls the new weight initialization + + + +As you are performing transfer learning in this example, the encoder of the model starts out frozen so the head of the model can be +trained only initially: + +```python + for param in model.parameters(): + param.requires_grad = False + for param in model.get_classifier().parameters(): + param.requires_grad = True +``` + +Normalizing the batches of images will make training a little faster: + +```python + mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None] + std = torch.tensor(model.default_cfg["std"])[None, :, None, None] +``` + +To make these constants available on the active device, you should set it to the Accelerator's device: + +```python + mean = mean.to(accelerator.device) + std = std.to(accelerator.device) +``` + +Next instantiate the rest of the PyTorch classes used for training: + +```python + optimizer = torch.optim.Adam(params=model.parameters(), lr=3e-2 / 25) + lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=3e-2, epochs=5, steps_per_epoch=len(train_dataloader)) +``` + +Before passing everything to [`~Accelerator.prepare`]. + + + + There is no specific order to remember, you just need to unpack the objects in the same order you gave them to the prepare method. + + + +```python + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) +``` + +Now train the model: + +```python + for epoch in range(5): + model.train() + for batch in train_dataloader: + inputs = (batch["image"] - mean) / std + outputs = model(inputs) + loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() +``` + +The evaluation loop will look slightly different compared to the training loop. The number of elements passed as well as the overall +total accuracy of each batch will be added to two constants: + +```python + model.eval() + accurate = 0 + num_elems = 0 +``` + +Next you have the rest of your standard PyTorch loop: + +```python + for batch in eval_dataloader: + inputs = (batch["image"] - mean) / std + with torch.no_grad(): + outputs = model(inputs) + predictions = outputs.argmax(dim=-1) +``` + +Before finally the last major difference. + +When performing distributed evaluation, the predictions and labels need to be passed through +[`~Accelerator.gather`] so that all of the data is available on the current device and a properly calculated metric can be achieved: + +```python + accurate_preds = accelerator.gather(predictions) == accelerator.gather(batch["label"]) + num_elems += accurate_preds.shape[0] + accurate += accurate_preds.long().sum() +``` + +Now you just need to calculate the actual metric for this problem, and you can print it on the main process using [`~Accelerator.print`]: + +```python + eval_metric = accurate.item() / num_elems + accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") +``` + +A full version of this training loop is available below: + +```python +def training_loop(mixed_precision="fp16", seed: int = 42, batch_size: int = 64): + set_seed(seed) + # Initialize accelerator + accelerator = Accelerator(mixed_precision=mixed_precision) + # Build dataloaders + train_dataloader, eval_dataloader = get_dataloaders(batch_size) + + # Instantiate the model (you build the model here so that the seed also controls new weight initaliziations) + model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) + + # Freeze the base model + for param in model.parameters(): + param.requires_grad = False + for param in model.get_classifier().parameters(): + param.requires_grad = True + + # You can normalize the batches of images to be a bit faster + mean = torch.tensor(model.default_cfg["mean"])[None, :, None, None] + std = torch.tensor(model.default_cfg["std"])[None, :, None, None] + + # To make these constants available on the active device, set it to the accelerator device + mean = mean.to(accelerator.device) + std = std.to(accelerator.device) + + # Instantiate the optimizer + optimizer = torch.optim.Adam(params=model.parameters(), lr=3e-2 / 25) + + # Instantiate the learning rate scheduler + lr_scheduler = OneCycleLR(optimizer=optimizer, max_lr=3e-2, epochs=5, steps_per_epoch=len(train_dataloader)) + + # Prepare everything + # There is no specific order to remember, you just need to unpack the objects in the same order you gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + + # Now you train the model + for epoch in range(5): + model.train() + for batch in train_dataloader: + inputs = (batch["image"] - mean) / std + outputs = model(inputs) + loss = torch.nn.functional.cross_entropy(outputs, batch["label"]) + accelerator.backward(loss) + optimizer.step() + lr_scheduler.step() + optimizer.zero_grad() + + model.eval() + accurate = 0 + num_elems = 0 + for batch in eval_dataloader: + inputs = (batch["image"] - mean) / std + with torch.no_grad(): + outputs = model(inputs) + predictions = outputs.argmax(dim=-1) + accurate_preds = accelerator.gather(predictions) == accelerator.gather(batch["label"]) + num_elems += accurate_preds.shape[0] + accurate += accurate_preds.long().sum() + + eval_metric = accurate.item() / num_elems + # Use accelerator.print to print only on the main process. + accelerator.print(f"epoch {epoch}: {100 * eval_metric:.2f}") +``` + +## Using the notebook_launcher + +All that's left is to use the [`notebook_launcher`]. + +You pass in the function, the arguments (as a tuple), and the number of processes to train on. (See the [documentation](../package_reference/launchers) for more information) + +```python +from accelerate import notebook_launcher +``` + +```python +args = ("fp16", 42, 64) +notebook_launcher(training_loop, args, num_processes=2) +``` + +In the case of running on multiple nodes, you need to set up a Jupyter session at each node and run the launching cell at the same time. + +For an environment containing 2 nodes (computers) with 8 GPUs each and the main computer with an IP address of "172.31.43.8", it would look like so: + +```python +notebook_launcher(training_loop, args, master_addr="172.31.43.8", node_rank=0, num_nodes=2, num_processes=8) +``` + +And in the second Jupyter session on the other machine: + + + + Notice how the `node_rank` has changed + + + +```python +notebook_launcher(training_loop, args, master_addr="172.31.43.8", node_rank=1, num_nodes=2, num_processes=8) +``` + +In the case of running on the TPU, it would look like so: + +```python +model = create_model("resnet50d", pretrained=True, num_classes=len(label_to_id)) + +args = (model, "fp16", 42, 64) +notebook_launcher(training_loop, args, num_processes=8) +``` + +To launch the training process with elasticity, enabling fault tolerance, you can use the `elastic_launch` feature provided by PyTorch. This requires setting additional parameters such as `rdzv_backend` and `max_restarts`. Here is an example of how to use `notebook_launcher` with elastic capabilities: + +```python +notebook_launcher( + training_loop, + args, + num_processes=2, + max_restarts=3 +) +``` + +As it's running it will print the progress as well as state how many devices you ran on. This tutorial was ran with two GPUs: + +```python out +Launching training on 2 GPUs. +epoch 0: 88.12 +epoch 1: 91.73 +epoch 2: 92.58 +epoch 3: 93.90 +epoch 4: 94.71 +``` + +And that's it! + +Please note that [`notebook_launcher`] ignores the 🤗 Accelerate config file, to launch based on the config use: + +```bash +accelerate launch +``` + +## Debugging + +A common issue when running the `notebook_launcher` is receiving a CUDA has already been initialized issue. This usually stems +from an import or prior code in the notebook that makes a call to the PyTorch `torch.cuda` sublibrary. To help narrow down what went wrong, +you can launch the `notebook_launcher` with `ACCELERATE_DEBUG_MODE=yes` in your environment and an additional check +will be made when spawning that a regular process can be created and utilize CUDA without issue. (Your CUDA code can still be ran afterwards). + +## Conclusion + +This notebook showed how to perform distributed training from inside of a Jupyter Notebook. Some key notes to remember: + +- Make sure to save any code that use CUDA (or CUDA imports) for the function passed to [`notebook_launcher`] +- Set the `num_processes` to be the number of devices used for training (such as number of GPUs, CPUs, TPUs, etc) +- If using the TPU, declare your model outside the training loop function diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/overview.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/overview.md new file mode 100644 index 0000000000000000000000000000000000000000..6a62e72da091d0066b7c30540e58ad3998210b98 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/overview.md @@ -0,0 +1,24 @@ + + +# Overview + +Welcome to the 🤗 Accelerate tutorials! These introductory guides will help catch you up to speed on working with 🤗 Accelerate. +You'll learn how to modify your code to have it work with the API seamlessly, how to launch your script properly, +and more! + +These tutorials assume some basic knowledge of Python and familiarity with the PyTorch framework. + +If you have any questions about 🤗 Accelerate, feel free to join and ask the community on our [forum](https://discuss.huggingface.co/c/accelerate/18). \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/tpu.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/tpu.md new file mode 100644 index 0000000000000000000000000000000000000000..f4780e3fe5f555b35d3d867fe0da071b49eb3c6a --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/tpu.md @@ -0,0 +1,38 @@ + + +# TPU training + +A [TPU (Tensor Processing Unit)](https://cloud.google.com/tpu/docs/intro-to-tpu) is a type of hardware specifically designed for training models efficiently. Accelerate supports TPU training, but there are a few things you should be aware of, namely graph compilation. This tutorial briefly discusses compilation, and for more details, take a look at the [Training on TPUs with Accelerate](../concept_guides/training_tpu) guide. + +## Compilation + +A TPU creates a graph of all the operations in the training step such as the forward pass, backward pass and optimizer step. This is why the first training step always takes a while because building and compiling this graph takes time. But once compilation is complete, it is cached and all subsequent steps are much faster. + +The key is to avoid compiling your code again or else training is super slow. This means all your operations must be exactly the same: + +* all tensors in your batches must have the same length (for example, no dynamic padding for NLP tasks) +* your code must be static (for example, no layers with for loops that have different lengths depending on the input such as a LSTM) + +## Weight tying + +A common language model design is to tie the weights of the embedding and softmax layers. However, moving the model to a TPU (either yourself or passing it to the [`~Accelerator.prepare`] method) breaks the weight tying and you'll need to retie the weights. + +To add special behavior (like weight tying) in your script for TPUs, set [`~Accelerator.distributed_type`] to `DistributedType.TPU` first. Then you can use the [`~transformers.PreTrainedModel.tie_weights`] method to tie the weights. + +```py +if accelerator.distributed_type == DistributedType.TPU: + model.tie_weights() +``` diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/troubleshooting.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/troubleshooting.md new file mode 100644 index 0000000000000000000000000000000000000000..6752bffc692d780885fab180d35a2fba1540b586 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/basic_tutorials/troubleshooting.md @@ -0,0 +1,211 @@ + + +# Troubleshoot + +This guide provides solutions to some issues you might encounter when using Accelerate. Not all errors are covered because Accelerate is an active library that is continuously evolving and there are many different use cases and distributed training setups. If the solutions described here don't help with your specific error, please take a look at the [Ask for help](#ask-for-help) section to learn where and how to get help. + +## Logging + +Logging can help you identify where an error is coming from. In a distributed setup with multiple processes, logging can be a challenge, but Accelerate provides the [`~accelerate.logging`] utility to ensure logs are synchronized. + +To troubleshoot an issue, use [`~accelerate.logging`] instead of the standard Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging) module. Set the verbosity level (`INFO`, `DEBUG`, `WARNING`, `ERROR`, `CRITICAL`) with the `log_level` parameter, and then you can either: + +1. Export the `log_level` as the `ACCELERATE_LOG_LEVEL` environment variable. +2. Pass the `log_level` directly to `get_logger`. + +For example, to set `log_level="INFO"`: + +```py +from accelerate.logging import get_logger + +logger = get_logger(__name__, log_level="DEBUG") +``` + +By default, the log is called on main processes only. To call it on all processes, pass `main_process_only=False`. +If a log should be called on all processes and in order, also pass `in_order=True`. + +```py +from accelerate.logging import get_logger + +logger = get_logger(__name__, log_level="DEBUG") +# log all processes +logger.debug("thing_to_log", main_process_only=False) +# log all processes in order +logger.debug("thing_to_log", main_process_only=False, in_order=True) +``` + +## Hanging code and timeout errors + +There can be many reasons why your code is hanging. Let's take a look at how to solve some of the most common issues that can cause your code to hang. + +### Mismatched tensor shapes + +Mismatched tensor shapes is a common issue that can cause your code to hang for a significant amount of time on a distributed setup. + +When running scripts in a distributed setup, functions such as [`Accelerator.gather`] and [`Accelerator.reduce`] are necessary to grab tensors across devices to collectively perform operations on them. These (and other) functions rely on `torch.distributed` to perform a `gather` operation, which requires tensors to have the **exact same shape** across all processes. When the tensor shapes don't match, your code hangs and you'll eventually hit a timeout exception. + +You can use Accelerate's operational debug mode to immediately catch this issue. We recommend enabling this mode during the `accelerate config` setup, but you can also enable it from the CLI, as an environment variable, or by manually editing the `config.yaml` file. + + + + +```bash +accelerate launch --debug {my_script.py} --arg1 --arg2 +``` + + + + +If enabling debug mode as an environment variable, you don't need to call `accelerate launch`. + +```bash +ACCELERATE_DEBUG_MODE="1" torchrun {my_script.py} --arg1 --arg2 +``` + + + + +Add `debug: true` to your `config.yaml` file. + +```yaml +compute_environment: LOCAL_MACHINE +debug: true +``` + + + + +Once you enable debug mode, you should get a traceback that points to the tensor shape mismatch issue. + +```py +Traceback (most recent call last): + File "/home/zach_mueller_huggingface_co/test.py", line 18, in + main() + File "/home/zach_mueller_huggingface_co/test.py", line 15, in main + broadcast_tensor = broadcast(tensor) + File "/home/zach_mueller_huggingface_co/accelerate/src/accelerate/utils/operations.py", line 303, in wrapper +accelerate.utils.operations.DistributedOperationException: + +Cannot apply desired operation due to shape mismatches. All shapes across devices must be valid. + +Operation: `accelerate.utils.operations.broadcast` +Input shapes: + - Process 0: [1, 5] + - Process 1: [1, 2, 5] +``` + +### Early stopping + +For early stopping in distributed training, if each process has a specific stopping condition (e.g. validation loss), it may not be synchronized across all processes. As a result, a break can happen on process 0 but not on process 1 which will cause your code to hang indefinitely until a timeout occurs. + +If you have early stopping conditionals, use the `set_breakpoint` and `check_breakpoint` methods to make sure all the processes +are ended correctly. + +```py +# Assume `should_do_breakpoint` is a custom defined function that returns a conditional, +# and that conditional might be true only on process 1 +if should_do_breakpoint(loss): + accelerator.set_breakpoint() + +# Later in the training script when we need to check for the breakpoint +if accelerator.check_breakpoint(): + break +``` + +### Low kernel versions on Linux + +On Linux with kernel version < 5.5, hanging processes have been reported. To avoid this problem, upgrade your system to a later kernel version. + +### MPI + +If your distributed CPU training job using MPI is hanging, ensure that you have +[passwordless SSH](https://www.open-mpi.org/faq/?category=rsh#ssh-keys) setup (using keys) between the nodes. This means +that for all nodes in your hostfile, you should to be able to SSH from one node to another without being prompted for a password. + +Next, try to run the `mpirun` command as a sanity check. For example, the command below should print out the +hostnames for each of the nodes. + +```bash +mpirun -f hostfile -n {number of nodes} -ppn 1 hostname +``` + +## CUDA Out-of-Memory + +One of the most frustrating errors when it comes to running training scripts is hitting "CUDA Out-of-Memory". The entire script needs to be restarted and any progress is lost. + +To address this problem, Accelerate provides the [`find_executable_batch_size`] utility that is heavily based on [toma](https://github.com/BlackHC/toma). +This utility retries code that fails due to OOM (out-of-memory) conditions and automatically lowers batch sizes. For each OOM condition, the algorithm decreases the batch size by half and retries the code until it succeeds. + +To use [`find_executable_batch_size`], restructure your training function to include an inner function with `find_executable_batch_size` and build your dataloaders inside it. At a minimum, this only takes 4 new lines of code. + + + +The inner function **must** take batch size as the first parameter, but we do not pass one to it when called. The wrapper will handles this for you. Any object (models, optimizers) that consumes CUDA memory and is passed to the [`Accelerator`] also **must** be declared inside the inner function. + + + +```diff +def training_function(args): + accelerator = Accelerator() + ++ @find_executable_batch_size(starting_batch_size=args.batch_size) ++ def inner_training_loop(batch_size): ++ nonlocal accelerator # Ensure they can be used in our context ++ accelerator.free_memory() # Free all lingering references + model = get_model() + model.to(accelerator.device) + optimizer = get_optimizer() + train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size) + lr_scheduler = get_scheduler( + optimizer, + num_training_steps=len(train_dataloader)*num_epochs + ) + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader, lr_scheduler + ) + train(model, optimizer, train_dataloader, lr_scheduler) + validate(model, eval_dataloader) ++ inner_training_loop() +``` + +## Non-reproducible results between device setups + +If you changed the device setup and observe different model performance, it is likely you didn't update your script when moving from one setup to another. Even if you're using the same script with the same batch size, the results will still be different on a TPU, multi-GPU, and single GPU. + +For example, if you were training on a single GPU with a batch size of 16 and you move to a dual GPU setup, you need to change the batch size to 8 to have the same effective batch size. This is because when training with Accelerate, the batch size passed to the dataloader is the **batch size per GPU**. + +To make sure you can reproduce the results between the setups, make sure to use the same seed, adjust the batch size accordingly, and consider scaling the learning rate. + +For more details and a quick reference for batch sizes, check out the [Comparing performance between different device setups](../concept_guides/performance) guide. + +## Performance issues on different GPUs + +If your multi-GPU setup consists of different GPUs, you may encounter some performance issues: + +- There may be an imbalance in GPU memory between the GPUs. In this case, the GPU with the smaller memory will limit the batch size or the size of the model that can be loaded onto the GPUs. +- If you are using GPUs with different performance profiles, the performance will be driven by the slowest GPU you are using because the other GPUs will have to wait for it to complete its workload. + +Vastly different GPUs within the same setup can lead to performance bottlenecks. + +## Ask for help + +If none of the solutions and advice here helped resolve your issue, you can always reach out to the community and Accelerate team for help. + +- Ask for help on the Hugging Face forums by posting your question in the [🤗 Accelerate category](https://discuss.huggingface.co/c/accelerate/18). Make sure to write a descriptive post with relevant context about your setup and reproducible code to maximize the likelihood that your problem is solved! + +- Post a question on [Discord](http://hf.co/join/discord), and let the team and the community help you. + +- Create an Issue on the 🤗 Accelerate [GitHub repository](https://github.com/huggingface/accelerate/issues) if you think you've found a bug related to the library. Include context regarding the bug and details about your distributed setup to help us better figure out what's wrong and how we can fix it. diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/big_model_inference.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/big_model_inference.md new file mode 100644 index 0000000000000000000000000000000000000000..b2d8ab038ae0f4abdf985ff099dd1d27a0684869 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/big_model_inference.md @@ -0,0 +1,341 @@ + + +# Handling big models for inference + +When loading a pre-trained model in PyTorch, the usual workflow looks like this: + +```py +import torch + +my_model = ModelClass(...) +state_dict = torch.load(checkpoint_file) +my_model.load_state_dict(state_dict) +``` + +In plain English, those steps are: +1. Create the model with randomly initialized weights +2. Load the model weights (in a dictionary usually called a state dict) from the disk +3. Load those weights inside the model + +While this works very well for regularly sized models, this workflow has some clear limitations when we deal with a huge model: in step 1, we load a full version of the model in RAM, and spend some time randomly initializing the weights (which will be discarded in step 3). In step 2, we load another full version of the model in RAM, with the pre-trained weights. If you're loading a model with 6 billion parameters, this means you will need 24GB of RAM for each copy of the model, so 48GB in total (half of it to load the model in FP16). + + + +This API is quite new and still in its experimental stage. While we strive to provide a stable API, it's possible some small parts of the public API will change in the future. + + + +## How the Process Works: A Quick Overview + + + +## How the Process Works: Working with Code + +### Instantiating an empty model + +The first tool 🤗 Accelerate introduces to help with big models is a context manager [`init_empty_weights`] that helps you initialize a model without using any RAM so that step 1 can be done on models of any size. Here is how it works: + +```py +from accelerate import init_empty_weights + +with init_empty_weights(): + my_model = ModelClass(...) +``` + +For instance: + +```py +with init_empty_weights(): + model = nn.Sequential(*[nn.Linear(10000, 10000) for _ in range(1000)]) +``` + +initializes an empty model with a bit more than 100B parameters. Behind the scenes, this relies on the meta device introduced in PyTorch 1.9. During the initialization under the context manager, each time a parameter is created, it is instantly moved to that device. + + + + You can't move a model initialized like this on CPU or another device directly, since it doesn't have any data. It's also very likely that a forward pass with that empty model will fail, as not all operations are supported on the meta device. + + + +### Sharded checkpoints + +It's possible your model is so big that even a single copy won't fit in RAM. That doesn't mean it can't be loaded: if you have one or several GPUs, this is more memory available to store your model. In this case, it's better if your checkpoint is split into several smaller files that we call checkpoint shards. + +🤗 Accelerate will handle sharded checkpoints as long as you follow the following format: your checkpoint should be in a folder, with several files containing the partial state dicts, and there should be an index in the JSON format that contains a dictionary mapping parameter names to the file containing their weights. You can easily shard your model with [`~Accelerator.save_model`]. For instance, we could have a folder containing: + +```bash +first_state_dict.bin +index.json +second_state_dict.bin +``` + +with index.json being the following file: + +``` +{ + "linear1.weight": "first_state_dict.bin", + "linear1.bias": "first_state_dict.bin", + "linear2.weight": "second_state_dict.bin", + "linear2.bias": "second_state_dict.bin" +} +``` + +and `first_state_dict.bin` containing the weights for `"linear1.weight"` and `"linear1.bias"`, `second_state_dict.bin` the ones for `"linear2.weight"` and `"linear2.bias"` + +### Loading weights + +The second tool 🤗 Accelerate introduces is a function [`load_checkpoint_and_dispatch`], that will allow you to load a checkpoint inside your empty model. This supports full checkpoints (a single file containing the whole state dict) as well as sharded checkpoints. It will also automatically dispatch those weights across the devices you have available (GPUs, CPU RAM), so if you are loading a sharded checkpoint, the maximum RAM usage will be the size of the biggest shard. + +If you want to use big model inference with 🤗 Transformers models, check out this [documentation](https://huggingface.co/docs/transformers/main/en/main_classes/model#large-model-loading). + +Here is how we can use this to load the [GPT2-1.5B](https://huggingface.co/marcsun13/gpt2-xl-linear-sharded) model. + +Let's download the sharded version of this model. + +```bash +pip install huggingface_hub +``` + +```py +from huggingface_hub import snapshot_download +checkpoint = "marcsun13/gpt2-xl-linear-sharded" +weights_location = snapshot_download(repo_id=checkpoint) +``` + +In order to initialize the model, we will use the library minGPT. + +```bash +git clone https://github.com/karpathy/minGPT.git +pip install minGPT/ +``` + +```py +from accelerate import init_empty_weights +from mingpt.model import GPT + +model_config = GPT.get_default_config() +model_config.model_type = 'gpt2-xl' +model_config.vocab_size = 50257 +model_config.block_size = 1024 + +with init_empty_weights(): + model = GPT(model_config) +``` + +Then, load the checkpoint we just downloaded with: + +```py +from accelerate import load_checkpoint_and_dispatch + +model = load_checkpoint_and_dispatch( + model, checkpoint=weights_location, device_map="auto", no_split_module_classes=['Block'] +) +``` + +By passing `device_map="auto"`, we tell 🤗 Accelerate to determine automatically where to put each layer of the model depending on the available resources: +- first, we use the maximum space available on the GPU(s) +- if we still need space, we store the remaining weights on the CPU +- if there is not enough RAM, we store the remaining weights on the hard drive as memory-mapped tensors + + +#### `no_split_module_classes` + +This parameter will indicate that some of the modules with the name `"Block"` should not be split across different devices. You should set here all blocks that +include a residual connection of some kind. + + +#### The `device_map` + +You can see the `device_map` that 🤗 Accelerate picked by accessing the `hf_device_map` attribute of your model: + +```py +model.hf_device_map +``` + +```python out +{'transformer.wte': 0, + 'transformer.wpe': 0, + 'transformer.drop': 0, + 'transformer.h.0': 0, + ... + 'transformer.h.21': 0, + 'transformer.h.22': 1, + 'transformer.h.23': 1, + 'transformer.h.24': 1, + ... + 'transformer.h.47': 1, + 'transformer.ln_f': 1, + 'lm_head': 1} + ``` + +It's fully possible to create your own device map for the layers to use as well, specifying the GPU device to use (a number), `"cpu"`, or `"disk"` and pass this in: + +```python +device_map = { + "transformer.wte": "cpu", + "transformer.wpe": 0, + "transformer.drop": "cpu", + "transformer.h.0": "disk" +} + +model = load_checkpoint_and_dispatch( + model, checkpoint=weights_location, device_map=device_map +) + +``` + +### Run the model + +Now that we have done this, our model lies across several devices, and maybe the hard drive. But it can still be used as a regular PyTorch model: + +```py +from mingpt.bpe import BPETokenizer +tokenizer = BPETokenizer() +inputs = tokenizer("Hello, my name is").to(0) + +outputs = model.generate(x1, max_new_tokens=10, do_sample=False)[0] +tokenizer.decode(outputs.cpu().squeeze()) +``` + +Behind the scenes, 🤗 Accelerate added hooks to the model, so that: +- at each layer, the inputs are put on the right device (so even if your model is spread across several GPUs, it works) +- for the weights offloaded on the CPU, they are put on a GPU just before the forward pass and cleaned up just after +- for the weights offloaded on the hard drive, they are loaded in RAM then put on a GPU just before the forward pass and cleaned up just after + +This way, your model can run for inference even if it doesn't fit on one of the GPUs or the CPU RAM! + + + + This only supports the inference of your model, not training. Most of the computation happens behind `torch.no_grad()` context managers to avoid spending some GPU memory with intermediate activations. + + + +### Designing a device map + +You can let 🤗 Accelerate handle the device map computation by setting `device_map` to one of the supported options (`"auto"`, `"balanced"`, `"balanced_low_0"`, `"sequential"`) or create one yourself if you want more control over where each layer should go. + + + + You can derive all sizes of the model (and thus compute a `device_map`) on a model that is on the meta device. + + + +All the options will produce the same result when you don't have enough GPU memory to accommodate the whole model (which is to fit everything that can on the GPU, then offload weights on the CPU or even on the disk if there is not enough RAM). + +When you have more GPU memory available than the model size, here is the difference between each option: +- `"auto"` and `"balanced"` evenly split the model on all available GPUs, making it possible for you to use a batch size greater than 1. +- `"balanced_low_0"` evenly splits the model on all GPUs except the first one, and only puts on GPU 0 what does not fit on the others. This option is great when you need to use GPU 0 for some processing of the outputs, like when using the `generate` function for Transformers models +- `"sequential"` will fit what it can on GPU 0, then move on GPU 1 and so forth (so won't use the last GPUs if it doesn't need to). + + + + The options `"auto"` and `"balanced"` produce the same results for now, but the behavior of `"auto"` might change in the future if we find a strategy that makes more sense, while `"balanced"` will stay stable. + + + +First note that you can limit the memory used on each GPU by using the `max_memory` argument (available in [`infer_auto_device_map`] and in all functions using it). When setting `max_memory`, you should pass along a dictionary containing the GPU identifiers (for instance `0`, `1` etc.) and the `"cpu"` key for the maximum RAM you want to use for CPU offload. The values can either be an integer (in bytes) or a string representing a number with its unit, such as `"10GiB"` or `"10GB"`. + +Here is an example where we don't want to use more than 10GiB on each of the two GPUs and no more than 30GiB of CPU RAM for the model weights: + +```python +from accelerate import infer_auto_device_map + +device_map = infer_auto_device_map(my_model, max_memory={0: "10GiB", 1: "10GiB", "cpu": "30GiB"}) +``` + + + + When a first allocation happens in PyTorch, it loads CUDA kernels which take about 1-2GB of memory depending on the GPU. Therefore you always have less usable memory than the actual size of the GPU. To see how much memory is actually used do `torch.ones(1).cuda()` and look at the memory usage. + + Therefore when you create memory maps with `max_memory` make sure to adjust the available memory accordingly to avoid out-of-memory errors. + + + +Additionally, if you do some additional operations with your outputs without placing them back on the CPU (for instance inside the `generate` method of Transformers) and if you placed your inputs on a GPU, that GPU will consume more memory than the others (Accelerate always place the output back to the device of the input). Therefore if you would like to optimize the maximum batch size and you have many GPUs, give the first GPU less memory. For example, with BLOOM-176B on 8x80 A100 setup, the close-to-ideal map is: + +```python +max_memory = {0: "30GIB", 1: "46GIB", 2: "46GIB", 3: "46GIB", 4: "46GIB", 5: "46GIB", 6: "46GIB", 7: "46GIB"} +``` +as you can see we gave the remaining 7 GPUs ~50% more memory than GPU 0. + +If you opt to fully design the `device_map` yourself, it should be a dictionary with keys being module names of your model and values being a valid device identifier (for instance an integer for the GPUs) or `"cpu"` for CPU offload, `"disk"` for disk offload. The keys need to cover the whole model, you can then define your device map as you wish: for instance, if your model has two blocks (let's say `block1` and `block2`) which each contain three linear layers (let's say `linear1`, `linear2` and `linear3`), a valid device map can be: + +```python +device_map = {"block1": 0, "block2": 1} +``` + +another one that is valid could be: + +```python +device_map = {"block1": 0, "block2.linear1": 0, "block2.linear2": 1, "block2.linear3": 1} +``` + +On the other hand, this one is not valid as it does not cover every parameter of the model: + +```python +device_map = {"block1": 0, "block2.linear1": 1, "block2.linear2": 1} +``` + + + + To be the most efficient, make sure your device map puts the parameters on the GPUs in a sequential manner (e.g. don't put one of the first weights on GPU 0, then weights on GPU 1 and the last weight back to GPU 0) to avoid making many transfers of data between the GPUs. + + + +## CPU offload only + +If you want to offload your model on CPU, you can use [`cpu_offload`]. As a result, all parameters of the model will be offloaded and only one copy of the state dict of the model will be kept. During the forward pass, parameters will be extracted from that state dict and put on the execution device and passed as they are needed, then offloaded again. + +```python +cpu_offload(model, execution_device) +``` + +You can also use [`cpu_offload_with_hook`]. This function will offloads a model on the CPU and puts it back to an execution device when executed. The difference with [`cpu_offload`] is that the model stays on the execution device after the forward and is only offloaded again when the `offload` method of the returned `hook` is called. Furthermore, [`cpu_offload_with_hook`] is more performant but less memory saving. It is useful for pipelines running a model in a loop: + +```python +model_1, hook_1 = cpu_offload_with_hook(model_1, execution_device) +model_2, hook_2 = cpu_offload_with_hook(model_2, execution_device, prev_module_hook=hook_1) +model_3, hook_3 = cpu_offload_with_hook(model_3, execution_device, prev_module_hook=hook_2) + +hid_1 = model_1(input) +for i in range(50): + # model1 is offloaded on the CPU at the first iteration, model 2 stays on the GPU for this whole loop. + hid_2 = model_2(hid_1) +# model2 is offloaded to the CPU just before this forward. +hid_3 = model_3(hid_3) + +# For model3, you need to manually call the hook offload method. +hook_3.offload() +``` + +## Disk offload only + +To perform disk offload, you can use [`disk_offload`]. As a result, all parameters of the model will be offloaded as memory-mapped array in a given folder. During the forward pass, parameters will be accessed from that folder and put on the execution device passed as they are needed, then offloaded again. + +```python +disk_offload(model, offload_dir, execution_device) +``` + +## Limits and further development + +We are aware of the current limitations in the API: + +- [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) tries to maximize GPU and CPU RAM it sees available when you execute it. While PyTorch is very good at managing GPU RAM efficiently (and giving it back when not needed), it's not entirely true with Python and CPU RAM. Therefore, an automatically computed device map might be too intense on the CPU. Move a few modules to the disk device if you get crashes due to a lack of RAM. +- [`infer_auto_device_map`] (or `device_map="auto"` in [`load_checkpoint_and_dispatch`]) attributes devices sequentially (to avoid moving things back and forth) so if your first layer is bigger than the size of the GPU you have, it will end up with everything on the CPU/Disk. +- [`load_checkpoint_and_dispatch`] and [`load_checkpoint_in_model`] do not perform any check on the correctness of your state dict compared to your model at the moment (this will be fixed in a future version), so you may get some weird errors if trying to load a checkpoint with mismatched or missing keys. +- The model parallelism used when your model is split on several GPUs is naive and not optimized, meaning that only one GPU works at a given time and the other sits idle. +- When weights are offloaded on the CPU/hard drive, there is no pre-fetching (yet, we will work on this for future versions) which means the weights are put on the GPU when they are needed and not before. +- Hard-drive offloading might be very slow if the hardware you run on does not have fast communication between disk and CPU (like NVMes). diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/deferring_execution.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/deferring_execution.md new file mode 100644 index 0000000000000000000000000000000000000000..f90b38e6a8bf49ade32765e4011f967d124fa235 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/deferring_execution.md @@ -0,0 +1,130 @@ + + +# Deferring Executions + +When you run your usual script, instructions are executed in order. Using 🤗 Accelerate to deploy your script on several +GPUs at the same time introduces a complication: while each process executes all instructions in order, some may be +faster than others. + +You might need to wait for all processes to have reached a certain point before executing a given instruction. For +instance, you shouldn't save a model before being sure every process is done with training, and you wouldn't want to +continue training before all the model weights have been loaded in. To do this, just write the following line in your code: + +``` +accelerator.wait_for_everyone() +``` + +This instruction will block all the processes that arrive first until all the other processes have reached that +point (if you run your script on just one GPU or CPU, this won't do anything). + +A few example cases of when to use this utility are listed below: + + + + Some of these are utilized with the [`~Accelerator.main_process_first`] context manager, which utilizes [`~Accelerator.wait_for_everyone`] to + run a particular set of code on the main process beforehand before triggering and launching the other processes + + + +## Downloading a Dataset + +When downloading a dataset, you should download it first on the main process and then load the cached dataset afterward + + + + `load_dataset` will perform a lock under the hood to stop multiple downloads from happening at once, but if you are downloading something + not using this library you should use this method. + + + +```python +with accelerator.main_process_first(): + datasets = load_dataset("glue", "mrpc") +``` + +Under the hood this is the same as calling: + +```python +# First do something on the main process +if accelerator.is_main_process: + datasets = load_dataset("glue", "mrpc") +else: + accelerator.wait_for_everyone() + +# And then send it to the rest of them +if not accelerator.is_main_process: + datasets = load_dataset("glue", "mrpc") +else: + accelerator.wait_for_everyone() +``` + +## Saving the `state_dict` + +When saving the `state_dict` of the model, since you would normally save one file on just the main process +you should specify that: + +```python +if accelerator.is_main_process: + model = accelerator.unwrap_model(model) + torch.save(model.state_dict(), "weights.pth") +``` + +## Loading in the `state_dict` + +When loading in the `state_dict` to a model, optimizer, or scheduler, you should wait +for all workers to have the weights loaded in before moving on to training + +```python +with accelerator.main_process_first(): + state = torch.load("weights.pth") + model.load_state_dict(state) +``` + +## Applying a multi-worker CPU operation + +Applying a `map()` operation on multiple workers, such as tokenizing should be done on the +main process first, and then propagated to each one. + +```python +datasets = load_dataset("glue", "mrpc") + +with accelerator.main_process_first(): + tokenized_datasets = datasets.map( + tokenize_function, + batched=True, + remove_columns=["idx", "sentence1", "sentence2"], + ) +``` + +## Applying checks such as Early Stopping + +To have a check that works with a flag set by a particular process, the `set_trigger` and `check_trigger` API should be used. Useful examples +for doing so can include situations such as using early stopping and monitoring the loss (as each loss slightly differs on each process). + +Call [`Accelerator.set_trigger`] when your condition has been met, and [`Accelerator.check_trigger`] when checking if that condition has been met in any process: + +```python +for (x,y) in data_loader: + logits = model(x) + loss = loss_func(logits, y) + # Assume `should_do_early_stopping` is a custom defined function that returns a conditional + if should_do_early_stopping(loss): + accelerator.set_trigger() + + # Later in the training script when we need to check for the breakpoint + if accelerator.check_trigger(): + break +``` \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/fsdp_and_deepspeed.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/fsdp_and_deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..6665eb8885cb0ded847a2ef3446dd850efb2fca6 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/fsdp_and_deepspeed.md @@ -0,0 +1,192 @@ + + +# Moving between FSDP And DeepSpeed + +🤗 Accelerate offers flexibilty of training frameworks, by integrating two extremely powerful tools for distributed training, namely [Pytorch FSDP](../usage_guides/fsdp) and [Microsoft DeepSpeed](../usage_guides/deepspeed). The aim of this tutorial is to draw parallels, as well as to outline potential differences, to empower the user to switch seamlessly between these two frameworks. + + + + To switch between the frameworks, we recommend launching code 🤗 `accelerate launch` passing in the correct config file with `--config_file`, or passing in the respective arguments directly for [FSDP and DeepSpeed](../package_reference/cli#accelerate-launch) . + + Example 🤗 Accelerate configurations can be found here for [DeepSpeed](../usage_guides/deepspeed#accelerate-deepspeed-plugin) and [FSDP](../usage_guides/fsdp#how-it-works-out-of-the-box), or in the [example zoo under "Launch Configurations"](../usage_guides/explore) + + + + + +This tutorial is for single-node, multi-GPU, scenarios only. + + + +## Configuring Functionalities + +Model tensors are split into different GPUs in an attempt to scale up model sizes; this is termed *sharding* in FSDP, and *partitioning* in DeepSpeed. FSDP sharding and DeepSpeed ZeRO (partitioning) stages are configured by `--fsdp_sharding_strategy`, and `--zero_stage`, respectively. In particular, FSDP `FULL_SHARD` maps to DeepSpeed ZeRO stage `3`; see this [comprehensive mapping between FSDP sharding and DeepSpeed ZeRO settings](../usage_guides/fsdp#mapping-between-fsdp-sharding-strategies-and-deepspeed-zero-stages). The below table summarizes and groups similar settings: + +Group | Framework | Configuration | Example | Restrictions (if any) +--|--|--|--|-- +sharding / partitioning | FSDP
DeepSpeed | `--fsdp_sharding_strategy`
`--zero_stage` | `1` (`FULL_SHARD`)
`3` | +offload | FSDP
DeepSpeed | `--fsdp_offload_params`
`--offload_param_device`
`--offload_optimizer_device` | `true`
`cpu`
`cpu` | all or nothing

+model loading | FSDP
DeepSpeed | `--fsdp_cpu_ram_efficient_loading`
`--zero3_init_flag` | `true`
`true` |
only ZeRO 3 +efficient checkpointing | FSDP
DeepSpeed | `--fsdp_state_dict_type`
`--zero3_save_16bit_model` | `SHARDED_STATE_DICT`
`true` |
only ZeRO 3 +weights prefetching | FSDP

DeepSpeed | `--fsdp_forward_prefetch`
`--fsdp_backward_prefetch`
None | `true`
`BACKWARD_PRE` |

+model | FSDP

DeepSpeed | `--fsdp_auto_wrap_policy`
`--fsdp_transformer_layer_cls_to_wrap`
None | `TRANSFORMER_BASED_WRAP`
|
Usually not needed
Transparent to user. +parameters summoning | FSDP
DeepSpeed | `--fsdp_use_orig_params`
None | `true` | required for `torch.compile`
Transparent to user +parameters syncing | FSDP
DeepSpeed | `--fsdp_sync_module_states`
None | `true` | +training | FSDP
DeepSpeed | None
`--gradient_accumulation_steps`
`--gradient_clipping` |
`auto`
`auto` | Transparent to user + +For detailed descriptions of the above, refer to [🤗 `Accelerate` launch documentation](../package_reference/cli#accelerate-launch). + + + + To access other DeepSpeed configurations, such as mixed precision settings, + you need to pass in a `--deepspeed_config_file`, see the [documentation](../usage_guides/deepspeed#deepspeed-config-file). + + DeepSpeed can be also configured via [`DeepSpeedPlugin`], e.g., `DeepSpeedPlugin.zero_stage` is equivalent of `--zero_stage`, and `DeepSpeedPlugin.hf_ds_config` can be used to pass `--deepeed_config_file.` + + + + + + FSDP can be also configured via [`FullyShardedDataParallelPlugin`], e.g., `FullyShardedDataParallelPlugin.sharding_strategy` is equivalent of `--fsdp_sharding_strategy`. + + + +### Checkpointing + +Do note that while FSDP can be configured via `--fsdp_state_dict_type` to save either full / sharded checkpoints. + + + + For DeepSpeed Zero3, one could pass a `--zero3_save_16bit_model true`, which conveniently consolidates the model to a single rank and saves; this is the FSDP equivalent of `fsdp_state_dict_type: FULL_STATE_DICT`. + + + + + + For large models, consolidating the model to a single rank can be very slow. + + + + + + For quicker checkpointing, for FSDP use `fsdp_state_dict_type: SHARDED_STATE_DICT`, and for DeepSpeed Zero3 [use the `zero_to_fp32.py` script to post-convert sharded checkpoints](https://www.deepspeed.ai/tutorials/zero/#extracting-weights). + + + + +### Offloading + +FSDP only allows *all-or-nothing* offload (i.e., either offload parameters, gradients, and optimizer, or keep them all in GPU), but DeepSpeed can offload parameters and optimizer differently. Furthermore, DeepSpeed also supports [offloading to NVME](https://www.deepspeed.ai/docs/config-json/#parameter-offloading). + +### Prefetching + +FSDP allows two prefetching configurations `--fsdp_forward_prefetch` and `--fsdp_backward_prefetch` to improve overlap of comms / computation at a cost of extra memory, see [FSDP documentation](https://pytorch.org/docs/stable/fsdp.html). +For DeepSpeed, the prefetching will be turned on when needed, and it turns on depending on certain hyper-params like `stage3_param_persistence_threshold`, `stage3_max_reuse_distance`, etc, [that can be configured for Zero3](https://www.deepspeed.ai/docs/config-json/#parameter-offloading); 🤗 `accelerate` may set these hyper-params automatically if you don't set those explicitly in the deepspeed config file. + + + + For FSDP set `fsdp_backward_prefetch: BACKWARD_PRE` for improved throughputs if memory allows. + + + +### Model Loading + +While FSDP require an explicit `--fsdp_cpu_ram_efficient_loading true` to activate efficient model loading, 🤗 `transformers` will activate the similar feature whenever DeepSpeed Zero3 is used. + + + + For FSDP, whenever setting `--fsdp_cpu_ram_efficient_loading true`, 🤗 `accelerate` will automatically set `sync_module_states` to true. + For RAM efficient loading the weights will be loaded only in a singe rank, and thus requires `sync_module_states` to broadcast weights to other ranks. + + + +### Model + +FSDP requires an explicit `--fsdp_auto_wrap_policy` for the algorithm to decide how to schedule the all-gather and reduce-scatter operations. But for DeepSpeed this is transparent to the user. + + + + For FSDP, simply set `fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP`. With the latest [`transformers`] versions, we try our best to figure out the suitable `fsdp_transformer_layer_cls_to_wrap` for HF transformers models. However, if you get an error regarding it, please specify this. + + + +### Parameters Summoning + +FSDP requires an explicit `--fsdp_use_orig_params` flag if using `torch.compile`, see [the pytorch documenation](https://pytorch.org/docs/stable/fsdp.html#module-torch.distributed.fsdp). For DeepSpeed this is transparent to the user. + + + + For FSDP, when using `torch.compile` please set `fsdp_use_orig_params: True`. + + + + +## Training + +Deepspeed requires explicit `--gradient_accumulation_steps` and `--gradient_clipping` flags. For FSDP this is transparent to the user. + + + + When using DeepSpeed, set `gradient_accumulation_steps: "auto"` and `gradient_clipping: "auto"` to automatically pick up values set in the [`Accelerator`] or [`TrainingArguments`] (if using `transformers`). + + + + +## On Differences in Data Precision Handling + +To discuss the how data precision is handled in both FSDP and Deepspeed, it is instructive to first give an overview of how model parameters are handled in these frameworks. Before the model / optimizer parameters are distributed across GPUs, parameter preparation is involved to first "flatten" them to one-dimensional [`torch.Tensor`](https://pytorch.org/docs/stable/tensors.html#torch-tensor). The implementation of FSDP / DeepSpeed varies in the respect of the `dtype` in which these "flattened" parameters are stored, and there are ramifications with regards to how [`torch.Optimizer`](https://pytorch.org/docs/stable/optim.html#module-torch.optim) allocate their `dtype`s. The table below outlines the processes for both frameworks; the "Local" column indicates the process occurring at a per-gpu level, therefore any memory overheads by upcasting should be understood to be amortized by the number of gpus used. + + + + As a rule of thumb, for stable training with automatic mixed precision, all the trainable parameters have to be in `torch.float32`. + + + +Process | Local | Framework | Details +--|--|--|-- +Loading, i.e., [`AutoModel.from_pretrained(..., torch_dtype=torch_dtype)`] | +Preparation, i.e., creation of "flat params" | ✅ | FSDP
DeepSpeed | created in `torch_dtype`.
disregards `torch_dtype`, created in `float32`. +Optimizer initialization | ✅ | FSDP
DeepSpeed | creates parameters in `torch_dtype`
creates parameters in `float32` +Training Step, i.e, forward, backward, reduction | | FSDP
DeepSpeed | follows [`MixedPrecision`](https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.MixedPrecision)
follows `deepspeed_config_file` mixed precision settings. +Optimizer (Pre-Step) | ✅ | FSDP
DeepSpeed | upcasting (if any) to `torch_dtype`
upcasted to `float32` +Optimizer (Actual Step) | ✅ | FSDP
DeepSpeed | occurs in `torch_dtype`
occurs in `float32`. + + + + Therefore when using DeepSpeed a small number of GPUs, be aware of potentially significant memory overheads due to the upcasting during preperation. + + + + + + With FSDP, in the absence of mixed precision, it is possible to operate the [`torch.Optimizer`](https://pytorch.org/docs/stable/optim.html#module-torch.optim) in low precision `torch_dtype`, which may be helpful when using small number of GPUs. + + + + + + With mixed precision, FSDP and DeepSpeed will upcast in the model preparation step (c.f. table above). But do note that FSDP will then save checkpoints in the upcasted precision; Deepspeed may still save low precision checkpoints if `--zero3_save_16bit_model` is specified. + + + + +To clarify the above table consider the concrete examples below; the optimizer pre- and actual step combined for brevity. With FSDP it is possible to operate in the two modes shown below, but DeepSpeed can only operate in one. + +Framework | Model Loading (`torch_dtype`) | Mixed Precision | Preparation (Local) | Training | Optimizer (Local) +--|--|--|--|--|-- +FSDP | bf16 | default (none) | bf16 | bf16 | bf16 +FSDP | bf16 | bf16 | fp32 | bf16 | fp32 +DeepSpeed | bf16 | bf16 | fp32 | bf16 | fp32 diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/gradient_synchronization.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/gradient_synchronization.md new file mode 100644 index 0000000000000000000000000000000000000000..d90ac29fd23ce3e805983e614ff35e8a50f2c832 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/gradient_synchronization.md @@ -0,0 +1,184 @@ + + +# Gradient Synchronization + +PyTorch's distributed module operates by communicating back and forth between all of the GPUs in your system. +This communication takes time, and ensuring all processes know the states of each other happens at particular triggerpoints +when using the `ddp` module. + +These triggerpoints are added to the PyTorch model, specifically their `forward()` and `backward()` methods. +This happens when the model is wrapped with `DistributedDataParallel`: +```python +import torch.nn as nn +from torch.nn.parallel import DistributedDataParallel + +model = nn.Linear(10, 10) +ddp_model = DistributedDataParallel(model) +``` +In 🤗 Accelerate this conversion happens automatically when calling [`~Accelerator.prepare`] and passing in your model. + +```diff ++ from accelerate import Accelerator ++ accelerator = Accelerator() + import torch.nn as nn +- from torch.nn.parallel import DistributedDataParallel + + model = nn.Linear(10,10) ++ model = accelerator.prepare(model) +``` + +## The slowdown in gradient accumulation + +You now understand that PyTorch adds hooks to the `forward` and `backward` method of your PyTorch model when +training in a distributed setup. But how does this risk slowing down your code? + +In DDP (distributed data parallel), the specific order in which processes are performed and ran are expected +at specific points and these must also occur at roughly the same time before moving on. + +The most direct example is when you update model parameters through +`optimizer.step()`. +Without gradient accumulation, all instances of the model need to have updated +their gradients computed, collated, and updated before moving on to the next +batch of data. +When performing gradient accumulation, you accumulate `n` loss gradients and +skip `optimizer.step()` until `n` batches have been reached. As all training +processes only need to synchronize by the time `optimizer.step()` is called, +without any modification to your training step, this needless inter-process +communication can cause a significant slowdown. + + How can you avoid this overhead? + +## Solving the slowdown problem + +Since you are skipping model parameter updates when training on these batches, their gradients do not need to be synchronized until the point where `optimizer.step()` is actually called. +PyTorch cannot automagically tell when you need to do this, but they do provide a tool to help through the [`no_sync`](https://pytorch.org/docs/stable/generated/torch.nn.parallel.DistributedDataParallel.html#torch.nn.parallel.DistributedDataParallel.no_sync) context manager +that is added to your model after converting it to DDP. + +Under this context manager, PyTorch will skip synchronizing the gradients when +`.backward()` is called, and the first call to `.backward()` outside this +context manager will trigger the synchronization. See an example below: +```python +ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer) + +for index, batch in enumerate(dataloader): + inputs, targets = batch + # Trigger gradient synchronization on the last batch + if index != (len(dataloader) - 1): + with ddp_model.no_sync(): + # Gradients only accumulate + outputs = ddp_model(inputs) + loss = loss_func(outputs) + accelerator.backward(loss) + else: + # Gradients finally sync + outputs = ddp_model(inputs) + loss = loss_func(outputs) + accelerator.backward(loss) + optimizer.step() +``` + +In 🤗 Accelerate to make this an API that can be called no matter the training device (though it may not do anything if you are not in a distributed system!), +`ddp_model.no_sync` gets replaced with [`~Accelerator.no_sync`] and operates the same way: + +```diff + ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer) + + for index, batch in enumerate(dataloader): + inputs, targets = batch + # Trigger gradient synchronization on the last batch + if index != (len(dataloader)-1): +- with ddp_model.no_sync(): ++ with accelerator.no_sync(model): + # Gradients only accumulate + outputs = ddp_model(inputs) + loss = loss_func(outputs, targets) + accelerator.backward(loss) + else: + # Gradients finally sync + outputs = ddp_model(inputs) + loss = loss_func(outputs) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + +As you may expect, the [`~Accelerator.accumulate`] function wraps around this conditional check by keeping track of the current batch number, leaving you with the final +gradient accumulation API: + +```python +ddp_model, dataloader, optimizer = accelerator.prepare(model, dataloader, optimizer) + +for batch in dataloader: + with accelerator.accumulate(model): + optimizer.zero_grad() + inputs, targets = batch + outputs = model(inputs) + loss = loss_function(outputs, targets) + accelerator.backward(loss) + optimizer.step() + optimizer.zero_grad() +``` + +As a result, you should either use *`accelerator.accumulate` or `accelerator.no_sync`* when it comes to API choice. + +## Just how much of a slowdown is there, and easy mistakes you can make + +To set up a realistic example, consider the following setup: + +* Two single-GPU T4 nodes and one node with two GPUs +* Each GPU is a T4, and are hosted on GCP +* The script used is a modification of the [NLP Example](https://github.com/muellerzr/timing_experiments/blob/main/baseline.py) script +* Batch size per GPU is 16, and gradients are accumulated every 4 steps + +All scripts are available in [this repository](https://github.com/muellerzr/timing_experiments). + +If not careful about gradient synchronization and GPU communication, a *large* amount of time can be wasted +from when these GPUs communicate to each other during unnecessary periods. + +By how much? + +Reference: +- Baseline: uses no synchronization practices discussed here +- `no_sync` improperly: `no_sync` only around the `backward` call, not the `forward` +- `no_sync`: using the `no_sync` pattern properly +- `accumulate`: using [`~Accelerator.accumulate`] properly + +Below are the average seconds per batch iterating over 29 batches of data for each setup on both a single node and on the dual-node setup: + +| | Baseline | `no_sync` improperly | `no_sync` | `accumulate`| +| :---------: | :-------: | :------------------: | :-------: | :---------: | +| Multi-Node | 2±0.01s | 2.13±0.08s | **0.91±0.11s** | **0.91±0.11s** | +| Single Node | 0.50±0.01s | 0.50±0.01s | **0.41±0.015s** | **0.41±0.015s** | + +As you can see, if you are not careful about how you set up your gradient synchronization, you can get upwards of more than a 2x slowdown during training! + +If you are worried about making sure everything is done properly, we highly recommend utilizing the [`~Accelerator.accumulate`] function and passing in +`gradient_accumulation_steps` or `gradient_accumulation_plugin` to the [`Accelerator`] object so Accelerate can handle this for you. + +### `no_sync` requires additional GPU memory when using FSDP + +Be aware that not syncing gradients can have adverse effects while performing FSDP training. As it has been warned in `torch`, the [`no_sync` context manager for FSDP](https://pytorch.org/docs/stable/fsdp.html#torch.distributed.fsdp.FullyShardedDataParallel.no_sync) will require additional memory. + +Therefore in memory intensive situations while using FSDP, we recommend to set `sync_each_batch` to `True` in the [`~utils.GradientAccumulationPlugin`] to disable `no_sync`. + +See the example below where we fine-tune Mixtral (47B parameters) on 8 A100-80GB GPUs. We see that even for a modest `gradient_accumulation_steps=2` we quickly go out-of-memory (OOM) if `no_sync` is enabled. Again, this is due to additional memory overheads due to FSDP's `no_sync`. However, if `no_sync` is disabled via `sync_each_batch=True`, then the memory consumption for `gradient_accumulation_steps=16` reverts to that of `gradient_accumulation_steps=1`. + +| Model | `no_sync` (accum=1) | `no_sync` (accum=2) | `no_sync` disabled (accum=16) +| :-------------: | :-----------------: | :-----------------: | :-----------------: +mixtral 8x7B | 69G | OOM | 69G + +> [!WARNING] +> Disabling `no_sync` means there _will be slowdown_ due the extra data syncs, as explained by the earlier sections of this guide. \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/internal_mechanism.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/internal_mechanism.md new file mode 100644 index 0000000000000000000000000000000000000000..2410d882bb52acc4371b01af7ec588d1d4c92d37 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/internal_mechanism.md @@ -0,0 +1,78 @@ + + +# 🤗 Accelerate's internal mechanisms + +Internally, 🤗 Accelerate works by first analyzing the environment in which the script is launched to determine which +kind of distributed setup is used, how many different processes there are and which one the current script is in. All +that information is stored in the [`~AcceleratorState`]. + +This class is initialized the first time you instantiate an [`~Accelerator`] as well as performing any +specific initialization your distributed setup needs. Its state is then uniquely shared through all instances of +[`~state.AcceleratorState`]. (The same can also be done with the [`PartialState`], a more barebones version it inherits) + +Then, when calling [`~Accelerator.prepare`], the library: + +- wraps your model(s) in the container adapted for the distributed setup, +- wraps your optimizer(s) in an [`~optimizer.AcceleratedOptimizer`], +- wraps your scheduler(s) in an [`~scheduler.AcceleratedScheduler`] +- creates a new version of your dataloader(s) in a [`~data_loader.DataLoaderShard`] or [`~data_loader.DataLoaderDispatcher`] + +While the model(s), optimizer(s), and scheduler(s) are just put in simple wrappers, the dataloader(s) are re-created. This is mostly +because PyTorch does not let the user change the `batch_sampler` of a dataloader once it's been created and the +library handles the sharding of your data between processes by changing that `batch_sampler` to yield every other +`num_processes` batches (if enabled). + +The [`~data_loader.DataLoaderShard`] subclasses `DataLoader` to add the following functionality: + +- it synchronizes the appropriate random number generator of all processes at each new iteration, to ensure any + randomization (like shuffling) is done the exact same way across processes. +- it puts the batches on the proper device before yielding them (unless you have opted out of + `device_placement=True`). + +The [`~data_loader.DataLoaderDispatcher`] subclasses differs from the [`~data_loader.DataLoaderShard`] in that when iterating through the `DataLoader`, the data is all starting from process 0 and *then* split and sent off to each process rather than it happening at the dataset level. + +The random number generator synchronization will by default synchronize: + +- the `generator` attribute of a given sampler (like the PyTorch `RandomSampler`) for PyTorch >= 1.6 +- the main random number generator in PyTorch <=1.5.1 + +You can choose which random number generator(s) to synchronize with the `rng_types` argument of the main +[`Accelerator`]. In PyTorch >= 1.6, it is recommended to rely on a local `generator` to avoid +setting the same seed in the main random number generator in all processes. + + + + Synchronization of the main torch (or CUDA or XLA) random number generator will affect any other potential random + artifacts you could have in your dataset (like random data augmentation) in the sense that all processes will get + the same random numbers from the torch random modules (so will apply the same random data augmentation if it's + controlled by torch). + + + + + + The randomization part of your custom sampler, batch sampler or iterable dataset should be done using a local + `torch.Generator` object (in PyTorch >= 1.6), see the traditional `RandomSampler`, as an example. + + + + + +If you have [`torchdata>=0.8.0`](https://github.com/pytorch/data/tree/main) installed, and you have passed `use_stateful_dataloader=True` into your [`~utils.DataLoaderConfiguration`], these classes will directly inherit from `StatefulDataLoader` instead, and maintain a `state_dict`. + + + +For more details about the internals, see the [Internals page](package_reference/torch_wrappers). diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/low_precision_training.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/low_precision_training.md new file mode 100644 index 0000000000000000000000000000000000000000..2d8df0ca4e747b8d7cc42c04284b3d6a5ca2bf8d --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/low_precision_training.md @@ -0,0 +1,74 @@ + + +# Low Precision Training Methods + +The release of new kinds of hardware led to the emergence of new training paradigms that better utilize them. Currently, this is in the form of training +in 8-bit precision using packages such as [TransformersEngine](https://github.com/NVIDIA/TransformerEngine) (TE) or [MS-AMP](https://github.com/Azure/MS-AMP/tree/main). + +For an introduction to the topics discussed today, we recommend reviewing the [low-precision usage guide](../usage_guides/low_precision_training) as this documentation will reference it regularly. + +## A Quick Chart + +Below is a quick chart from the MS-AMP documentation showing the different bit-precisions for each solution during training: + +Optimization Level | Computation(GEMM) | Comm | Weight | Master Weight | Weight Gradient | Optimizer States +-- | -- | -- | -- | -- | -- | -- +FP16 AMP | FP16 | FP32 | FP32 | N/A | FP32 | FP32+FP32 +Nvidia TE | FP8 | FP32 | FP32 | N/A | FP32 | FP32+FP32 +MS-AMP O1 | FP8 | FP8 | FP16 | N/A | FP8 | FP32+FP32 +MS-AMP O2 | FP8 | FP8 | FP16 | N/A | FP8 | FP8+FP16 +MS-AMP O3 | FP8 | FP8 | FP8 | FP16 | FP8 | FP8+FP16 + +## `TransformersEngine` + +`TransformersEngine` is the first solution to trying to train in 8-bit floating point. It works by using drop-in replacement layers for certain ones in a model that utilizes their FP8-engine to reduce the number of bits (such as 32 to 8) without degrading the final accuracy of the model. + +Specifically, 🤗 Accelerate will find and replace the following layers with `TransformersEngine` versions: + +* `nn.LayerNorm` for `te.LayerNorm` +* `nn.Linear` for `te.Linear` + +As a result we wind up with a model that has most of its layers in BF16, while some layers are in FP8 reducing some of the memory. + +Anecdotally, we have noticed that performance gains don't really start showing when using `TransformerEngine` until a large majority of the layers +in the model are made up of those two layers to replace. As a result, only larger models have shown performance improvements when the number of parameters is around and upwards of a few billion. + +The `TransformerEngine` can receive many different arguments that customize how it performs FP8 calculations and what they do. A full list of the arguments is available below: + +* `margin`: The margin to use for the gradient scaling. +* `interval`: The interval to use for how often the scaling factor is recomputed. +* `fp8_format``: The format to use for the FP8 recipe. Must be one of `HYBRID` or `E4M3`. (Generally `HYBRID` for training, `E4M3` for evaluation) +* `amax_history_len`: The length of the history to use for the scaling factor computation +* `amax_compute_algo`: The algorithm to use for the scaling factor computation. Must be one of `max` or `most_recent`. +* `override_linear_precision`: Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. + +You can customize each of these as part of [`utils.FP8RecipeKwargs`] to help optimize performance of your models. + +If we notice in the chart mentioned earlier, TE simply casts the computation layers into FP8, while everything else is in FP32. As a result this winds up utilizing the most memory but does so with the benefit of guaranteeing the least amount of loss in end accuracy during training. + +## `MS-AMP` + +MS-AMP takes a different approach to `TransformersEngine` by providing three different optimization levels to convert more operations in FP8 or FP16. + +* The base optimization level (`O1`), passes communications of the weights (such as in DDP) in FP8, stores the weights of the model in FP16, and leaves the optimizer states in FP32. The main benefit of this optimization level is that we can reduce the communication bandwidth by essentially half. Additionally, more GPU memory is saved due to 1/2 of everything being cast in FP8, and the weights being cast to FP16. Notably, both the optimizer states remain in FP32. + +* The second optimization level (`O2`) improves upon this by also reducing the precision of the optimizer states. One is in FP8 while the other is in FP16. Generally it's been shown that this will only provide a net-gain of no degraded end accuracy, increased training speed, and reduced memory as now every state is either in FP16 or FP8. + +* Finally, MS-AMP has a third optimization level (`O3`) which helps during DDP scenarios such as DeepSpeed. The weights of the model in memory are fully cast to FP8, and the master weights are now stored in FP16. This fully reduces memory by the highest factor as now not only is almost everything in FP8, only two states are left in FP16. Currently, only DeepSpeed versions up through 0.9.2 are supported, so this capability is not included in the 🤗 Accelerate integration + +## Combining the two + +More experiments need to be performed but it's been noted that combining both MS-AMP and TransformersEngine can lead to the highest throughput by relying on NVIDIA's optimized FP8 operators and utilizing how MS-AMP reduces the memory overhead. diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/performance.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/performance.md new file mode 100644 index 0000000000000000000000000000000000000000..8b11200536580b26c129ac2089b6ae5f37978cdd --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/performance.md @@ -0,0 +1,103 @@ + + +# Comparing performance between different device setups + +Evaluating and comparing the performance from different setups can be quite tricky if you don't know what to look for. +For example, you cannot run the same script with the same batch size across TPU, multi-GPU, and single-GPU with Accelerate +and expect your results to line up. + +But why? + +There are three reasons for this that this tutorial will cover: + +1. **Setting the right seeds** +2. **Observed Batch Sizes** +3. **Learning Rates** + +## Setting the Seed + +While this issue has not come up as much, make sure to use [`utils.set_seed`] to fully set the seed in all distributed cases so training will be reproducible: + +```python +from accelerate.utils import set_seed + +set_seed(42) +``` + +Why is this important? Under the hood this will set **5** different seed settings: + +```python + random.seed(seed) + np.random.seed(seed) + torch.manual_seed(seed) + torch.cuda.manual_seed_all(seed) + # ^^ safe to call this function even if cuda is not available + if is_torch_xla_available(): + xm.set_rng_state(seed) +``` + +The random state, numpy's state, torch, torch's cuda state, and if TPUs are available torch_xla's cuda state. + +## Observed Batch Sizes + +When training with Accelerate, the batch size passed to the dataloader is the **batch size per GPU**. What this entails is +a batch size of 64 on two GPUs is truly a batch size of 128. As a result, when testing on a single GPU this needs to be accounted for, +as well as similarly for TPUs. + +The below table can be used as a quick reference to try out different batch sizes: + + + +In this example, there are two GPUs for "Multi-GPU" and a TPU pod with 8 workers + + + +| Single GPU Batch Size | Multi-GPU Equivalent Batch Size | TPU Equivalent Batch Size | +|-----------------------|---------------------------------|---------------------------| +| 256 | 128 | 32 | +| 128 | 64 | 16 | +| 64 | 32 | 8 | +| 32 | 16 | 4 | + +## Learning Rates + +As noted in multiple sources[[1](https://aws.amazon.com/blogs/machine-learning/scalable-multi-node-deep-learning-training-using-gpus-in-the-aws-cloud/)][[2](https://docs.nvidia.com/clara/clara-train-sdk/pt/model.html#classification-models-multi-gpu-training)], the learning rate should be scaled *linearly* based on the number of devices present. The below +snippet shows doing so with Accelerate: + + + +Since users can have their own learning rate schedulers defined, we leave this up to the user to decide if they wish to scale their +learning rate or not. + + + +```python +learning_rate = 1e-3 +accelerator = Accelerator() +learning_rate *= accelerator.num_processes + +optimizer = AdamW(params=model.parameters(), lr=learning_rate) +``` + +You will also find that `accelerate` will step the learning rate based on the number of processes being trained on. This is because +of the observed batch size noted earlier. So in the case of 2 GPUs, the learning rate will be stepped twice as often as a single GPU +to account for the batch size being twice as large (if no changes to the batch size on the single GPU instance are made). + +## Gradient Accumulation and Mixed Precision + +When using gradient accumulation and mixed precision, due to how gradient averaging works (accumulation) and the precision loss (mixed precision), +some degradation in performance is expected. This will be explicitly seen when comparing the batch-wise loss between different compute +setups. However, the overall loss, metric, and general performance at the end of training should be _roughly_ the same. diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/training_tpu.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/training_tpu.md new file mode 100644 index 0000000000000000000000000000000000000000..45c10f0384fdfcc272a2103a314b2bfb61632a44 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/concept_guides/training_tpu.md @@ -0,0 +1,167 @@ + + +# Training on TPUs with 🤗 Accelerate + +Training on TPUs can be slightly different from training on multi-gpu, even with 🤗 Accelerate. This guide aims to show you +where you should be careful and why, as well as the best practices in general. + +## Training in a Notebook + +The main carepoint when training on TPUs comes from the [`notebook_launcher`]. As mentioned in the [notebook tutorial](../usage_guides/notebook), you need to +restructure your training code into a function that can get passed to the [`notebook_launcher`] function and be careful about not declaring any tensors on the GPU. + +While on a TPU that last part is not as important, a critical part to understand is that when you launch code from a notebook you do so through a process called **forking**. +When launching from the command-line, you perform **spawning**, where a python process is not currently running and you *spawn* a new process in. Since your Jupyter notebook is already +utilizing a python process, you need to *fork* a new process from it to launch your code. + +Where this becomes important is in regard to declaring your model. On forked TPU processes, it is recommended that you instantiate your model *once* and pass this into your +training function. This is different than training on GPUs where you create `n` models that have their gradients synced and back-propagated at certain moments. Instead, one +model instance is shared between all the nodes and it is passed back and forth. This is important especially when training on low-resource TPUs such as those provided in Kaggle kernels or +on Google Colaboratory. + +Below is an example of a training function passed to the [`notebook_launcher`] if training on CPUs or GPUs: + + + + This code snippet is based off the one from the `simple_nlp_example` notebook found [here](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb) with slight + modifications for the sake of simplicity + + + +```python +def training_function(): + # Initialize accelerator + accelerator = Accelerator() + model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2) + train_dataloader, eval_dataloader = create_dataloaders( + train_batch_size=hyperparameters["train_batch_size"], eval_batch_size=hyperparameters["eval_batch_size"] + ) + + # Instantiate optimizer + optimizer = AdamW(params=model.parameters(), lr=hyperparameters["learning_rate"]) + + # Prepare everything + # There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the + # prepare method. + model, optimizer, train_dataloader, eval_dataloader = accelerator.prepare( + model, optimizer, train_dataloader, eval_dataloader + ) + + num_epochs = hyperparameters["num_epochs"] + # Now we train the model + for epoch in range(num_epochs): + model.train() + for step, batch in enumerate(train_dataloader): + outputs = model(**batch) + loss = outputs.loss + accelerator.backward(loss) + + optimizer.step() + optimizer.zero_grad() +``` + +```python +from accelerate import notebook_launcher + +notebook_launcher(training_function) +``` + + + + The `notebook_launcher` will default to 8 processes if 🤗 Accelerate has been configured for a TPU + + + +If you use this example and declare the model *inside* the training loop, then on a low-resource system you will potentially see an error +like: + +``` +ProcessExitedException: process 0 terminated with signal SIGSEGV +``` + +This error is *extremely* cryptic but the basic explanation is you ran out of system RAM. You can avoid this entirely by reconfiguring the training function to +accept a single `model` argument, and declare it in an outside cell: + +```python +# In another Jupyter cell +model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2) +``` + +```diff ++ def training_function(model): + # Initialize accelerator + accelerator = Accelerator() +- model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", num_labels=2) + train_dataloader, eval_dataloader = create_dataloaders( + train_batch_size=hyperparameters["train_batch_size"], eval_batch_size=hyperparameters["eval_batch_size"] + ) + ... +``` + +And finally calling the training function with: + +```diff + from accelerate import notebook_launcher +- notebook_launcher(training_function) ++ notebook_launcher(training_function, (model,)) +``` + + + + The above workaround is only needed when launching a TPU instance from a Jupyter Notebook on a low-resource server such as Google Colaboratory or Kaggle. If + using a script or launching on a much beefier server declaring the model beforehand is not needed. + + + +## Mixed Precision and Global Variables + +As mentioned in the [mixed precision tutorial](../usage_guides/mixed_precision), 🤗 Accelerate supports fp16 and bf16, both of which can be used on TPUs. +That being said, ideally `bf16` should be utilized as it is extremely efficient to use. + +There are two "layers" when using `bf16` and 🤗 Accelerate on TPUs, at the base level and at the operation level. + +At the base level, this is enabled when passing `mixed_precision="bf16"` to `Accelerator`, such as: +```python +accelerator = Accelerator(mixed_precision="bf16") +``` +By default, this will cast `torch.float` and `torch.double` to `bfloat16` on TPUs. +The specific configuration being set is an environmental variable of `XLA_USE_BF16` is set to `1`. + +There is a further configuration you can perform which is setting the `XLA_DOWNCAST_BF16` environmental variable. If set to `1`, then +`torch.float` is `bfloat16` and `torch.double` is `float32`. + +This is performed in the `Accelerator` object when passing `downcast_bf16=True`: +```python +accelerator = Accelerator(mixed_precision="bf16", downcast_bf16=True) +``` + +Using downcasting instead of bf16 everywhere is good for when you are trying to calculate metrics, log values, and more where raw bf16 tensors would be unusable. + +## Training Times on TPUs + +As you launch your script, you may notice that training seems exceptionally slow at first. This is because TPUs +first run through a few batches of data to see how much memory to allocate before finally utilizing this configured +memory allocation extremely efficiently. + +If you notice that your evaluation code to calculate the metrics of your model takes longer due to a larger batch size being used, +it is recommended to keep the batch size the same as the training data if it is too slow. Otherwise the memory will reallocate to this +new batch size after the first few iterations. + + + + Just because the memory is allocated does not mean it will be used or that the batch size will increase when going back to your training dataloader. + + diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/accelerate_logo.png b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/accelerate_logo.png new file mode 100644 index 0000000000000000000000000000000000000000..c8d2659132eb4b4b6c0e5438335477720e89198e --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/accelerate_logo.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:5ab00c5c1a233390ec3161c39b7c2d529043f1eddc7f66954392f614d5d7a81d +size 12653 diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/course_banner.png b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/course_banner.png new file mode 100644 index 0000000000000000000000000000000000000000..95093b20769aabaffc86b26e7d92ebf1022a41be --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/course_banner.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:809c043430c67617f0f1b1551f51cee564a4b3cce938d34b4eb478dc94a63280 +size 80305 diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/profile_export.png b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/profile_export.png new file mode 100644 index 0000000000000000000000000000000000000000..39fff39eaaf06a7daa2a5cba90b5c6d0b7aded5f --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/imgs/profile_export.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f96bb5d988aefa89b480c40f83a11b543c185804e7c15f9574f14ff45514ec2e +size 107863 diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/index.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/index.md new file mode 100644 index 0000000000000000000000000000000000000000..0c08d5f60b70f46d745188ea03badb75f5d2bb30 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/index.md @@ -0,0 +1,74 @@ + + +# Accelerate + +🤗 Accelerate is a library that enables the same PyTorch code to be run across any distributed configuration by adding just four lines of code! In short, training and inference at scale made simple, efficient and adaptable. + +```diff ++ from accelerate import Accelerator ++ accelerator = Accelerator() + ++ model, optimizer, training_dataloader, scheduler = accelerator.prepare( ++ model, optimizer, training_dataloader, scheduler ++ ) + + for batch in training_dataloader: + optimizer.zero_grad() + inputs, targets = batch + inputs = inputs.to(device) + targets = targets.to(device) + outputs = model(inputs) + loss = loss_function(outputs, targets) ++ accelerator.backward(loss) + optimizer.step() + scheduler.step() +``` + +Built on `torch_xla` and `torch.distributed`, 🤗 Accelerate takes care of the heavy lifting, so you don't have to write any custom code to adapt to these platforms. +Convert existing codebases to utilize [DeepSpeed](usage_guides/deepspeed), perform [fully sharded data parallelism](usage_guides/fsdp), and have automatic support for mixed-precision training! + + + + To get a better idea of this process, make sure to check out the [Tutorials](basic_tutorials/overview)! + + + + +This code can then be launched on any system through Accelerate's CLI interface: +```bash +accelerate launch {my_script.py} +``` + + diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/accelerator.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/accelerator.md new file mode 100644 index 0000000000000000000000000000000000000000..7d915a4ee60e5518f1f652f549476ed286e98e10 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/accelerator.md @@ -0,0 +1,26 @@ + + +# Accelerator + +The [`Accelerator`] is the main class for enabling distributed training on any type of training setup. Read the [Add Accelerator to your code](../basic_tutorials/migration) tutorial to learn more about how to add the [`Accelerator`] to your script. + +## Accelerator[[api]] + +[[autodoc]] Accelerator + +## Utilities + +[[autodoc]] accelerate.utils.gather_object diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/big_modeling.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/big_modeling.md new file mode 100644 index 0000000000000000000000000000000000000000..98383f702d99999aa3f2aa5493e4019802d3149b --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/big_modeling.md @@ -0,0 +1,47 @@ + + +# Working with large models + +## Dispatching and Offloading Models + +[[autodoc]] big_modeling.init_empty_weights +[[autodoc]] big_modeling.cpu_offload +[[autodoc]] big_modeling.cpu_offload_with_hook +[[autodoc]] big_modeling.disk_offload +[[autodoc]] big_modeling.dispatch_model +[[autodoc]] big_modeling.load_checkpoint_and_dispatch +[[autodoc]] big_modeling.load_checkpoint_in_model +[[autodoc]] utils.infer_auto_device_map + +## Model Hooks + +### Hook Classes + +[[autodoc]] hooks.ModelHook +[[autodoc]] hooks.AlignDevicesHook +[[autodoc]] hooks.SequentialHook + +### Adding Hooks + +[[autodoc]] hooks.add_hook_to_module +[[autodoc]] hooks.attach_execution_device_hook +[[autodoc]] hooks.attach_align_device_hook +[[autodoc]] hooks.attach_align_device_hook_on_blocks + +### Removing Hooks + +[[autodoc]] hooks.remove_hook_from_module +[[autodoc]] hooks.remove_hook_from_submodules \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/cli.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/cli.md new file mode 100644 index 0000000000000000000000000000000000000000..1f3ec85827b90bff1fe886265727c5d7e85b37ef --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/cli.md @@ -0,0 +1,335 @@ + + +# The Command Line + +Below is a list of all the available commands 🤗 Accelerate with their parameters + +## accelerate config + +**Command**: + +`accelerate config` or `accelerate-config` + +Launches a series of prompts to create and save a `default_config.yml` configuration file for your training system. Should +always be ran first on your machine. + +**Usage**: + +```bash +accelerate config [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. +* `-h`, `--help` (`bool`) -- Show a help message and exit + +## accelerate config default + +**Command**: + +`accelerate config default` or `accelerate-config default` + +Create a default config file for Accelerate with only a few flags set. + +**Usage**: + +```bash +accelerate config default [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. + +* `-h`, `--help` (`bool`) -- Show a help message and exit +* `--mixed_precision {no,fp16,bf16}` (`str`) -- Whether or not to use mixed precision training. Choose between FP16 and BF16 (bfloat16) training. BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later. + +## accelerate config update + +**Command**: + +`accelerate config update` or `accelerate-config update` + +Update an existing config file with the latest defaults while maintaining the old configuration. + +**Usage**: + +```bash +accelerate config update [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to the config file to update. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. + +* `-h`, `--help` (`bool`) -- Show a help message and exit + + +## accelerate env + +**Command**: + +`accelerate env` or `accelerate-env` or `python -m accelerate.commands.env` + +Lists the contents of the passed 🤗 Accelerate configuration file. Should always be used when opening an issue on the [GitHub repository](https://github.com/huggingface/accelerate). + +**Usage**: + +```bash +accelerate env [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. +* `-h`, `--help` (`bool`) -- Show a help message and exit + +## accelerate launch + +**Command**: + +`accelerate launch` or `accelerate-launch` or `python -m accelerate.commands.launch` + +Launches a specified script on a distributed system with the right parameters. + +**Usage**: + +```bash +accelerate launch [arguments] {training_script} --{training_script-argument-1} --{training_script-argument-2} ... +``` + +**Positional Arguments**: + +- `{training_script}` -- The full path to the script to be launched in parallel +- `--{training_script-argument-1}` -- Arguments of the training script + +**Optional Arguments**: + +* `-h`, `--help` (`bool`) -- Show a help message and exit +* `--config_file CONFIG_FILE` (`str`)-- The config file to use for the default values in the launching script. +* `-m`, `--module` (`bool`) -- Change each process to interpret the launch script as a Python module, executing with the same behavior as 'python -m'. +* `--no_python` (`bool`) -- Skip prepending the training script with 'python' - just execute it directly. Useful when the script is not a Python script. +* `--debug` (`bool`) -- Whether to print out the torch.distributed stack trace when something fails. +* `-q`, `--quiet` (`bool`) -- Silence subprocess errors from the launch stack trace to only show the relevant tracebacks. (Only applicable to DeepSpeed and single-process configurations). + + +The rest of these arguments are configured through `accelerate config` and are read in from the specified `--config_file` (or default configuration) for their +values. They can also be passed in manually. + +**Hardware Selection Arguments**: + +* `--cpu` (`bool`) -- Whether or not to force the training on the CPU. +* `--multi_gpu` (`bool`) -- Whether or not this should launch a distributed GPU training. +* `--tpu` (`bool`) -- Whether or not this should launch a TPU training. +* `--ipex` (`bool`) -- Whether or not this should launch an Intel Pytorch Extension (IPEX) training. + +**Resource Selection Arguments**: + +The following arguments are useful for fine-tuning how available hardware should be used + +* `--mixed_precision {no,fp16,bf16,fp8}` (`str`) -- Whether or not to use mixed precision training. Choose between FP16 and BF16 (bfloat16) training. BF16 training is only supported on Nvidia Ampere GPUs and PyTorch 1.10 or later. +* `--num_processes NUM_PROCESSES` (`int`) -- The total number of processes to be launched in parallel. +* `--num_machines NUM_MACHINES` (`int`) -- The total number of machines used in this training. +* `--num_cpu_threads_per_process NUM_CPU_THREADS_PER_PROCESS` (`int`) -- The number of CPU threads per process. Can be tuned for optimal performance. +* `--enable_cpu_affinity` (`bool`) -- Whether or not CPU affinity and balancing should be enabled. Currently only supported on NVIDIA hardware. + +**Training Paradigm Arguments**: + +The following arguments are useful for selecting which training paradigm to use. + +* `--use_deepspeed` (`bool`) -- Whether or not to use DeepSpeed for training. +* `--use_fsdp` (`bool`) -- Whether or not to use FullyShardedDataParallel for training. +* `--use_megatron_lm` (`bool`) -- Whether or not to use Megatron-LM for training. +* `--use_xpu` (`bool`) -- Whether to use IPEX plugin to speed up training on XPU specifically. + +**Distributed GPU Arguments**: + +The following arguments are only useful when `multi_gpu` is passed or multi-gpu training is configured through `accelerate config`: + +* `--gpu_ids` (`str`) -- What GPUs (by id) should be used for training on this machine as a comma-seperated list +* `--same_network` (`bool`) -- Whether all machines used for multinode training exist on the same local network. +* `--machine_rank` (`int`) -- The rank of the machine on which this script is launched. +* `--main_process_ip` (`str`) -- The IP address of the machine of rank 0. +* `--main_process_port` (`int`) -- The port to use to communicate with the machine of rank 0. +* `-t`, `--tee` (`str`) -- Tee std streams into a log file and also to console. +* `--log_dir` (`str`) -- Base directory to use for log files when using torchrun/torch.distributed.run as launcher. Use with --tee to redirect std streams info log files. +* `--role` (`str`) -- User-defined role for the workers. +* `--rdzv_backend` (`str`) -- The rendezvous method to use, such as 'static' (the default) or 'c10d' +* `--rdzv_conf` (`str`) -- Additional rendezvous configuration (=,=,...). +* `--max_restarts` (`int`) -- Maximum number of worker group restarts before failing. +* `--monitor_interval` (`int`) -- Interval, in seconds, to monitor the state of workers. + +**TPU Arguments**: + +The following arguments are only useful when `tpu` is passed or TPU training is configured through `accelerate config`: + +* `--tpu_cluster` (`bool`) -- Whether to use a GCP TPU pod for training. +* `--tpu_use_sudo` (`bool`) -- Whether to use `sudo` when running the TPU training script in each pod. +* `--vm` (`str`) -- List of single Compute VM instance names. If not provided we assume usage of instance groups. For TPU pods. +* `--env` (`str`) -- List of environment variables to set on the Compute VM instances. For TPU pods. +* `--main_training_function` (`str`) -- The name of the main function to be executed in your script (only for TPU training). +* `--downcast_bf16` (`bool`) -- Whether when using bf16 precision on TPUs if both float and double tensors are cast to bfloat16 or if double tensors remain as float32. + +**DeepSpeed Arguments**: + +The following arguments are only useful when `use_deepspeed` is passed or `deepspeed` is configured through `accelerate config`: + +* `--deepspeed_config_file` (`str`) -- DeepSpeed config file. +* `--zero_stage` (`int`) -- DeepSpeed's ZeRO optimization stage. +* `--offload_optimizer_device` (`str`) -- Decides where (none|cpu|nvme) to offload optimizer states. +* `--offload_param_device` (`str`) -- Decides where (none|cpu|nvme) to offload parameters. +* `--offload_optimizer_nvme_path` (`str`) -- Decides Nvme Path to offload optimizer states. +* `--gradient_accumulation_steps` (`int`) -- No of gradient_accumulation_steps used in your training script. +* `--gradient_clipping` (`float`) -- Gradient clipping value used in your training script. +* `--zero3_init_flag` (`str`) -- Decides Whether (true|false) to enable `deepspeed.zero.Init` for constructing massive models. Only applicable with DeepSpeed ZeRO Stage-3. +* `--zero3_save_16bit_model` (`str`) -- Decides Whether (true|false) to save 16-bit model weights when using ZeRO Stage-3. Only applicable with DeepSpeed ZeRO Stage-3. +* `--deepspeed_hostfile` (`str`) -- DeepSpeed hostfile for configuring multi-node compute resources. +* `--deepspeed_exclusion_filter` (`str`) -- DeepSpeed exclusion filter string when using mutli-node setup. +* `--deepspeed_inclusion_filter` (`str`) -- DeepSpeed inclusion filter string when using mutli-node setup. +* `--deepspeed_multinode_launcher` (`str`) -- DeepSpeed multi-node launcher to use. +* `--deepspeed_moe_layer_cls_names` (`str`) -- comma-separated list of transformer MoE layer class names (case-sensitive) to wrap, e.g, `MixtralSparseMoeBlock` `Qwen2MoeSparseMoeBlock`, `JetMoEAttention,JetMoEBlock` + +**Fully Sharded Data Parallelism Arguments**: + +The following arguments are only useful when `use_fsdp` is passed or Fully Sharded Data Parallelism is configured through `accelerate config`: + +* `--fsdp_offload_params` (`str`) -- Decides Whether (true|false) to offload parameters and gradients to CPU. +* `--fsdp_min_num_params` (`int`) -- FSDP's minimum number of parameters for Default Auto Wrapping. +* `--fsdp_sharding_strategy` (`int`) -- FSDP's Sharding Strategy. +* `--fsdp_auto_wrap_policy` (`str`) -- FSDP's auto wrap policy. +* `--fsdp_transformer_layer_cls_to_wrap` (`str`) -- Transformer layer class name (case-sensitive) to wrap, e.g, `BertLayer`, `GPTJBlock`, `T5Block` ... +* `--fsdp_backward_prefetch_policy` (`str`) -- FSDP's backward prefetch policy. +* `--fsdp_state_dict_type` (`str`) -- FSDP's state dict type. +* `--fsdp_forward_prefetch` (`str`) -- FSDP forward prefetch. +* `--fsdp_use_orig_params` (`str`) -- If True, allows non-uniform `requires_grad` mixed in a FSDP unit. +* `--fsdp_cpu_ram_efficient_loading` (`str`) -- If true, only the first process loads the pretrained model checkoint while all other processes have empty weights. When using this, `--fsdp_sync_module_states` needs to True. +* `--fsdp_sync_module_states` (`str`) -- If true, each individually wrapped FSDP unit will broadcast module parameters from rank 0. +* `--fsdp_activation_checkpointing` (`bool`) -- Decides Whether intermediate activations are freed during the forward pass, and a checkpoint is left as a placeholder + +**Megatron-LM Arguments**: + +The following arguments are only useful when `use_megatron_lm` is passed or Megatron-LM is configured through `accelerate config`: + +* `--megatron_lm_tp_degree` (``) -- Megatron-LM's Tensor Parallelism (TP) degree. +* `--megatron_lm_pp_degree` (``) -- Megatron-LM's Pipeline Parallelism (PP) degree. +* `--megatron_lm_num_micro_batches` (``) -- Megatron-LM's number of micro batches when PP degree > 1. +* `--megatron_lm_sequence_parallelism` (``) -- Decides Whether (true|false) to enable Sequence Parallelism when TP degree > 1. +* `--megatron_lm_recompute_activations` (``) -- Decides Whether (true|false) to enable Selective Activation Recomputation. +* `--megatron_lm_use_distributed_optimizer` (``) -- Decides Whether (true|false) to use distributed optimizer which shards optimizer state and gradients across Data Parallel (DP) ranks. +* `--megatron_lm_gradient_clipping` (``) -- Megatron-LM's gradient clipping value based on global L2 Norm (0 to disable). + +**FP8 Arguments**: + +* `--fp8_backend` (`str`) -- Choose a backend to train with FP8 (`te` or `msamp`) +* `--fp8_use_autocast_during_eval` (`bool`) -- Whether to use FP8 autocast during eval mode (useful only when `--fp8_backend=te` is passed). Generally better metrics are found when this is not passed. +* `--fp8_margin` (`int`) -- The margin to use for the gradient scaling (useful only when `--fp8_backend=te` is passed). +* `--fp8_interval` (`int`) -- The interval to use for how often the scaling factor is recomputed (useful only when `--fp8_backend=te` is passed). +* `--fp8_format` (`str`) -- The format to use for the FP8 recipe (useful only when `--fp8_backend=te` is passed). +* `--fp8_amax_history_len` (`int`) -- The length of the history to use for the scaling factor computation (useful only when `--fp8_backend=te` is passed). +* `--fp8_amax_compute_algo` (`str`) -- The algorithm to use for the scaling factor computation. (useful only when `--fp8_backend=te` is passed). +* `--fp8_override_linear_precision` (`Tuple[bool, bool, bool]`) -- Whether or not to execute `fprop`, `dgrad`, and `wgrad` GEMMS in higher precision. +* `--fp8_opt_level` (`str`) -- What level of 8-bit collective communication should be used with MS-AMP (useful only when `--fp8_backend=msamp` is passed) + +**AWS SageMaker Arguments**: + +The following arguments are only useful when training in SageMaker + +* `--aws_access_key_id AWS_ACCESS_KEY_ID` (`str`) -- The AWS_ACCESS_KEY_ID used to launch the Amazon SageMaker training job +* `--aws_secret_access_key AWS_SECRET_ACCESS_KEY` (`str`) -- The AWS_SECRET_ACCESS_KEY used to launch the Amazon SageMaker training job + +## accelerate estimate-memory + +**Command**: + +`accelerate estimate-memory` or `accelerate-estimate-memory` or `python -m accelerate.commands.estimate` + +Estimates the total vRAM a particular model hosted on the Hub needs to be loaded in with an estimate for training. Requires that `huggingface_hub` be installed. + + + + When performing inference, typically add ≤20% to the result as overall allocation [as referenced here](https://blog.eleuther.ai/transformer-math/). We will have more extensive estimations in the future that will automatically be included in the calculation. + + + +**Usage**: + +```bash +accelerate estimate-memory {MODEL_NAME} --library_name {LIBRARY_NAME} --dtypes {dtype_1} {dtype_2} ... +``` + +**Required Arguments**: + +* `MODEL_NAME` (`str`)-- The model name on the Hugging Face Hub + +**Optional Arguments**: + +* `--library_name {timm,transformers}` (`str`) -- The library the model has an integration with, such as `transformers`, needed only if this information is not stored on the Hub +* `--dtypes {float32,float16,int8,int4}` (`[{float32,float16,int8,int4} ...]`) -- The dtypes to use for the model, must be one (or many) of `float32`, `float16`, `int8`, and `int4` +* `--trust_remote_code` (`bool`) -- Whether or not to allow for custom models defined on the Hub in their own modeling files. This option should only be passed for repositories you trust and in which you have read the code, as it will execute code present on the Hub on your local machine. + +## accelerate tpu-config + +`accelerate tpu-config` + +**Usage**: + +```bash +accelerate tpu-config [arguments] +``` + +**Optional Arguments**: +* `-h`, `--help` (`bool`) -- Show a help message and exit + +**Config Arguments**: + +Arguments that can be configured through `accelerate config`. + +* `--config_file` (`str`) -- Path to the config file to use for accelerate. +* `--tpu_name` (`str`) -- The name of the TPU to use. If not specified, will use the TPU specified in the config file. +* `--tpu_zone` (`str`) -- The zone of the TPU to use. If not specified, will use the zone specified in the config file. + +**TPU Arguments**: + +Arguments for options ran inside the TPU. + +* `--command_file` (`str`) -- The path to the file containing the commands to run on the pod on startup. +* `--command` (`str`) -- A command to run on the pod. Can be passed multiple times. +* `--install_accelerate` (`bool`) -- Whether to install accelerate on the pod. Defaults to False. +* `--accelerate_version` (`str`) -- The version of accelerate to install on the pod. If not specified, will use the latest pypi version. Specify 'dev' to install from GitHub. +* `--debug` (`bool`) -- If set, will print the command that would be run instead of running it. + +## accelerate test + +`accelerate test` or `accelerate-test` + +Runs `accelerate/test_utils/test_script.py` to verify that 🤗 Accelerate has been properly configured on your system and runs. + +**Usage**: + +```bash +accelerate test [arguments] +``` + +**Optional Arguments**: +* `--config_file CONFIG_FILE` (`str`) -- The path to use to store the config file. Will default to a file named default_config.yaml in the cache location, which is the content + of the environment `HF_HOME` suffixed with 'accelerate', or if you don't have such an environment variable, your cache directory + (`~/.cache` or the content of `XDG_CACHE_HOME`) suffixed with `huggingface`. +* `-h`, `--help` (`bool`) -- Show a help message and exit diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/deepspeed.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/deepspeed.md new file mode 100644 index 0000000000000000000000000000000000000000..9e247f1ac4065cd68847807118a3012ba72f94cb --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/deepspeed.md @@ -0,0 +1,28 @@ + + +# Utilities for DeepSpeed + +[[autodoc]] utils.DeepSpeedPlugin + +[[autodoc]] utils.deepspeed.DummyOptim + +[[autodoc]] utils.deepspeed.DummyScheduler + +[[autodoc]] utils.deepspeed.DeepSpeedEngineWrapper + +[[autodoc]] utils.deepspeed.DeepSpeedOptimizerWrapper + +[[autodoc]] utils.deepspeed.DeepSpeedSchedulerWrapper diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/fp8.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/fp8.md new file mode 100644 index 0000000000000000000000000000000000000000..5b16e658cacdfcbb895f5dbfb389b438d5708863 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/fp8.md @@ -0,0 +1,28 @@ + + +# FP8 Functionality + +Below are functions and classes relative to the underlying FP8 implementation + +[[autodoc]] utils.FP8RecipeKwargs + +[[autodoc]] utils.convert_model + +[[autodoc]] utils.has_transformer_engine_layers + +[[autodoc]] utils.contextual_fp8_autocast + +[[autodoc]] utils.apply_fp8_autowrap diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/fsdp.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/fsdp.md new file mode 100644 index 0000000000000000000000000000000000000000..ca35ffc7735851385fc8f8aeaa7dd1e03154bed7 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/fsdp.md @@ -0,0 +1,24 @@ + + +# Utilities for Fully Sharded Data Parallelism + +[[autodoc]] utils.enable_fsdp_ram_efficient_loading + +[[autodoc]] utils.disable_fsdp_ram_efficient_loading + +[[autodoc]] utils.merge_fsdp_weights + +[[autodoc]] utils.FullyShardedDataParallelPlugin diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/inference.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/inference.md new file mode 100644 index 0000000000000000000000000000000000000000..4347f98441e03da1b0ba02efc720b8a1a8a19da4 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/inference.md @@ -0,0 +1,20 @@ + + +# The inference API + +These docs refer to the [PiPPy](https://github.com/PyTorch/PiPPy) integration. + +[[autodoc]] inference.prepare_pippy diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/kwargs.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/kwargs.md new file mode 100644 index 0000000000000000000000000000000000000000..a45b6793f6f406072b18c54d18570b9bf1708892 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/kwargs.md @@ -0,0 +1,47 @@ + + +# Kwargs Handlers + +The following objects can be passed to the main [`Accelerator`] to customize how some PyTorch objects +related to distributed training or mixed precision are created. + +## AutocastKwargs + +[[autodoc]] AutocastKwargs + +## DistributedDataParallelKwargs + +[[autodoc]] DistributedDataParallelKwargs + +## FP8RecipeKwargs + +[[autodoc]] utils.FP8RecipeKwargs + +## ProfileKwargs + +[[autodoc]] utils.ProfileKwargs + +## GradScalerKwargs + +[[autodoc]] GradScalerKwargs + +## InitProcessGroupKwargs + +[[autodoc]] InitProcessGroupKwargs + +## KwargsHandler + +[[autodoc]] utils.KwargsHandler diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/launchers.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/launchers.md new file mode 100644 index 0000000000000000000000000000000000000000..a0335c8cf8996edbf1b1e7b77aaaa4b5d32797c0 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/launchers.md @@ -0,0 +1,22 @@ + + +# Launchers + +Functions for launching training on distributed processes. + + +[[autodoc]] accelerate.notebook_launcher +[[autodoc]] accelerate.debug_launcher \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/logging.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/logging.md new file mode 100644 index 0000000000000000000000000000000000000000..588913016e10d0a55de9e33be613e080d31f4658 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/logging.md @@ -0,0 +1,21 @@ + + +# Logging with Accelerate + +Refer to the [Troubleshooting guide](../usage_guides/troubleshooting#logging) or to the example below to learn +how to use 🤗 Accelerate's logger. + +[[autodoc]] logging.get_logger \ No newline at end of file diff --git a/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/megatron_lm.md b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/megatron_lm.md new file mode 100644 index 0000000000000000000000000000000000000000..d1874fdab1120a994d0e903dbd5e22fb06915d48 --- /dev/null +++ b/tasks/tasksmith-5d12db5414d2/tests/source/docs/source/package_reference/megatron_lm.md @@ -0,0 +1,32 @@ + + +# Utilities for Megatron-LM + +[[autodoc]] utils.MegatronLMPlugin + +[[autodoc]] utils.MegatronLMDummyScheduler + +[[autodoc]] utils.MegatronLMDummyDataLoader + +[[autodoc]] utils.AbstractTrainStep + +[[autodoc]] utils.GPTTrainStep + +[[autodoc]] utils.BertTrainStep + +[[autodoc]] utils.T5TrainStep + +[[autodoc]] utils.avg_losses_across_data_parallel_group