code
stringlengths
66
870k
docstring
stringlengths
19
26.7k
func_name
stringlengths
1
138
language
stringclasses
1 value
repo
stringlengths
7
68
path
stringlengths
5
324
url
stringlengths
46
389
license
stringclasses
7 values
def test_token_dropping(self): r""" This test checks if the token dropping actually drops tokens. """ config = SwitchTransformersConfig(expert_capacity=0) # we drop everything moe = SwitchTransformersSparseMLP(config) dropped_token_results = moe(torch.randn(2, 3, 768))[0...
This test checks if the token dropping actually drops tokens.
test_token_dropping
python
huggingface/transformers
tests/models/switch_transformers/test_modeling_switch_transformers.py
https://github.com/huggingface/transformers/blob/master/tests/models/switch_transformers/test_modeling_switch_transformers.py
Apache-2.0
def test_small_integration_test(self): """ For comparison run: >>> import t5 # pip install t5==0.7.1 >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary >>> path_to_mtf_small_t5_checkpoint = '<fill_in>' >>> path_to_mtf_small_spm_model_path = '<fill_...
For comparison run: >>> import t5 # pip install t5==0.7.1 >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary >>> path_to_mtf_small_t5_checkpoint = '<fill_in>' >>> path_to_mtf_small_spm_model_path = '<fill_in>' >>> t5_model = t5.models.MtfModel(mod...
test_small_integration_test
python
huggingface/transformers
tests/models/t5/test_modeling_flax_t5.py
https://github.com/huggingface/transformers/blob/master/tests/models/t5/test_modeling_flax_t5.py
Apache-2.0
def test_small_v1_1_integration_test(self): """ For comparison run: >>> import t5 # pip install t5==0.7.1 >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary >>> path_to_mtf_small_t5_v1_1_checkpoint = '<fill_in>' >>> path_to_mtf_small_spm_model_path...
For comparison run: >>> import t5 # pip install t5==0.7.1 >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary >>> path_to_mtf_small_t5_v1_1_checkpoint = '<fill_in>' >>> path_to_mtf_small_spm_model_path = '<fill_in>' >>> t5_model = t5.models.MtfMode...
test_small_v1_1_integration_test
python
huggingface/transformers
tests/models/t5/test_modeling_flax_t5.py
https://github.com/huggingface/transformers/blob/master/tests/models/t5/test_modeling_flax_t5.py
Apache-2.0
def test_small_byt5_integration_test(self): """ For comparison run: >>> import t5 # pip install t5==0.9.1 >>> path_to_byt5_small_checkpoint = '<fill_in>' >>> t5_model = t5.models.MtfModel(model_dir=path_to_tf_checkpoint, batch_size=1, tpu=None) >>> vocab = t5.data.ByteV...
For comparison run: >>> import t5 # pip install t5==0.9.1 >>> path_to_byt5_small_checkpoint = '<fill_in>' >>> t5_model = t5.models.MtfModel(model_dir=path_to_tf_checkpoint, batch_size=1, tpu=None) >>> vocab = t5.data.ByteVocabulary() >>> score = t5_model.score(inputs=[...
test_small_byt5_integration_test
python
huggingface/transformers
tests/models/t5/test_modeling_flax_t5.py
https://github.com/huggingface/transformers/blob/master/tests/models/t5/test_modeling_flax_t5.py
Apache-2.0
def test_export_encoder(self): """Test exporting T5EncoderModel to torch export format.""" if not is_torch_greater_or_equal_than_2_4: self.skipTest("This test requires torch >= 2.4 to run.") from transformers.integrations.executorch import Seq2SeqLMEncoderExportableModule m...
Test exporting T5EncoderModel to torch export format.
test_export_encoder
python
huggingface/transformers
tests/models/t5/test_modeling_t5.py
https://github.com/huggingface/transformers/blob/master/tests/models/t5/test_modeling_t5.py
Apache-2.0
def test_export_decoder(self): """Test exporting T5 decoder with static cache to torch export format.""" if not is_torch_greater_or_equal_than_2_4: self.skipTest("This test requires torch >= 2.4 to run.") from transformers import AutoModelForSeq2SeqLM, T5ForConditionalGeneration ...
Test exporting T5 decoder with static cache to torch export format.
test_export_decoder
python
huggingface/transformers
tests/models/t5/test_modeling_t5.py
https://github.com/huggingface/transformers/blob/master/tests/models/t5/test_modeling_t5.py
Apache-2.0
def test_export_t5_summarization(self): """Test composing exported T5 encoder and decoder for summarization.""" if not is_torch_greater_or_equal_than_2_4: self.skipTest("This test requires torch >= 2.4 to run.") from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, T5ForCon...
Test composing exported T5 encoder and decoder for summarization.
test_export_t5_summarization
python
huggingface/transformers
tests/models/t5/test_modeling_t5.py
https://github.com/huggingface/transformers/blob/master/tests/models/t5/test_modeling_t5.py
Apache-2.0
def test_small_v1_1_integration_test(self): """ For comparison run: >>> import t5 # pip install t5==0.7.1 >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary >>> path_to_mtf_small_t5_v1.1_checkpoint = '<fill_in>' >>> path_to_mtf_small_spm_model_path...
For comparison run: >>> import t5 # pip install t5==0.7.1 >>> from t5.data.sentencepiece_vocabulary import SentencePieceVocabulary >>> path_to_mtf_small_t5_v1.1_checkpoint = '<fill_in>' >>> path_to_mtf_small_spm_model_path = '<fill_in>' >>> t5_model = t5.models.MtfMode...
test_small_v1_1_integration_test
python
huggingface/transformers
tests/models/t5/test_modeling_tf_t5.py
https://github.com/huggingface/transformers/blob/master/tests/models/t5/test_modeling_tf_t5.py
Apache-2.0
def get_expected_values(self, image_inputs, batched=False): """ This function computes the expected height and width when providing images to TvpImageProcessor, assuming do_resize is set to True with a scalar size. """ if not batched: return (int(self.pad_size["height...
This function computes the expected height and width when providing images to TvpImageProcessor, assuming do_resize is set to True with a scalar size.
get_expected_values
python
huggingface/transformers
tests/models/tvp/test_image_processing_tvp.py
https://github.com/huggingface/transformers/blob/master/tests/models/tvp/test_image_processing_tvp.py
Apache-2.0
def test_find_longest_common_subsequence_old(self): """Test using the old processing functions used in the ASR pipeline, but that serves as a BC reference.""" max_source_positions = 1500 processor = WhisperProcessor.from_pretrained("openai/whisper-tiny") previous_sequence = [[51492, 406...
Test using the old processing functions used in the ASR pipeline, but that serves as a BC reference.
test_find_longest_common_subsequence_old
python
huggingface/transformers
tests/models/whisper/test_processor_whisper.py
https://github.com/huggingface/transformers/blob/master/tests/models/whisper/test_processor_whisper.py
Apache-2.0
def _fast_find_longest_common_sequence(sequence_left, sequence_right): """Old processing function used in the ASR pipeline.""" seq_len_left = len(sequence_left) seq_len_right = len(sequence_right) counter = [[0] * (seq_len_right + 1) for _ in range(seq_len_left + 1)] longest = 0 for i in range(s...
Old processing function used in the ASR pipeline.
_fast_find_longest_common_sequence
python
huggingface/transformers
tests/models/whisper/test_processor_whisper.py
https://github.com/huggingface/transformers/blob/master/tests/models/whisper/test_processor_whisper.py
Apache-2.0
def _find_timestamp_sequence(sequences, tokenizer, feature_extractor, max_source_positions): """ Old processing function used in the ASR pipeline. Computes the final sequences by merging the end of the nth sequence with the beginning of the n+1th sequence. Since `WhisperForConditionalGeneration` produc...
Old processing function used in the ASR pipeline. Computes the final sequences by merging the end of the nth sequence with the beginning of the n+1th sequence. Since `WhisperForConditionalGeneration` produces the timestamps pairwise, we filter the consecutive timestamps and only iterate over them. We ...
_find_timestamp_sequence
python
huggingface/transformers
tests/models/whisper/test_processor_whisper.py
https://github.com/huggingface/transformers/blob/master/tests/models/whisper/test_processor_whisper.py
Apache-2.0
def test_create_position_ids_respects_padding_index(self): """This is a regression test for https://github.com/huggingface/transformers/issues/1761 The position ids should be masked with the embedding object's padding index. Therefore, the first available non-padding position index is XLMRobert...
This is a regression test for https://github.com/huggingface/transformers/issues/1761 The position ids should be masked with the embedding object's padding index. Therefore, the first available non-padding position index is XLMRobertaXLEmbeddings.padding_idx + 1
test_create_position_ids_respects_padding_index
python
huggingface/transformers
tests/models/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py
https://github.com/huggingface/transformers/blob/master/tests/models/xlm_roberta_xl/test_modeling_xlm_roberta_xl.py
Apache-2.0
def test_create_position_ids_respects_padding_index(self): """This is a regression test for https://github.com/huggingface/transformers/issues/1761 The position ids should be masked with the embedding object's padding index. Therefore, the first available non-padding position index is XmodEmbed...
This is a regression test for https://github.com/huggingface/transformers/issues/1761 The position ids should be masked with the embedding object's padding index. Therefore, the first available non-padding position index is XmodEmbeddings.padding_idx + 1
test_create_position_ids_respects_padding_index
python
huggingface/transformers
tests/models/xmod/test_modeling_xmod.py
https://github.com/huggingface/transformers/blob/master/tests/models/xmod/test_modeling_xmod.py
Apache-2.0
def test_attention_outputs(self): r""" Overriding the test_attention_outputs test as the Zamba model outputs attention only for its attention layers """ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True seq_len = get...
Overriding the test_attention_outputs test as the Zamba model outputs attention only for its attention layers
test_attention_outputs
python
huggingface/transformers
tests/models/zamba/test_modeling_zamba.py
https://github.com/huggingface/transformers/blob/master/tests/models/zamba/test_modeling_zamba.py
Apache-2.0
def test_left_padding_compatibility(self): r""" Overriding the test_left_padding_compatibility test as the mamba layers accentuate the numerical differences effect of the left padding discussed in the issue in the note. Using a more permissive tolerance value. """ import inspect ...
Overriding the test_left_padding_compatibility test as the mamba layers accentuate the numerical differences effect of the left padding discussed in the issue in the note. Using a more permissive tolerance value.
test_left_padding_compatibility
python
huggingface/transformers
tests/models/zamba/test_modeling_zamba.py
https://github.com/huggingface/transformers/blob/master/tests/models/zamba/test_modeling_zamba.py
Apache-2.0
def test_flash_attn_2_fp32_ln(self): r""" Overriding the test_flash_attn_2_fp32_ln test as the Zamba model, like Mixtral, doesn't support right padding + use cache with FA2 """ for model_class in self.all_generative_model_classes: config, inputs_dict = self.model_test...
Overriding the test_flash_attn_2_fp32_ln test as the Zamba model, like Mixtral, doesn't support right padding + use cache with FA2
test_flash_attn_2_fp32_ln
python
huggingface/transformers
tests/models/zamba/test_modeling_zamba.py
https://github.com/huggingface/transformers/blob/master/tests/models/zamba/test_modeling_zamba.py
Apache-2.0
def test_past_key_values_format(self): """ Overwriting to pass the expected cache shapes (Zamba2 has cache shape = [batch_size, 0] for mamba layers) """ config, inputs = self.model_tester.prepare_config_and_inputs_for_common() batch_size, seq_length = inputs["input_ids"].shape ...
Overwriting to pass the expected cache shapes (Zamba2 has cache shape = [batch_size, 0] for mamba layers)
test_past_key_values_format
python
huggingface/transformers
tests/models/zamba2/test_modeling_zamba2.py
https://github.com/huggingface/transformers/blob/master/tests/models/zamba2/test_modeling_zamba2.py
Apache-2.0
def test_attention_outputs(self): r""" Overriding the test_attention_outputs test as the Zamba2 model outputs attention only for its attention layers """ config, inputs_dict = self.model_tester.prepare_config_and_inputs_for_common() config.return_dict = True seq_len = ge...
Overriding the test_attention_outputs test as the Zamba2 model outputs attention only for its attention layers
test_attention_outputs
python
huggingface/transformers
tests/models/zamba2/test_modeling_zamba2.py
https://github.com/huggingface/transformers/blob/master/tests/models/zamba2/test_modeling_zamba2.py
Apache-2.0
def test_flash_attn_2_fp32_ln(self): r""" Overriding the test_flash_attn_2_fp32_ln test as the Zamba2 model, like Mixtral, doesn't support right padding + use cache with FA2 """ for model_class in self.all_generative_model_classes: config, inputs_dict = self.model_tes...
Overriding the test_flash_attn_2_fp32_ln test as the Zamba2 model, like Mixtral, doesn't support right padding + use cache with FA2
test_flash_attn_2_fp32_ln
python
huggingface/transformers
tests/models/zamba2/test_modeling_zamba2.py
https://github.com/huggingface/transformers/blob/master/tests/models/zamba2/test_modeling_zamba2.py
Apache-2.0
def test_flex_attention_with_grads(self): """ Overwriting as the base hidden size is big enough for compile. Manipulation of dims causes issues due to other constraints not being satisfied anymore. """ for model_class in self.all_model_classes: config, inputs_dict = s...
Overwriting as the base hidden size is big enough for compile. Manipulation of dims causes issues due to other constraints not being satisfied anymore.
test_flex_attention_with_grads
python
huggingface/transformers
tests/models/zamba2/test_modeling_zamba2.py
https://github.com/huggingface/transformers/blob/master/tests/models/zamba2/test_modeling_zamba2.py
Apache-2.0
def test_delete_adapter(self): """ Enhanced test for `delete_adapter` to handle multiple adapters, edge cases, and proper error handling. """ from peft import LoraConfig for model_id in self.transformers_test_model_ids: for transformers_class in self.transfor...
Enhanced test for `delete_adapter` to handle multiple adapters, edge cases, and proper error handling.
test_delete_adapter
python
huggingface/transformers
tests/peft_integration/test_peft_integration.py
https://github.com/huggingface/transformers/blob/master/tests/peft_integration/test_peft_integration.py
Apache-2.0
def test_peft_add_adapter_with_state_dict_low_cpu_mem_usage(self): """ Check the usage of low_cpu_mem_usage, which is supported in PEFT >= 0.13.0 """ from peft import LoraConfig min_version_lcmu = "0.13.0" is_lcmu_supported = version.parse(importlib.metadata.version("pef...
Check the usage of low_cpu_mem_usage, which is supported in PEFT >= 0.13.0
test_peft_add_adapter_with_state_dict_low_cpu_mem_usage
python
huggingface/transformers
tests/peft_integration/test_peft_integration.py
https://github.com/huggingface/transformers/blob/master/tests/peft_integration/test_peft_integration.py
Apache-2.0
def test_peft_from_pretrained_unexpected_keys_warning(self): """ Test for warning when loading a PEFT checkpoint with unexpected keys. """ from peft import LoraConfig logger = logging.get_logger("transformers.integrations.peft") for model_id, peft_model_id in zip(self.t...
Test for warning when loading a PEFT checkpoint with unexpected keys.
test_peft_from_pretrained_unexpected_keys_warning
python
huggingface/transformers
tests/peft_integration/test_peft_integration.py
https://github.com/huggingface/transformers/blob/master/tests/peft_integration/test_peft_integration.py
Apache-2.0
def test_peft_from_pretrained_missing_keys_warning(self): """ Test for warning when loading a PEFT checkpoint with missing keys. """ from peft import LoraConfig logger = logging.get_logger("transformers.integrations.peft") for model_id, peft_model_id in zip(self.transfo...
Test for warning when loading a PEFT checkpoint with missing keys.
test_peft_from_pretrained_missing_keys_warning
python
huggingface/transformers
tests/peft_integration/test_peft_integration.py
https://github.com/huggingface/transformers/blob/master/tests/peft_integration/test_peft_integration.py
Apache-2.0
def test_peft_load_adapter_training_inference_mode_true(self): """ By default, when loading an adapter, the whole model should be in eval mode and no parameter should have requires_grad=False. """ for model_id in self.peft_test_model_ids: for transformers_class in sel...
By default, when loading an adapter, the whole model should be in eval mode and no parameter should have requires_grad=False.
test_peft_load_adapter_training_inference_mode_true
python
huggingface/transformers
tests/peft_integration/test_peft_integration.py
https://github.com/huggingface/transformers/blob/master/tests/peft_integration/test_peft_integration.py
Apache-2.0
def test_peft_load_adapter_training_inference_mode_false(self): """ When passing is_trainable=True, the LoRA modules should be in training mode and their parameters should have requires_grad=True. """ for model_id in self.peft_test_model_ids: for transformers_class in...
When passing is_trainable=True, the LoRA modules should be in training mode and their parameters should have requires_grad=True.
test_peft_load_adapter_training_inference_mode_false
python
huggingface/transformers
tests/peft_integration/test_peft_integration.py
https://github.com/huggingface/transformers/blob/master/tests/peft_integration/test_peft_integration.py
Apache-2.0
def test_peft_pipeline_no_warning(self): """ Test to verify that the warning message "The model 'PeftModel' is not supported for text-generation" does not appear when using PeftModel with text-generation pipeline. """ from peft import PeftModel from transformers import p...
Test to verify that the warning message "The model 'PeftModel' is not supported for text-generation" does not appear when using PeftModel with text-generation pipeline.
test_peft_pipeline_no_warning
python
huggingface/transformers
tests/peft_integration/test_peft_integration.py
https://github.com/huggingface/transformers/blob/master/tests/peft_integration/test_peft_integration.py
Apache-2.0
def test_input_parameter_passthrough(self): """Test that chunked vs non chunked versions of ASR pipelines returns the same structure for the same inputs.""" speech_recognizer = pipeline( task="automatic-speech-recognition", model="hf-internal-testing/tiny-random-wav2vec2", ...
Test that chunked vs non chunked versions of ASR pipelines returns the same structure for the same inputs.
test_input_parameter_passthrough
python
huggingface/transformers
tests/pipelines/test_pipelines_automatic_speech_recognition.py
https://github.com/huggingface/transformers/blob/master/tests/pipelines/test_pipelines_automatic_speech_recognition.py
Apache-2.0
def test_pipeline_assisted_generation(self): """Tests that we can run assisted generation in the pipeline""" model = "openai/whisper-tiny" pipe = pipeline("automatic-speech-recognition", model=model, assistant_model=model) # We can run the pipeline prompt = load_dataset("hf-inte...
Tests that we can run assisted generation in the pipeline
test_pipeline_assisted_generation
python
huggingface/transformers
tests/pipelines/test_pipelines_automatic_speech_recognition.py
https://github.com/huggingface/transformers/blob/master/tests/pipelines/test_pipelines_automatic_speech_recognition.py
Apache-2.0
def test_pipeline_with_task_parameters_no_side_effects(self): """ Regression test: certain pipeline flags, like `task`, modified the model configuration, causing unexpected side-effects """ # This checkpoint has task-specific parameters that will modify the behavior of the pipeli...
Regression test: certain pipeline flags, like `task`, modified the model configuration, causing unexpected side-effects
test_pipeline_with_task_parameters_no_side_effects
python
huggingface/transformers
tests/pipelines/test_pipelines_common.py
https://github.com/huggingface/transformers/blob/master/tests/pipelines/test_pipelines_common.py
Apache-2.0
def test_quantized_model_exllama(self): """ Simple test that checks if the quantized model is working properly with exllama backend """ input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) quantization_config = AwqConfig(version="exllama") qu...
Simple test that checks if the quantized model is working properly with exllama backend
test_quantized_model_exllama
python
huggingface/transformers
tests/quantization/autoawq/test_awq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoawq/test_awq.py
Apache-2.0
def test_raise_save_pretrained(self): """ Test that `save_pretrained` is effectively blocked for fused models """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.model_name, qu...
Test that `save_pretrained` is effectively blocked for fused models
test_raise_save_pretrained
python
huggingface/transformers
tests/quantization/autoawq/test_awq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoawq/test_awq.py
Apache-2.0
def test_fused_modules_to_not_convert(self): """ Test if fused + modules to_not_covnert work as expected """ model_id = "hf-internal-testing/Mixtral-tiny-AWQ" quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) model = AutoModelForCausalLM.from_pr...
Test if fused + modules to_not_covnert work as expected
test_fused_modules_to_not_convert
python
huggingface/transformers
tests/quantization/autoawq/test_awq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoawq/test_awq.py
Apache-2.0
def test_generation_fused(self): """ Test generation quality for fused models - single batch case """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.model_name, quantization_c...
Test generation quality for fused models - single batch case
test_generation_fused
python
huggingface/transformers
tests/quantization/autoawq/test_awq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoawq/test_awq.py
Apache-2.0
def test_generation_fused_batched(self): """ Test generation quality for fused models - multi batch case """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=128, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.model_name, quantiz...
Test generation quality for fused models - multi batch case
test_generation_fused_batched
python
huggingface/transformers
tests/quantization/autoawq/test_awq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoawq/test_awq.py
Apache-2.0
def test_generation_custom_model(self): """ Test generation quality for fused models using custom fused map. """ quantization_config = AwqConfig( bits=4, fuse_max_seq_len=512, modules_to_fuse={ "attention": ["q_proj", "k_proj", "v_proj"...
Test generation quality for fused models using custom fused map.
test_generation_custom_model
python
huggingface/transformers
tests/quantization/autoawq/test_awq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoawq/test_awq.py
Apache-2.0
def test_generation_mixtral_fused(self): """ Text generation test for Mixtral + AWQ + fused """ quantization_config = AwqConfig(bits=4, fuse_max_seq_len=1024, do_fuse=True) model = AutoModelForCausalLM.from_pretrained( self.mixtral_model_name, quantization...
Text generation test for Mixtral + AWQ + fused
test_generation_mixtral_fused
python
huggingface/transformers
tests/quantization/autoawq/test_awq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoawq/test_awq.py
Apache-2.0
def test_quantized_model_multi_accelerator(self): """ Simple test that checks if the quantized model is working properly with multiple accelerators """ input_ids = self.tokenizer(self.input_text, return_tensors="pt").to(torch_device) quantization_config = AutoRoundConfig(backend=...
Simple test that checks if the quantized model is working properly with multiple accelerators
test_quantized_model_multi_accelerator
python
huggingface/transformers
tests/quantization/autoround/test_auto_round.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoround/test_auto_round.py
Apache-2.0
def test_convert_from_gptq(self): """ Simple test that checks if auto-round work properly with gptq format """ model_name = "ybelkada/opt-125m-gptq-4bit" quantization_config = AutoRoundConfig() model = AutoModelForCausalLM.from_pretrained( model_name, device...
Simple test that checks if auto-round work properly with gptq format
test_convert_from_gptq
python
huggingface/transformers
tests/quantization/autoround/test_auto_round.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoround/test_auto_round.py
Apache-2.0
def test_convert_from_awq_cpu(self): """ Simple test that checks if auto-round work properly with awq format """ model_name = "casperhansen/opt-125m-awq" quantization_config = AutoRoundConfig() model = AutoModelForCausalLM.from_pretrained( model_name, device...
Simple test that checks if auto-round work properly with awq format
test_convert_from_awq_cpu
python
huggingface/transformers
tests/quantization/autoround/test_auto_round.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoround/test_auto_round.py
Apache-2.0
def test_mixed_bits(self): """ Simple test that checks if auto-round work properly with mixed bits """ model_name = "facebook/opt-125m" model = AutoModelForCausalLM.from_pretrained(model_name, torch_dtype="auto") tokenizer = AutoTokenizer.from_pretrained(model_name) ...
Simple test that checks if auto-round work properly with mixed bits
test_mixed_bits
python
huggingface/transformers
tests/quantization/autoround/test_auto_round.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/autoround/test_auto_round.py
Apache-2.0
def test_packing_unpacking(self): """ Simple test the packing and unpacking logic """ from transformers.integrations import pack_weights, unpack_weights u = torch.randint(0, 255, (256, 256), dtype=torch.uint8) unpacked_u = unpack_weights(u, dtype=torch.bfloat16) ...
Simple test the packing and unpacking logic
test_packing_unpacking
python
huggingface/transformers
tests/quantization/bitnet_integration/test_bitnet.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bitnet_integration/test_bitnet.py
Apache-2.0
def test_weights_dtype(self): """ test the weights dtype after loading """ self_attn_q = self.quantized_model.model.layers[0].self_attn.q_proj.weight self_attn_k = self.quantized_model.model.layers[0].self_attn.k_proj.weight self_attn_v = self.quantized_model.model.layer...
test the weights dtype after loading
test_weights_dtype
python
huggingface/transformers
tests/quantization/bitnet_integration/test_bitnet.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bitnet_integration/test_bitnet.py
Apache-2.0
def test_replace_with_bitlinear_shape(self): """ test that the BitNet layer weight shapes are correct, and the weight_scale is correctly initialized to 1 """ from transformers.integrations import replace_with_bitnet_linear out_features = 1024 in_features = 512 ...
test that the BitNet layer weight shapes are correct, and the weight_scale is correctly initialized to 1
test_replace_with_bitlinear_shape
python
huggingface/transformers
tests/quantization/bitnet_integration/test_bitnet.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bitnet_integration/test_bitnet.py
Apache-2.0
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_c...
Test that loading the model and unquantize it produce correct results
test_generate_quality_dequantize
python
huggingface/transformers
tests/quantization/bnb/test_4bit.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_4bit.py
Apache-2.0
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 inval...
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.
test_device_and_dtype_assignment
python
huggingface/transformers
tests/quantization/bnb/test_4bit.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_4bit.py
Apache-2.0
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....
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.
test_inference_without_keep_in_fp32
python
huggingface/transformers
tests/quantization/bnb/test_4bit.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_4bit.py
Apache-2.0
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. """ # s...
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.
test_pipeline
python
huggingface/transformers
tests/quantization/bnb/test_4bit.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_4bit.py
Apache-2.0
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...
Test that loading the model and dequantizing it produce correct results
test_generate_quality_dequantize
python
huggingface/transformers
tests/quantization/bnb/test_mixed_int8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_mixed_int8.py
Apache-2.0
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 inval...
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.
test_device_and_dtype_assignment
python
huggingface/transformers
tests/quantization/bnb/test_mixed_int8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_mixed_int8.py
Apache-2.0
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....
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.
test_inference_without_keep_in_fp32
python
huggingface/transformers
tests/quantization/bnb/test_mixed_int8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_mixed_int8.py
Apache-2.0
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...
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.
test_inference_with_keep_in_fp32_serialized
python
huggingface/transformers
tests/quantization/bnb/test_mixed_int8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_mixed_int8.py
Apache-2.0
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. """ # s...
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.
test_pipeline
python
huggingface/transformers
tests/quantization/bnb/test_mixed_int8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/bnb/test_mixed_int8.py
Apache-2.0
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): ...
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.
test_compressed_uncompressed_model_shapes
python
huggingface/transformers
tests/quantization/compressed_tensors_integration/test_compressed_models.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/compressed_tensors_integration/test_compressed_models.py
Apache-2.0
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_te...
Ensure that the generated outputs match between the uncompressed model and its decompressed compressed counterpart.
test_outputs_match
python
huggingface/transformers
tests/quantization/compressed_tensors_integration/test_compressed_models.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/compressed_tensors_integration/test_compressed_models.py
Apache-2.0
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 wa...
Confirm that loading any model using compressed tensors does not trigger warnings about missing or unexpected keys.
test_no_warnings_for_all_models
python
huggingface/transformers
tests/quantization/compressed_tensors_integration/test_compressed_models.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/compressed_tensors_integration/test_compressed_models.py
Apache-2.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=Fal...
Check that run_compressed=True/False output are the same
test_run_compressed_outputs_match
python
huggingface/transformers
tests/quantization/compressed_tensors_integration/test_compressed_models.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/compressed_tensors_integration/test_compressed_models.py
Apache-2.0
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) ...
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
test_quantized_model_multi_gpu
python
huggingface/transformers
tests/quantization/eetq_integration/test_eetq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/eetq_integration/test_eetq.py
Apache-2.0
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 mo...
Simple test that checks if the quantized model returns an error when loading with cpu/disk offloaded
test_quantized_model_offload
python
huggingface/transformers
tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
Apache-2.0
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...
Simple test that checks if the saved quantized model is working properly cpu/disk offload
test_save_pretrained_offload
python
huggingface/transformers
tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
Apache-2.0
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 =...
Test that FbgemmFp8Linear generates the correct shape when in_features != out_features.
test_linear_with_diff_feature_size_preserves_shape
python
huggingface/transformers
tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/fbgemm_fp8/test_fbgemm_fp8.py
Apache-2.0
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.weigh...
Simple test that checks if the weight and weight_scale_inv are working properly
test_weight_and_weight_scale_inv
python
huggingface/transformers
tests/quantization/finegrained_fp8/test_fp8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/finegrained_fp8/test_fp8.py
Apache-2.0
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)) quantize...
Simple test that checks if the block size is working properly
test_block_size
python
huggingface/transformers
tests/quantization/finegrained_fp8/test_fp8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/finegrained_fp8/test_fp8.py
Apache-2.0
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. """ inp...
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.
test_quantized_model_multi_accelerator
python
huggingface/transformers
tests/quantization/finegrained_fp8/test_fp8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/finegrained_fp8/test_fp8.py
Apache-2.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) ...
Test that FP8Linear generates the correct shape when in_features != out_features.
test_linear_with_diff_feature_size_preserves_shape
python
huggingface/transformers
tests/quantization/finegrained_fp8/test_fp8.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/finegrained_fp8/test_fp8.py
Apache-2.0
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_...
Test the ability to dequantize a model
test_dequantize
python
huggingface/transformers
tests/quantization/higgs/test_higgs.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/higgs/test_higgs.py
Apache-2.0
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" ...
Simple LLM model testing fp16 with multi-gpu
test_fp16_quantized_model_multipgpu
python
huggingface/transformers
tests/quantization/hqq/test_hqq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/hqq/test_hqq.py
Apache-2.0
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 ...
Simple LLM model testing fp16 with bias
test_fp16_quantized_model
python
huggingface/transformers
tests/quantization/hqq/test_hqq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/hqq/test_hqq.py
Apache-2.0
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, com...
Test saving and loading a quantized model with bias
test_save_and_load_quantized_model
python
huggingface/transformers
tests/quantization/hqq/test_hqq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/hqq/test_hqq.py
Apache-2.0
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 ) inp...
Simple HQQ LLM save/load test
test_model_serialization
python
huggingface/transformers
tests/quantization/hqq/test_hqq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/hqq/test_hqq.py
Apache-2.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={ ...
Simple HQQ LLM save/load test with dynamic quant
test_model_serialization_dynamic_quant_with_skip
python
huggingface/transformers
tests/quantization/hqq/test_hqq.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/hqq/test_hqq.py
Apache-2.0
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) ...
Simple test that checks if the quantized model has been converted properly when using weight only quantization
test_weight_only_quantization_conversion
python
huggingface/transformers
tests/quantization/quanto_integration/test_quanto.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/quanto_integration/test_quanto.py
Apache-2.0
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="in...
Simple test that checks if the quantized model has been converted properly when using weight + activation quantization
test_weight_and_activation_quantization_conversion
python
huggingface/transformers
tests/quantization/quanto_integration/test_quanto.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/quanto_integration/test_quanto.py
Apache-2.0
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...
Simple test that checks if the quantized model has been converted properly when specifying modules_to_not_convert argument
test_conversion_with_modules_to_not_convert
python
huggingface/transformers
tests/quantization/quanto_integration/test_quanto.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/quanto_integration/test_quanto.py
Apache-2.0
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,...
Test the serialization, the loading and the inference of the quantized weights
test_serialization_bin
python
huggingface/transformers
tests/quantization/quanto_integration/test_quanto.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/quanto_integration/test_quanto.py
Apache-2.0
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[ ...
We check that we have unquantized value in the cpu and in the disk
test_check_offload_quantized
python
huggingface/transformers
tests/quantization/quanto_integration/test_quanto.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/quanto_integration/test_quanto.py
Apache-2.0
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: _ = se...
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 .
test_device_and_dtype_assignment
python
huggingface/transformers
tests/quantization/quark_integration/test_quark.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/quark_integration/test_quark.py
Apache-2.0
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...
Check that the config dict can be JSON serialized.
test_json_serializable
python
huggingface/transformers
tests/quantization/torchao_integration/test_torchao.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/torchao_integration/test_torchao.py
Apache-2.0
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_...
Simple LLM model testing int4 weight only quantization
test_int4wo_quant
python
huggingface/transformers
tests/quantization/torchao_integration/test_torchao.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/torchao_integration/test_torchao.py
Apache-2.0
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...
Testing the dtype of model will be modified to be bfloat16 for int4 weight only quantization
test_int4wo_quant_bfloat16_conversion
python
huggingface/transformers
tests/quantization/torchao_integration/test_torchao.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/torchao_integration/test_torchao.py
Apache-2.0
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, "mod...
Simple test that checks if the quantized model int4 weight only is working properly with cpu/disk offload
test_int4wo_offload
python
huggingface/transformers
tests/quantization/torchao_integration/test_torchao.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/torchao_integration/test_torchao.py
Apache-2.0
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 ...
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
test_int4wo_quant_multi_accelerator
python
huggingface/transformers
tests/quantization/torchao_integration/test_torchao.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/torchao_integration/test_torchao.py
Apache-2.0
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 tmp...
Test if we can serialize and load/infer the model again on the same device
check_serialization_expected_output
python
huggingface/transformers
tests/quantization/torchao_integration/test_torchao.py
https://github.com/huggingface/transformers/blob/master/tests/quantization/torchao_integration/test_torchao.py
Apache-2.0
def torchrun(self, script: str, is_torchrun: bool = True): """Run the `script` using `torchrun` command for multi-processing in a subprocess. Captures errors as necessary.""" with tempfile.NamedTemporaryFile(mode="w+", suffix=".py") as tmp: tmp.write(script) tmp.flush() ...
Run the `script` using `torchrun` command for multi-processing in a subprocess. Captures errors as necessary.
torchrun
python
huggingface/transformers
tests/tensor_parallel/test_tensor_parallel.py
https://github.com/huggingface/transformers/blob/master/tests/tensor_parallel/test_tensor_parallel.py
Apache-2.0
def test_probability_sum_error(self): """Test that the sum of mask_replace_prob and random_replace_prob exceeding 1 raises an error.""" tokenizer = BertTokenizer(self.vocab_file) with self.assertRaises(ValueError): DataCollatorForLanguageModeling(tokenizer=tokenizer, mask_replace_pro...
Test that the sum of mask_replace_prob and random_replace_prob exceeding 1 raises an error.
test_probability_sum_error
python
huggingface/transformers
tests/trainer/test_data_collator.py
https://github.com/huggingface/transformers/blob/master/tests/trainer/test_data_collator.py
Apache-2.0
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...
Test that load_backbone correctly loads a backbone from a backbone config.
test_load_backbone_from_config
python
huggingface/transformers
tests/utils/test_backbone_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_backbone_utils.py
Apache-2.0
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_indic...
Test that load_backbone correctly loads a backbone from a checkpoint.
test_load_backbone_from_checkpoint
python
huggingface/transformers
tests/utils/test_backbone_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_backbone_utils.py
Apache-2.0
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_backbon...
Test that load_backbone correctly configures the loaded backbone with the provided kwargs.
test_load_backbone_backbone_kwargs
python
huggingface/transformers
tests/utils/test_backbone_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_backbone_utils.py
Apache-2.0
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): ...
Tests that new model can be created, with its weights instantiated and pretrained backbone weights loaded.
test_load_backbone_in_new_model
python
huggingface/transformers
tests/utils/test_backbone_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_backbone_utils.py
Apache-2.0
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): ...
Tests that we can convert back and forth between the legacy cache format and DynamicCache
test_dynamic_cache_retrocompatibility
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
def test_reorder_cache_retrocompatibility(self): """Tests that Cache.reorder_cache is retrocompatible with the legacy code path""" legacy_reorder_fn = ClvpForCausalLM._reorder_cache # An example of a legacy `_reorder_cache` function legacy_cache = () new_cache = DynamicCache() ...
Tests that Cache.reorder_cache is retrocompatible with the legacy code path
test_reorder_cache_retrocompatibility
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
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_d...
Tests that static cache works with multi-head attention (MHA), grouped query attention (GQA), and multi-query attention (MQA)
test_static_cache_mha_mqa_gqa
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
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"...
Function to skip tests on failed cache prerequisites, given a cache implementation
_skip_on_failed_cache_prerequisites
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
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"] ...
Sanity check: caches' `.update` function expects batched inputs
test_cache_batched
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
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_implementa...
Sanity check: caches' `reorder_cache` is operational. We can confirm this by looking at the beam indices (an output sequence contains multiple beam indices).
test_cache_beam_search
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
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."] ...
Tests that adding extra left-padding does not affect the generation with the cache
test_cache_extra_left_padding
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
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="...
Hard test for base cache implementation -- minor numerical fluctuations will cause this test to fail
test_dynamic_cache_hard
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
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...
Tests that different cache implementations work well with eager and SDPA inference
test_static_cache_greedy_decoding_pad_left
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0
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_pretr...
Tests that OffloadedCache uses less memory than the default DynamicCache
test_offloaded_cache_uses_less_memory_than_dynamic_cache
python
huggingface/transformers
tests/utils/test_cache_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py
Apache-2.0