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_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)
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_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)}, )
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): 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)
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): 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]) )
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() # Creates a new cache with 10 layers in both formats for layer_idx in range(10): new_key = torch.rand((4, 4, 8, 16)) new_value = torch.rand((4, 4, 8, 16)) new_cache.update(new_key, new_value, layer_idx) legacy_cache += ((new_key, new_value),) # Let's create some dummy beam indices. From the shape above, it is equivalent to the case where num_beams=4 # and batch_size=1 beam_idx = torch.randint(low=0, high=4, size=(4,)) legacy_cache_reordered = legacy_reorder_fn(legacy_cache, beam_idx) new_cache.reorder_cache(beam_idx) # Let's check that the results are the same 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_reordered[layer_idx][key_value_idx] ) )
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_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_batch_size=1, max_cache_len=10, device=torch_device) 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_batch_size=1, max_cache_len=10, device=torch_device) 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_batch_size=1, max_cache_len=10, device=torch_device) 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))
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") # 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")
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"] 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)
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_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)
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."] 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)
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="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, 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 a body that is " "covered in fur. They are carnivores, so they eat meat. They are also very clean animals, they groom " "themselves. They have a lot of different breeds. Some are small, some are large. Some are friendly, " "some are not. They have a lot of different personalities. They can be very independent, or they can be " "very affectionate. They can be very playful, or they can be very lazy. They can be very intelligent, or " "they can be very silly. They have a lot of different behaviors. They can be very curious, or they can " "be very cautious. They can be very vocal, or they can be very quiet. They can be very social, or they " "can be very solitary. They can be very active, or they can be very inactive. They can be very " "affectionate, or they can be very aloof. They can be very playful, or they can be very lazy. They can " "be very intelligent, or they can be very silly. They have a lot of different behaviors. They can be " "very curious, or they can" ) EXPECTED_SCORE_SUM = 11017.4971 self.assertEqual(decoded[0], EXPECTED_GENERATION) self.assertAlmostEqual(score_sum, EXPECTED_SCORE_SUM, places=2) self.assertIsInstance(gen_out.past_key_values, DynamicCache) # sanity check
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 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
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_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)
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
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_batch_size=1, max_cache_len=1024, device=torch_device, dtype=torch.bfloat16 ) 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 an " "enriching experience that broadens our horizons and allows us to explore the world beyond our comfort " "zones. Whether it's a short weekend getaway", "You are a helpful assistant. What is the capital of France?\n\n\n## Response:Paris is the capital " "of France.\n\n\n\n\n\n\n<|endoftext|>", ] self.assertEqual(responses, EXPECTED_DECODED_TEXT)
Tests that we can manually set a cache, copy, and reuse it for generation
test_cache_copy
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_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] )
Tests that the dynamic cache works with nn.DataParallel. Under the hood, `DynamicCache` is rebuilt from multiple `DynamicCache` in the gather step.
test_data_parallel_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
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())
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?)
test_static_cache_no_cuda_graph_skips
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_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")
Regression test for #35164: static cache with multi-accelerator
test_static_cache_multi_accelerator
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_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)
Tests caches with GPT-J model. Regression test for https://github.com/huggingface/transformers/pull/34799
test_cache_gptj_model
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_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 = "cpu" 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.batch_size, batch_size) self.assertEqual(model.generation_config.cache_config.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 using Dim.AUTO tokenizer = AutoTokenizer.from_pretrained(model_id) input_ids = tokenizer("Here's everything I know", return_tensors="pt").input_ids dynamic_shapes = {"input_ids": {1: torch.export.Dim.AUTO}, "cache_position": None} exported_program = convert_and_export_with_cache( model, example_input_ids=input_ids, dynamic_shapes=dynamic_shapes, strict=False, )
Tests that static cache works with `torch.export()`
test_static_cache_exportability
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_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 exportable_module = TorchExportableModuleForDecoderOnlyLM(model, max_batch_size, max_cache_len) exported_program = exportable_module.export() 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 tokenizer = AutoTokenizer.from_pretrained(model_id) input_ids = tokenizer("Here's everything I know", return_tensors="pt").input_ids dynamic_shapes = {"input_ids": {1: torch.export.Dim.AUTO}, "cache_position": None} exported_program = exportable_module.export( input_ids=input_ids, dynamic_shapes=dynamic_shapes, strict=False, )
Tests that static cache works with `torch.export()`
test_hybrid_cache_exportability
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 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, sliding_window_pattern=2, # Default pattern for hybrid sliding )
Set up common configuration and cache instances for all tests.
setUp
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_out_of_bounds(self): """Test StaticCache raises IndexError for out-of-bounds positions.""" static_cache = StaticCache(config=self.config, max_batch_size=1, 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}, )
Test StaticCache raises IndexError for out-of-bounds positions.
test_static_cache_out_of_bounds
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(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_batch_size=1, 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.key_cache[0][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.key_cache[0][0, 0, :, 0].tolist(), [1.0, 2.0, 3.0, 4.0], "StaticCache Scenario 2 failed" )
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]
test_static_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
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 sliding_cache = SlidingWindowCache(config=self.config, max_batch_size=1, max_cache_len=self.max_cache_len) prefill = torch.tensor([1.0, 2.0, 0.0, 0.0])[None, None, :, None] sliding_cache.update( key_states=prefill, value_states=prefill, layer_idx=0, cache_kwargs={"cache_position": torch.arange(4), "sliding_window": self.window_size}, ) 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]), "sliding_window": self.window_size}, ) self.assertEqual( sliding_cache.key_cache[0][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=self.config, max_batch_size=1, 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_window": self.window_size}, ) 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]), "sliding_window": self.window_size}, ) self.assertEqual( sliding_cache.key_cache[0][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=self.config, max_batch_size=1, 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), "sliding_window": self.window_size}, ) self.assertEqual( sliding_cache.key_cache[0][0, 0, :, 0].tolist(), [3.0, 4.0, 5.0, 6.0], "SlidingWindowCache Scenario 3 failed", )
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)
test_sliding_window_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
def test_hybrid_cache_static_mode(self): """Test HybridCache in static mode with hardcoded assertions. 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.sliding_window_pattern = 1 # Layer 0 is static (1 % 1 == 0) # Scenario 1 hybrid_cache_static_mode = HybridCache(config=config, max_batch_size=1, max_cache_len=self.max_cache_len) prefill = torch.tensor([1.0, 2.0, 0.0, 0.0])[None, None, :, None] hybrid_cache_static_mode.update( key_states=prefill, value_states=prefill, layer_idx=0, cache_kwargs={"cache_position": torch.arange(4)}, ) 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.key_cache[0][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.key_cache[0][0, 0, :, 0].tolist(), [1.0, 2.0, 3.0, 4.0], "HybridCache Static Scenario 2 failed", )
Test HybridCache in static mode with hardcoded assertions. 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]
test_hybrid_cache_static_mode
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_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) """ # Scenario 1: Update within window, no slide yet hybrid_cache = HybridCache(config=self.config, max_batch_size=1, max_cache_len=self.max_cache_len) prefill = torch.tensor([1.0, 2.0, 0.0, 0.0])[None, None, :, None] hybrid_cache.update( key_states=prefill, value_states=prefill, layer_idx=0, cache_kwargs={"cache_position": torch.arange(4), "sliding_window": self.window_size}, ) 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]), "sliding_window": self.window_size}, ) self.assertEqual( hybrid_cache.key_cache[0][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=self.config, max_batch_size=1, 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), "sliding_window": self.window_size}, ) 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]), "sliding_window": self.window_size}, ) self.assertEqual( hybrid_cache.key_cache[0][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]), "sliding_window": self.window_size}, ) self.assertEqual( hybrid_cache.key_cache[0][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=self.config, max_batch_size=1, 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), "sliding_window": self.window_size}, ) self.assertEqual( hybrid_cache.key_cache[0][0, 0, :, 0].tolist(), [3.0, 4.0, 5.0, 6.0], "HybridCache Sliding Scenario 4 failed", )
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)
test_hybrid_cache_sliding_mode
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 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
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.
fn
python
huggingface/transformers
tests/utils/test_chat_template_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_chat_template_utils.py
Apache-2.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")
Regression test for https://github.com/huggingface/transformers/issues/31002.
test_loading_config_do_not_raise_future_warnings
python
huggingface/transformers
tests/utils/test_configuration_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_configuration_utils.py
Apache-2.0
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)
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
analyze_directory
python
huggingface/transformers
tests/utils/test_doc_samples.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_doc_samples.py
Apache-2.0
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 config_return_dict is False or return_dict is False else BaseModelOutput 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)
Test that the can_return_tuple decorator works with eager mode.
test_decorator_eager
python
huggingface/transformers
tests/utils/test_generic.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_generic.py
Apache-2.0
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)
Test that the can_return_tuple decorator works with compiled mode.
test_decorator_compiled
python
huggingface/transformers
tests/utils/test_generic.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_generic.py
Apache-2.0
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),))
Test that the can_return_tuple decorator works with torch.export.
test_decorator_torch_export
python
huggingface/transformers
tests/utils/test_generic.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_generic.py
Apache-2.0
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)
Test that the can_return_tuple decorator works with torch.jit.trace.
test_decorator_torchscript
python
huggingface/transformers
tests/utils/test_generic.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_generic.py
Apache-2.0
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", )
Test that the `_is_top_level_module` attribute is removed after the forward call.
test_attribute_cleanup
python
huggingface/transformers
tests/utils/test_generic.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_generic.py
Apache-2.0
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", None) and yy.get("choices", None): 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)
Small helper to check pseudo-equality of parsed arguments on `ArgumentParser` instances.
argparsersEqual
python
huggingface/transformers
tests/utils/test_hf_argparser.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_hf_argparser.py
Apache-2.0
def test_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 in (dict, dict): raw_dict_fields.append(field) # Next check for `Union` or `Optional` elif get_origin(field.type) == Union: if any(arg in (dict, 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(args[0], (dict, dict)) self.assertEqual( str(args[1]), "<class 'str'>", 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`", )
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
test_valid_dict_annotation
python
huggingface/transformers
tests/utils/test_hf_argparser.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_hf_argparser.py
Apache-2.0
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)
Test download file from a gated repo fails with correct message when not authenticated.
test_get_file_gated_repo
python
huggingface/transformers
tests/utils/test_hub_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_hub_utils.py
Apache-2.0
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)
Test check file existence from a gated repo fails with correct message when not authenticated.
test_has_file_gated_repo
python
huggingface/transformers
tests/utils/test_hub_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_hub_utils.py
Apache-2.0
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")
Test that unhadled exceptions, e.g. ModuleNotFoundError, is properly re-raised by cached_files when hf_hub_download fails.
test_cached_files_exception_raised
python
huggingface/transformers
tests/utils/test_hub_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_hub_utils.py
Apache-2.0
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("\"', "))
Returns the content of the __all__ variable in the file content. Returns None if not defined, otherwise returns a list of strings.
fetch__all__
python
huggingface/transformers
tests/utils/test_import_structure.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_import_structure.py
Apache-2.0
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 requirement, module_object_mapping in import_structure.items(): 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)
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().
test_transformers_specific_model_import
python
huggingface/transformers
tests/utils/test_import_structure.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_import_structure.py
Apache-2.0
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)
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}
test_import_spread
python
huggingface/transformers
tests/utils/test_import_structure.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_import_structure.py
Apache-2.0
def test_safetensors_load_from_hub(self): """ This test checks that we can load safetensors from a checkpoint that only has those on the Hub """ flax_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-only") # Can load from the Flax-formatted checkpoint safetensors_model = FlaxBertModel.from_pretrained("hf-internal-testing/tiny-bert-flax-safetensors-only") self.assertTrue(check_models_equal(flax_model, safetensors_model))
This test checks that we can load safetensors from a checkpoint that only has those on the Hub
test_safetensors_load_from_hub
python
huggingface/transformers
tests/utils/test_modeling_flax_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_flax_utils.py
Apache-2.0
def test_safetensors_load_from_local(self): """ This test checks that we can load safetensors from a checkpoint that only has those on the Hub """ with tempfile.TemporaryDirectory() as tmp: location = snapshot_download("hf-internal-testing/tiny-bert-flax-only", cache_dir=tmp) flax_model = FlaxBertModel.from_pretrained(location) with tempfile.TemporaryDirectory() as tmp: location = snapshot_download("hf-internal-testing/tiny-bert-flax-safetensors-only", cache_dir=tmp) safetensors_model = FlaxBertModel.from_pretrained(location) self.assertTrue(check_models_equal(flax_model, safetensors_model))
This test checks that we can load safetensors from a checkpoint that only has those on the Hub
test_safetensors_load_from_local
python
huggingface/transformers
tests/utils/test_modeling_flax_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_flax_utils.py
Apache-2.0
def test_safetensors_load_from_local_msgpack_before_safetensors(self): """ This test checks that we'll first download msgpack weights before safetensors The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch """ with tempfile.TemporaryDirectory() as tmp: location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors-msgpack", cache_dir=tmp) FlaxBertModel.from_pretrained(location)
This test checks that we'll first download msgpack weights before safetensors The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch
test_safetensors_load_from_local_msgpack_before_safetensors
python
huggingface/transformers
tests/utils/test_modeling_flax_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_flax_utils.py
Apache-2.0
def test_safetensors_load_from_local(self): """ This test checks that we can load safetensors from a checkpoint that only has those on the Hub """ with tempfile.TemporaryDirectory() as tmp: location = snapshot_download("hf-internal-testing/tiny-bert-tf-only", cache_dir=tmp) tf_model = TFBertModel.from_pretrained(location) with tempfile.TemporaryDirectory() as tmp: location = snapshot_download("hf-internal-testing/tiny-bert-tf-safetensors-only", cache_dir=tmp) safetensors_model = TFBertModel.from_pretrained(location) for p1, p2 in zip(tf_model.weights, safetensors_model.weights): self.assertTrue(np.allclose(p1.numpy(), p2.numpy()))
This test checks that we can load safetensors from a checkpoint that only has those on the Hub
test_safetensors_load_from_local
python
huggingface/transformers
tests/utils/test_modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_tf_utils.py
Apache-2.0
def test_safetensors_load_from_hub_from_safetensors_pt(self): """ This test checks that we can load safetensors from a checkpoint that only has those on the Hub. saved in the "pt" format. """ tf_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-h5") # Can load from the PyTorch-formatted checkpoint safetensors_model = TFBertModel.from_pretrained("hf-internal-testing/tiny-bert-pt-safetensors") for p1, p2 in zip(tf_model.weights, safetensors_model.weights): self.assertTrue(np.allclose(p1.numpy(), p2.numpy()))
This test checks that we can load safetensors from a checkpoint that only has those on the Hub. saved in the "pt" format.
test_safetensors_load_from_hub_from_safetensors_pt
python
huggingface/transformers
tests/utils/test_modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_tf_utils.py
Apache-2.0
def test_safetensors_load_from_local_from_safetensors_pt(self): """ This test checks that we can load safetensors from a local checkpoint that only has those saved in the "pt" format. """ with tempfile.TemporaryDirectory() as tmp: location = snapshot_download("hf-internal-testing/tiny-bert-h5", cache_dir=tmp) tf_model = TFBertModel.from_pretrained(location) # Can load from the PyTorch-formatted checkpoint with tempfile.TemporaryDirectory() as tmp: location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors", cache_dir=tmp) safetensors_model = TFBertModel.from_pretrained(location) for p1, p2 in zip(tf_model.weights, safetensors_model.weights): self.assertTrue(np.allclose(p1.numpy(), p2.numpy()))
This test checks that we can load safetensors from a local checkpoint that only has those saved in the "pt" format.
test_safetensors_load_from_local_from_safetensors_pt
python
huggingface/transformers
tests/utils/test_modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_tf_utils.py
Apache-2.0
def test_safetensors_load_from_local_h5_before_safetensors(self): """ This test checks that we'll first download h5 weights before safetensors The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch """ with tempfile.TemporaryDirectory() as tmp: location = snapshot_download("hf-internal-testing/tiny-bert-pt-safetensors-msgpack", cache_dir=tmp) TFBertModel.from_pretrained(location)
This test checks that we'll first download h5 weights before safetensors The safetensors file on that repo is a pt safetensors and therefore cannot be loaded without PyTorch
test_safetensors_load_from_local_h5_before_safetensors
python
huggingface/transformers
tests/utils/test_modeling_tf_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_tf_utils.py
Apache-2.0
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"} )
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.
test_model_from_config_torch_dtype_composite
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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))
Calling `model.save_pretrained` should move the changes made to `generate` parameterization in the model config to the generation config.
test_modifying_model_config_gets_moved_to_generation_config
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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)) )
tests that our custom `isin_mps_friendly` matches `torch.isin`
test_isin_mps_friendly
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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)
Tests the behavior of `PreTrainedModel.can_generate` method.
test_can_generate
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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)
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)
test_save_and_load_config_with_custom_generation
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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)
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
test_cache_when_needed_at_train_time
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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)
Tests that the default torch dtype is restored when an error happens during the loading of a model.
test_restore_default_torch_dtype_from_pretrained
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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)
Tests that the default torch dtype is restored when an error happens during the loading of a model.
test_restore_default_torch_dtype_from_config
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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}")
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.
test_loading_is_fast_on_gpu
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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))
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.
test_explicit_transformers_weights_save_and_reload
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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))
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.
test_explicit_transformers_weights_index_save_and_reload
python
huggingface/transformers
tests/utils/test_modeling_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_modeling_utils.py
Apache-2.0
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)
Test `_is_offline_mode` helper (should respect both HF_HUB_OFFLINE and legacy TRANSFORMERS_OFFLINE env vars)
test_is_offline_mode
python
huggingface/transformers
tests/utils/test_offline.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_offline.py
Apache-2.0
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()
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.
_execute_with_env
python
huggingface/transformers
tests/utils/test_offline.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_offline.py
Apache-2.0
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)
Tests that videos can be grouped by frame size and number of frames
test_group_and_reorder_videos
python
huggingface/transformers
tests/utils/test_video_utils.py
https://github.com/huggingface/transformers/blob/master/tests/utils/test_video_utils.py
Apache-2.0
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
Infer the framework from the test class `test_class`.
get_framework
python
huggingface/transformers
utils/add_pipeline_model_mapping_to_test.py
https://github.com/huggingface/transformers/blob/master/utils/add_pipeline_model_mapping_to_test.py
Apache-2.0
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
Get mappings defined in `XXXPipelineTests` for the task `task`.
get_mapping_for_task
python
huggingface/transformers
utils/add_pipeline_model_mapping_to_test.py
https://github.com/huggingface/transformers/blob/master/utils/add_pipeline_model_mapping_to_test.py
Apache-2.0
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
Get the model architecture(s) related to the test class `test_class` for a pipeline `task`.
get_model_for_pipeline_test
python
huggingface/transformers
utils/add_pipeline_model_mapping_to_test.py
https://github.com/huggingface/transformers/blob/master/utils/add_pipeline_model_mapping_to_test.py
Apache-2.0
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
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.
get_pipeline_model_mapping_string
python
huggingface/transformers
utils/add_pipeline_model_mapping_to_test.py
https://github.com/huggingface/transformers/blob/master/utils/add_pipeline_model_mapping_to_test.py
Apache-2.0
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
Restrict to `XXXModelTesterMixin` and should be a subclass of `unittest.TestCase`.
is_valid_test_class
python
huggingface/transformers
utils/add_pipeline_model_mapping_to_test.py
https://github.com/huggingface/transformers/blob/master/utils/add_pipeline_model_mapping_to_test.py
Apache-2.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
Find a test class in `test_file` to which we will add `pipeline_model_mapping`.
find_test_class
python
huggingface/transformers
utils/add_pipeline_model_mapping_to_test.py
https://github.com/huggingface/transformers/blob/master/utils/add_pipeline_model_mapping_to_test.py
Apache-2.0
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
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.
check_attribute_being_used
python
huggingface/transformers
utils/check_config_attributes.py
https://github.com/huggingface/transformers/blob/master/utils/check_config_attributes.py
Apache-2.0
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)
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.
check_config_attributes_being_used
python
huggingface/transformers
utils/check_config_attributes.py
https://github.com/huggingface/transformers/blob/master/utils/check_config_attributes.py
Apache-2.0
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)
Check the arguments in `__init__` of all configuration classes are used in python files
check_config_attributes
python
huggingface/transformers
utils/check_config_attributes.py
https://github.com/huggingface/transformers/blob/master/utils/check_config_attributes.py
Apache-2.0
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.")
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.
_sanity_check_splits
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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
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).
find_block_end
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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
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)`.
split_code_into_blocks
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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
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.
find_code_in_transformers
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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
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.
replace_code
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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
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`.
find_code_and_splits
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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 ""
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).
get_indent
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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
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.
stylify
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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
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.
check_codes_match
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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.keys()} name_mappings_2 = {k: k for k in observed_code_blocks.keys()} # 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
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.
is_copy_consistent
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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." )
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.
check_copies
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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." )
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.
check_full_copies
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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)
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.
get_model_list
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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"
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.
convert_to_localized_md
python
huggingface/transformers
utils/check_copies.py
https://github.com/huggingface/transformers/blob/master/utils/check_copies.py
Apache-2.0
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])
Returns the number of spaces that start a line indent.
find_indent
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.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}`"
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.
stringify_default
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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
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 ```
eval_math_expression
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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
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.
replace_default_in_arg_description
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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 = "<fill_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}"
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.
get_default_description
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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")
Finds the source file of an object. Args: obj (`Any`): The object whose source file we are looking for. Returns: `Path`: The source file.
find_source_file
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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 = [] 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] if re.search(r"^\s*#\s*no-format\s*$", line_before_docstring): # This object is ignored return 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}): <fill_docstring>" # 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.keys() if len(arguments[name]) > 0] new_doc_arg = "\n".join(new_param_docs) return old_doc_arg, new_doc_arg
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.
match_docstring_with_signature
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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 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 if "".join(source[start_idx:idx])[:-1] != old_doc_args: # Args are not fully defined in the docstring of this object return 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") 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))
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`).
fix_docstring
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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
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.
find_matching_model_files
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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
From a list of files, return those that contain the @auto_docstring decorator.
find_files_with_auto_docstring
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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
For a file's lines, find the start and end line indices of all @auto_docstring candidates. Returns two lists: starts and ends.
get_auto_docstring_candidate_lines
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
def generate_new_docstring_for_signature( lines, sig_start_line, sig_end_line, docstring_line, arg_indent=" ", custom_args_dict={}, ): """ 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 = [] fill_docstring_args = [] signature_content = lines[sig_start_line:sig_end_line] 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") # Parse docstring if present args_docstring_dict = {} remaining_docstring = "" docstring_end = sig_end_line - 1 if docstring_line is not None: docstring_end = docstring_line if not lines[docstring_line].count('"""') >= 2: docstring_end += 1 while '"""' not in lines[docstring_end]: docstring_end += 1 docstring_content = lines[docstring_line : docstring_end + 1] parsed_docstring, remaining_docstring = parse_docstring("\n".join(docstring_content)) args_docstring_dict.update(parsed_docstring) # Fill missing args for arg in args_in_signature: if ( arg not in args_docstring_dict and arg not in source_args_doc([ModelArgs, ImageProcessorArgs]) and arg not in custom_args_dict ): missing_docstring_args.append(arg) args_docstring_dict[arg] = { "type": "<fill_type>", "optional": False, "shape": None, "description": f"\n{arg_indent} <fill_docstring>", "default": None, "additional_info": None, } # Build new docstring new_docstring = "" if len(args_docstring_dict) > 0 or remaining_docstring: new_docstring += 'r"""\n' for arg in args_docstring_dict: additional_info = args_docstring_dict[arg]["additional_info"] or "" custom_arg_description = args_docstring_dict[arg]["description"] if "<fill_docstring>" 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} ({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, 8) return new_docstring, sig_end_line, docstring_end, missing_docstring_args, fill_docstring_args
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)
generate_new_docstring_for_signature
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
def generate_new_docstring_for_function(lines, current_line_end, custom_args_dict): """ Wrapper for function docstring generation using the generalized helper. """ sig_line_end = _find_sig_line(lines, current_line_end) docstring_line = sig_line_end if '"""' in lines[sig_line_end] else None return generate_new_docstring_for_signature( lines, current_line_end, sig_line_end, docstring_line, arg_indent=" ", custom_args_dict=custom_args_dict, )
Wrapper for function docstring generation using the generalized helper.
generate_new_docstring_for_function
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0
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. """ init_method_line = current_line_end found_init_method = False while init_method_line < len(lines) - 1 and not found_init_method: init_method_line += 1 if " def __init__" in lines[init_method_line]: found_init_method = True elif lines[init_method_line].startswith("class "): break if not found_init_method: return "", None, None, None, [], [] init_method_sig_line_end = _find_sig_line(lines, init_method_line) docstring_line = init_method_sig_line_end if '"""' in lines[init_method_sig_line_end] else None new_docstring, _, init_method_docstring_end, missing_docstring_args, fill_docstring_args = ( generate_new_docstring_for_signature( lines, init_method_line, init_method_sig_line_end, docstring_line, arg_indent="", custom_args_dict=custom_args_dict, ) ) return ( new_docstring, init_method_line, init_method_sig_line_end, init_method_docstring_end, missing_docstring_args, fill_docstring_args, )
Wrapper for class docstring generation (via __init__) using the generalized helper. Returns the new docstring and relevant signature/docstring indices.
generate_new_docstring_for_class
python
huggingface/transformers
utils/check_docstrings.py
https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py
Apache-2.0