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_indic... |
Test that load_backbone correctly loads a backbone from a checkpoint.
| test_load_backbone_from_checkpoint | python | huggingface/transformers | tests/utils/test_backbone_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_backbone_utils.py | Apache-2.0 |
def test_load_backbone_backbone_kwargs(self):
"""
Test that load_backbone correctly configures the loaded backbone with the provided kwargs.
"""
config = MaskFormerConfig(backbone="resnet18", use_timm_backbone=True, backbone_kwargs={"out_indices": (0, 1)})
backbone = load_backbon... |
Test that load_backbone correctly configures the loaded backbone with the provided kwargs.
| test_load_backbone_backbone_kwargs | python | huggingface/transformers | tests/utils/test_backbone_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_backbone_utils.py | Apache-2.0 |
def test_load_backbone_in_new_model(self):
"""
Tests that new model can be created, with its weights instantiated and pretrained backbone weights loaded.
"""
# Inherit from PreTrainedModel to ensure that the weights are initialized
class NewModel(BertPreTrainedModel):
... |
Tests that new model can be created, with its weights instantiated and pretrained backbone weights loaded.
| test_load_backbone_in_new_model | python | huggingface/transformers | tests/utils/test_backbone_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_backbone_utils.py | Apache-2.0 |
def test_dynamic_cache_retrocompatibility(self):
"""Tests that we can convert back and forth between the legacy cache format and DynamicCache"""
legacy_cache = ()
new_cache = DynamicCache()
# Creates a new cache with 10 layers in both formats
for layer_idx in range(10):
... | Tests that we can convert back and forth between the legacy cache format and DynamicCache | test_dynamic_cache_retrocompatibility | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def test_reorder_cache_retrocompatibility(self):
"""Tests that Cache.reorder_cache is retrocompatible with the legacy code path"""
legacy_reorder_fn = ClvpForCausalLM._reorder_cache # An example of a legacy `_reorder_cache` function
legacy_cache = ()
new_cache = DynamicCache()
... | Tests that Cache.reorder_cache is retrocompatible with the legacy code path | test_reorder_cache_retrocompatibility | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def test_static_cache_mha_mqa_gqa(self):
"""
Tests that static cache works with multi-head attention (MHA), grouped query attention (GQA), and multi-query
attention (MQA)
"""
def _random_kvs(config):
# shape for key and values: (batch_size, num_heads, seq_len, head_d... |
Tests that static cache works with multi-head attention (MHA), grouped query attention (GQA), and multi-query
attention (MQA)
| test_static_cache_mha_mqa_gqa | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def _skip_on_failed_cache_prerequisites(test, cache_implementation):
"""Function to skip tests on failed cache prerequisites, given a cache implementation"""
# Installed dependencies
if cache_implementation == "quantized" and not is_optimum_quanto_available():
test.skipTest("Quanto is not available"... | Function to skip tests on failed cache prerequisites, given a cache implementation | _skip_on_failed_cache_prerequisites | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def test_cache_batched(self, cache_implementation):
"""Sanity check: caches' `.update` function expects batched inputs"""
_skip_on_failed_cache_prerequisites(self, cache_implementation)
EXPECTED_GENERATION = ["A sequence: 1, 2, 3, 4, 5, 6, 7, 8,", "A sequence: A, B, C, D, E, F, G, H"]
... | Sanity check: caches' `.update` function expects batched inputs | test_cache_batched | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def test_cache_beam_search(self, cache_implementation):
"""
Sanity check: caches' `reorder_cache` is operational. We can confirm this by looking at the beam indices
(an output sequence contains multiple beam indices).
"""
_skip_on_failed_cache_prerequisites(self, cache_implementa... |
Sanity check: caches' `reorder_cache` is operational. We can confirm this by looking at the beam indices
(an output sequence contains multiple beam indices).
| test_cache_beam_search | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def test_cache_extra_left_padding(self, cache_implementation):
"""Tests that adding extra left-padding does not affect the generation with the cache"""
_skip_on_failed_cache_prerequisites(self, cache_implementation)
EXPECTED_GENERATION = ["The cat's whiskers are also a sign of anxiety."]
... | Tests that adding extra left-padding does not affect the generation with the cache | test_cache_extra_left_padding | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def test_dynamic_cache_hard(self):
"""Hard test for base cache implementation -- minor numerical fluctuations will cause this test to fail"""
tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen3-4B", padding_side="left")
model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-4B", device_map="... | Hard test for base cache implementation -- minor numerical fluctuations will cause this test to fail | test_dynamic_cache_hard | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def test_static_cache_greedy_decoding_pad_left(self, attn_implementation):
"""Tests that different cache implementations work well with eager and SDPA inference"""
EXPECTED_GENERATION = [
"The best color is the one that is most suitable for the purpose.",
"We should not undermind... | Tests that different cache implementations work well with eager and SDPA inference | test_static_cache_greedy_decoding_pad_left | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
def test_offloaded_cache_uses_less_memory_than_dynamic_cache(self):
"""Tests that OffloadedCache uses less memory than the default DynamicCache"""
model_name = "microsoft/Phi-3-mini-4k-instruct"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretr... | Tests that OffloadedCache uses less memory than the default DynamicCache | test_offloaded_cache_uses_less_memory_than_dynamic_cache | python | huggingface/transformers | tests/utils/test_cache_utils.py | https://github.com/huggingface/transformers/blob/master/tests/utils/test_cache_utils.py | Apache-2.0 |
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"
... | 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... |
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 ... |
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_... | 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"
... | 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 = "bfloat1... |
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 TorchExpor... |
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,
... | 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
... | 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, ... | 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
... | 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]
u... | 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... | 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... | 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: [... | 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 m... |
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 lis... | 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")
... | 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, loo... |
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[st... | 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(
... | 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))
... | 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 = ... | 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)
... | 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):
... |
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()
... |
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.
c... | 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(GA... | 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 'MockModu... | 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.starts... |
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(... |
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.{froz... |
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.trans... | 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
... |
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)... |
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.Temporar... |
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)
... |
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")
# Ca... |
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-inte... |
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... |
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
mode... |
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/... |
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(
... | 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()
s... | 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 = T5ForConditionalGeneratio... |
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_MIS... |
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(torc... |
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.fl... |
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
unstabl... |
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 ... | 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 loa... |
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 no... | 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 wi... |
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 no... | 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_en... |
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.
Environmen... | 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 ... | 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... | 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[ta... | 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:
... | 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 fra... | 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... | 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 `pipelin... | 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.
... | 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 varian... | 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... | 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__:
... | 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 ... | 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 mor... | _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`):
... |
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... | 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... |
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 line... | 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.... |
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`.
ret... | 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.
"""
... | 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
... | 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 ... | 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])... |
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 formatte... |
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:
`Option... |
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 t... | 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 (`bo... |
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`, *optio... | 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 ... |
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... | 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.
"""
di... |
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... |
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 ... | 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 mode... |
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 ... | 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 th... |
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:
`Opti... |
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... | 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... |
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.
Retu... | 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.annota... |
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("."... |
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 t... |
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 docume... | 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`):
T... |
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 r... | 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_di... |
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:
co... |
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 = []
li... |
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: L... |
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 i... | 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
retur... |
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 =... |
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 |
Subsets and Splits
Django Code with Docstrings
Filters Python code examples from Django repository that contain Django-related code, helping identify relevant code snippets for understanding Django framework usage patterns.
SQL Console for Shuu12121/python-treesitter-filtered-datasetsV2
Retrieves specific code examples from the Flask repository but doesn't provide meaningful analysis or patterns beyond basic data retrieval.
HTTPX Repo Code and Docstrings
Retrieves specific code examples from the httpx repository, which is useful for understanding how particular libraries are used but doesn't provide broader analytical insights about the dataset.
Requests Repo Docstrings & Code
Retrieves code examples with their docstrings and file paths from the requests repository, providing basic filtering but limited analytical value beyond finding specific code samples.
Quart Repo Docstrings & Code
Retrieves code examples with their docstrings from the Quart repository, providing basic code samples but offering limited analytical value for understanding broader patterns or relationships in the dataset.