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_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 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 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 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_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 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_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_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 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 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 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 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 |
def find_custom_args_with_details(file_content: str, custom_args_var_name: str) -> list[dict]:
"""
Find the given custom args variable in the file content and return its content.
Args:
file_content: The string content of the Python file.
custom_args_var_name: The name of the custom args var... |
Find the given custom args variable in the file content and return its content.
Args:
file_content: The string content of the Python file.
custom_args_var_name: The name of the custom args variable.
| find_custom_args_with_details | python | huggingface/transformers | utils/check_docstrings.py | https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py | Apache-2.0 |
def update_file_with_new_docstrings(
candidate_file, lines, line_starts_candidates, line_ends_candidates, overwrite=False
):
"""
For a given file, update the docstrings for all @auto_docstring candidates and write the new content.
"""
content_base_file_new_lines = lines[: line_ends_candidates[0]]
... |
For a given file, update the docstrings for all @auto_docstring candidates and write the new content.
| update_file_with_new_docstrings | python | huggingface/transformers | utils/check_docstrings.py | https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py | Apache-2.0 |
def check_docstrings(overwrite: bool = False, check_all: bool = False):
"""
Check docstrings of all public objects that are callables and are documented. By default, only checks the diff.
Args:
overwrite (`bool`, *optional*, defaults to `False`):
Whether to fix inconsistencies or not.
... |
Check docstrings of all public objects that are callables and are documented. By default, only checks the diff.
Args:
overwrite (`bool`, *optional*, defaults to `False`):
Whether to fix inconsistencies or not.
check_all (`bool`, *optional*, defaults to `False`):
Whether... | check_docstrings | python | huggingface/transformers | utils/check_docstrings.py | https://github.com/huggingface/transformers/blob/master/utils/check_docstrings.py | Apache-2.0 |
def get_models_in_diff():
"""
Finds all models that have been modified in the diff.
Returns:
A set containing the names of the models that have been modified (e.g. {'llama', 'whisper'}).
"""
fork_point_sha = subprocess.check_output("git merge-base main HEAD".split()).decode("utf-8")
mod... |
Finds all models that have been modified in the diff.
Returns:
A set containing the names of the models that have been modified (e.g. {'llama', 'whisper'}).
| get_models_in_diff | python | huggingface/transformers | utils/check_modular_conversion.py | https://github.com/huggingface/transformers/blob/master/utils/check_modular_conversion.py | Apache-2.0 |
def guaranteed_no_diff(modular_file_path, dependencies, models_in_diff):
"""
Returns whether it is guaranteed to have no differences between the modular file and the modeling file.
Model is in the diff -> not guaranteed to have no differences
Dependency is in the diff -> not guaranteed to have no diffe... |
Returns whether it is guaranteed to have no differences between the modular file and the modeling file.
Model is in the diff -> not guaranteed to have no differences
Dependency is in the diff -> not guaranteed to have no differences
Otherwise -> guaranteed to have no differences
Args:
mod... | guaranteed_no_diff | python | huggingface/transformers | utils/check_modular_conversion.py | https://github.com/huggingface/transformers/blob/master/utils/check_modular_conversion.py | Apache-2.0 |
def find_all_documented_objects() -> List[str]:
"""
Parse the content of all doc files to detect which classes and functions it documents.
Returns:
`List[str]`: The list of all object names being documented.
`Dict[str, List[str]]`: A dictionary mapping the object name (full import path, e.g... |
Parse the content of all doc files to detect which classes and functions it documents.
Returns:
`List[str]`: The list of all object names being documented.
`Dict[str, List[str]]`: A dictionary mapping the object name (full import path, e.g.
`integrations.PeftAdapterMixin`) to its d... | find_all_documented_objects | python | huggingface/transformers | utils/check_repo.py | https://github.com/huggingface/transformers/blob/master/utils/check_repo.py | Apache-2.0 |
def check_public_method_exists(documented_methods_map):
"""Check that all explicitly documented public methods are defined in the corresponding class."""
failures = []
for obj, methods in documented_methods_map.items():
# Let's ensure there is no repetition
if len(set(methods)) != len(method... | Check that all explicitly documented public methods are defined in the corresponding class. | check_public_method_exists | python | huggingface/transformers | utils/check_repo.py | https://github.com/huggingface/transformers/blob/master/utils/check_repo.py | Apache-2.0 |
def check_repo_quality():
"""Check all models are tested and documented."""
print("Repository-wide checks:")
print(" - checking all models are included.")
check_model_list()
print(" - checking all models are public.")
check_models_are_in_init()
print(" - checking all models have tes... | Check all models are tested and documented. | check_repo_quality | python | huggingface/transformers | utils/check_repo.py | https://github.com/huggingface/transformers/blob/master/utils/check_repo.py | Apache-2.0 |
def find_priority_list(py_files):
"""
Given a list of modular files, sorts them by topological order. Modular models that DON'T depend on other modular
models will be higher in the topological order.
Args:
py_files: List of paths to the modular files
Returns:
A tuple with the order... |
Given a list of modular files, sorts them by topological order. Modular models that DON'T depend on other modular
models will be higher in the topological order.
Args:
py_files: List of paths to the modular files
Returns:
A tuple with the ordered files (list) and their dependencies (d... | find_priority_list | python | huggingface/transformers | utils/create_dependency_mapping.py | https://github.com/huggingface/transformers/blob/master/utils/create_dependency_mapping.py | Apache-2.0 |
def update_main_init_file(models):
"""
Replace all instances of model.model_name with model.deprecated.model_name in the __init__.py file
Args:
models (List[str]): The models to mark as deprecated
"""
filename = REPO_PATH / "src/transformers/__init__.py"
with open(filename, "r") as f:
... |
Replace all instances of model.model_name with model.deprecated.model_name in the __init__.py file
Args:
models (List[str]): The models to mark as deprecated
| update_main_init_file | python | huggingface/transformers | utils/deprecate_models.py | https://github.com/huggingface/transformers/blob/master/utils/deprecate_models.py | Apache-2.0 |
def remove_model_references_from_file(filename, models, condition):
"""
Remove all references to the given models from the given file
Args:
filename (str): The file to remove the references from
models (List[str]): The models to remove
condition (Callable): A function that takes the... |
Remove all references to the given models from the given file
Args:
filename (str): The file to remove the references from
models (List[str]): The models to remove
condition (Callable): A function that takes the line and model and returns True if the line should be removed
| remove_model_references_from_file | python | huggingface/transformers | utils/deprecate_models.py | https://github.com/huggingface/transformers/blob/master/utils/deprecate_models.py | Apache-2.0 |
def remove_model_config_classes_from_config_check(model_config_classes):
"""
Remove the deprecated model config classes from the check_config_attributes.py file
Args:
model_config_classes (List[str]): The model config classes to remove e.g. ["BertConfig", "DistilBertConfig"]
"""
filename = ... |
Remove the deprecated model config classes from the check_config_attributes.py file
Args:
model_config_classes (List[str]): The model config classes to remove e.g. ["BertConfig", "DistilBertConfig"]
| remove_model_config_classes_from_config_check | python | huggingface/transformers | utils/deprecate_models.py | https://github.com/huggingface/transformers/blob/master/utils/deprecate_models.py | Apache-2.0 |
def add_models_to_deprecated_models_in_config_auto(models):
"""
Add the models to the DEPRECATED_MODELS list in configuration_auto.py and sorts the list
to be in alphabetical order.
"""
filepath = REPO_PATH / "src/transformers/models/auto/configuration_auto.py"
with open(filepath, "r") as f:
... |
Add the models to the DEPRECATED_MODELS list in configuration_auto.py and sorts the list
to be in alphabetical order.
| add_models_to_deprecated_models_in_config_auto | python | huggingface/transformers | utils/deprecate_models.py | https://github.com/huggingface/transformers/blob/master/utils/deprecate_models.py | Apache-2.0 |
def get_jobs(workflow_run_id, token=None):
"""Extract jobs in a GitHub Actions workflow run"""
headers = None
if token is not None:
headers = {"Accept": "application/vnd.github+json", "Authorization": f"Bearer {token}"}
url = f"https://api.github.com/repos/huggingface/transformers/actions/runs... | Extract jobs in a GitHub Actions workflow run | get_jobs | python | huggingface/transformers | utils/get_ci_error_statistics.py | https://github.com/huggingface/transformers/blob/master/utils/get_ci_error_statistics.py | Apache-2.0 |
def get_cased_name(lowercase_name: str) -> str:
"""From a model name in lowercase in the format `my_model`, return the cased name in the format `MyModel`."""
alt_lowercase_name = lowercase_name.replace("_", "-")
if lowercase_name in CONFIG_MAPPING_NAMES:
return CONFIG_MAPPING_NAMES[lowercase_name].r... | From a model name in lowercase in the format `my_model`, return the cased name in the format `MyModel`. | get_cased_name | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def get_lowercase_name(cased_name: str) -> str:
"""From a model name in Camelcase in the format `MyModel`, return the lowercase name in the format `my_model`."""
inverse_mapping = {value: key for key, value in CONFIG_MAPPING_NAMES.items()}
if cased_name + "Config" in inverse_mapping:
return inverse_... | From a model name in Camelcase in the format `MyModel`, return the lowercase name in the format `my_model`. | get_lowercase_name | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def leave_ImportFrom(self, original_node, updated_node):
"""The imports from other file types (configuration, processing etc) should use original model name."""
if self.original_new_model_name != self.new_name and m.matches(updated_node.module, m.Name()):
patterns = "|".join(ALL_FILE_TYPES)
... | The imports from other file types (configuration, processing etc) should use original model name. | leave_ImportFrom | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def get_full_attribute_name(node: Union[cst.Attribute, cst.Name]) -> Optional[str]:
"""Get the full name of an Attribute or Name node (e.g. `"nn.Module"` for an Attribute representing it). If the
successive value of an Attribute are not Name nodes, return `None`."""
if m.matches(node, m.Name()):
ret... | Get the full name of an Attribute or Name node (e.g. `"nn.Module"` for an Attribute representing it). If the
successive value of an Attribute are not Name nodes, return `None`. | get_full_attribute_name | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def is_full_docstring(original_docstring: str, new_docstring: str, original_level: int) -> bool:
"""Check if `new_docstring` is a full docstring, or if it is only part of a docstring that should then
be merged with the existing old one.
"""
# libcst returns the docstrinbgs with literal `r"""` quotes in ... | Check if `new_docstring` is a full docstring, or if it is only part of a docstring that should then
be merged with the existing old one.
| is_full_docstring | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def update_body(self, existing_body, new_statements):
"""
Helper method to update the body by removing duplicates before adding new statements.
`existing_body` is the body of the original method, the parent class
`new_statements` are the additional statements
"""
deduplic... |
Helper method to update the body by removing duplicates before adding new statements.
`existing_body` is the body of the original method, the parent class
`new_statements` are the additional statements
| update_body | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def _fix_post_init_location(self, new_body: list[cst.CSTNode]):
"""Fix the location of the `post_init()` in the new body, if we added statements after the call to
`super()` (it needs to be the very last statement called)"""
# Fix the post_init() that has to be last
for i, node in enumera... | Fix the location of the `post_init()` in the new body, if we added statements after the call to
`super()` (it needs to be the very last statement called) | _fix_post_init_location | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def _fix_init_location(self, new_body):
"""Fix the location of the `super().__init__()` in the new body, if we had new statements before it."""
start_index = 0
for i, node in enumerate(new_body):
if m.matches(node, DOCSTRING_NODE) and i == start_index:
start_index += ... | Fix the location of the `super().__init__()` in the new body, if we had new statements before it. | _fix_init_location | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def replace_super_calls(self, node: cst.IndentedBlock, func_name: str) -> cst.CSTNode:
"""Updates the body of the input `node`'s `func_name` function by replacing calls
to super().func_name() with the source code of the parent class' `func_name`.
It keeps everything that is defined before `super... | Updates the body of the input `node`'s `func_name` function by replacing calls
to super().func_name() with the source code of the parent class' `func_name`.
It keeps everything that is defined before `super().func_name()`.
| replace_super_calls | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def leave_Return(self, original_node: cst.Return, updated_node: cst.Return) -> cst.CSTNode:
""" "When a return statement is reached, it is replaced with the unrolled super code"""
if m.matches(updated_node.value, m.Call(func=m.Attribute(attr=m.Name("super")))):
func_def = self.get_metadata(P... | "When a return statement is reached, it is replaced with the unrolled super code | leave_Return | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def find_all_dependencies(
dependency_mapping: Dict[str, set],
start_entity: Optional[str] = None,
initial_dependencies: Optional[set] = None,
initial_checked_dependencies: Optional[set] = None,
return_parent: bool = False,
) -> Union[list, set]:
"""Return all the dependencies of the given `star... | Return all the dependencies of the given `start_entity` or `initial_dependencies`. This is basically some kind of
BFS traversal algorithm. It can either start from `start_entity`, or `initial_dependencies`.
Args:
dependency_mapping (`Dict[str, set]`):
A mapping from entities (usually functi... | find_all_dependencies | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def dependencies_for_class_node(node: cst.ClassDef, global_names: set[str]) -> set:
"""Create immediate dependencies for a class node based on the `global_names`."""
temp_module = cst.Module(body=[node])
visitor = ClassDependencyMapper(node.name.value, global_names)
temp_module.visit(visitor)
return... | Create immediate dependencies for a class node based on the `global_names`. | dependencies_for_class_node | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def augmented_dependencies_for_class_node(
node: cst.ClassDef, mapper: "ModuleMapper", objects_imported_from_modeling: Optional[set[str]] = None
) -> set:
"""Create augmented dependencies for a class node based on a `mapper`.
Augmented dependencies means immediate dependencies + recursive function and assig... | Create augmented dependencies for a class node based on a `mapper`.
Augmented dependencies means immediate dependencies + recursive function and assignments dependencies.
| augmented_dependencies_for_class_node | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def visit_ImportFrom(self, node):
"""This keeps track of objects imported from neighbor modeling files (e.g. in `modeling_xxx.py, we have
`from .configuration_xxx import Config`, then `Config` should be recorded as it is not a dependency that needs
to be added (because it will be part of the imp... | This keeps track of objects imported from neighbor modeling files (e.g. in `modeling_xxx.py, we have
`from .configuration_xxx import Config`, then `Config` should be recorded as it is not a dependency that needs
to be added (because it will be part of the imports) | visit_ImportFrom | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def visit_SimpleStatementLine(self, node):
"""
Global Assigns like `GEMMA_INPUT_DOCSTRING = 'THIS IS THE INPUT'` and all import statements
are extracted and saved in their corresponding dict. They are then used when updating dependency mappings.
"""
parent_node = self.get_metadat... |
Global Assigns like `GEMMA_INPUT_DOCSTRING = 'THIS IS THE INPUT'` and all import statements
are extracted and saved in their corresponding dict. They are then used when updating dependency mappings.
| visit_SimpleStatementLine | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def visit_ClassDef(self, node: ClassDef) -> None:
"""Record class nodes to create their dependencies at the end."""
self.classes[node.name.value] = node
self.current_class = node.name.value | Record class nodes to create their dependencies at the end. | visit_ClassDef | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def visit_Name(self, node: cst.Call):
"""This is used to create a mapping from module-scope functions and assignments to objects used inside them."""
if self.current_function is not None:
self.object_dependency_mapping[self.current_function].add(node.value)
if self.current_assignment... | This is used to create a mapping from module-scope functions and assignments to objects used inside them. | visit_Name | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def leave_Module(self, node):
"""When leaving the module, we store the position of each global scoped node to allow sorting the dependencies
based on their position in the code later. We use the PositionProvider metadata wrapper for this.
We also make sure to update `self.object_dependency_mappi... | When leaving the module, we store the position of each global scoped node to allow sorting the dependencies
based on their position in the code later. We use the PositionProvider metadata wrapper for this.
We also make sure to update `self.object_dependency_mapping` so that it contains only names record... | leave_Module | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def _restrict_dependencies_to_known_entities(self):
"""Since we added every Name as part of `self.object_dependency_mapping`, we need to remove those that
are not part of the recorded objects in `self.global_nodes` (i.e. built-in variables, imports, etc).
This should be called only after all mer... | Since we added every Name as part of `self.object_dependency_mapping`, we need to remove those that
are not part of the recorded objects in `self.global_nodes` (i.e. built-in variables, imports, etc).
This should be called only after all merging operations have been finalized!! | _restrict_dependencies_to_known_entities | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def _compute_recursive_object_dependencies(self) -> dict[str, set]:
"""Based on immediate dependency mapping, create the recursive dependency mapping. For example, given the
following file:
```
def foo():
pass
def bar():
foo()
def test():
... | Based on immediate dependency mapping, create the recursive dependency mapping. For example, given the
following file:
```
def foo():
pass
def bar():
foo()
def test():
bar()
```
this visitor can only record immediate dependenc... | _compute_recursive_object_dependencies | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def augment_dependencies(self, dependencies: set[str]) -> set[str]:
"""For a set of `dependencies`, augment them by adding all potential dependencies of the **functions** and
**assignments** present in the `dependencies`.
"""
new_dependencies = dependencies.copy()
# Go through th... | For a set of `dependencies`, augment them by adding all potential dependencies of the **functions** and
**assignments** present in the `dependencies`.
| augment_dependencies | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def compute_class_dependencies(self):
"""For each visited class, find its dependencies based on visiting the current file + potential merged dependencies."""
self.class_dependency_mapping = {}
for class_name, class_node in self.classes.items():
dependencies = dependencies_for_class_n... | For each visited class, find its dependencies based on visiting the current file + potential merged dependencies. | compute_class_dependencies | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def compute_relative_order(self, missing_dependencies: set[str]) -> dict[str, int]:
"""Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that
will be created based on the modular.
"""
relative_order = {}
idx = 0
... | Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that
will be created based on the modular.
| compute_relative_order | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def _merge_functions(self, functions: dict[str, cst.CSTNode], object_mapping: dict[str, set]):
"""Update the global nodes and function dependency mapping with those from the modular file.
Merging rule: if any function with the same name was redefined in the modular, use it and its dependencies
... | Update the global nodes and function dependency mapping with those from the modular file.
Merging rule: if any function with the same name was redefined in the modular, use it and its dependencies
instead of the original ones (this may mean to add new functions as well, if any redefined function uses a... | _merge_functions | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def _merge_assignments(self, assignments: dict[str, cst.CSTNode], object_mapping: dict[str, set]):
"""Update the global nodes with the assignment from the modular file.
Merging rule: if any assignment with the same name was redefined in the modular, we use it and its dependencies ONLY if it matches
... | Update the global nodes with the assignment from the modular file.
Merging rule: if any assignment with the same name was redefined in the modular, we use it and its dependencies ONLY if it matches
a pattern in `ASSIGNMENTS_REGEX_TO_KEEP_IF_NOT_NONE` and its value is not None, or if it matches a patter... | _merge_assignments | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def _merge_classes(self, classes: dict[str, cst.CSTNode]):
"""Update the global nodes with the new classes from the modular (i.e. classes which do not exist in current file, and
are not imported). We do NOT update any dependency mapping here. This is because we only need the names of newly defined
... | Update the global nodes with the new classes from the modular (i.e. classes which do not exist in current file, and
are not imported). We do NOT update any dependency mapping here. This is because we only need the names of newly defined
classes in the modular to be discoverable when computing dependenci... | _merge_classes | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def merge_modular_dependencies(self, classes, functions, assignments, object_mapping, start_lines):
"""Merge classes, functions and assignments from the modular definitions into the current module file,
then record the relative order of all nodes.
Note: This function takes care of updating `glob... | Merge classes, functions and assignments from the modular definitions into the current module file,
then record the relative order of all nodes.
Note: This function takes care of updating `global_nodes` and `object_recursive_dependency_mapping` as well after the
merge with other files dependenci... | merge_modular_dependencies | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def common_partial_suffix(str1: str, str2: str) -> str:
"""Return the biggest common suffix between 2 strings. If one string is a full suffix of the other string,
we do not consider it a common suffix and return `""`"""
common_suffix = ""
for i in range(1, min(len(str1), len(str2)) + 1):
if str1... | Return the biggest common suffix between 2 strings. If one string is a full suffix of the other string,
we do not consider it a common suffix and return `""` | common_partial_suffix | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def replace_class_node(
mapper: ModelFileMapper, class_node: cst.ClassDef, renamed_super_class: str, original_super_class: str
):
"""
Replace a class node which inherits from another modeling class. This function works in the following way:
- start from the base class node of the inherited class (a cst.... |
Replace a class node which inherits from another modeling class. This function works in the following way:
- start from the base class node of the inherited class (a cst.Node)
- replace all methods of the base node with the methods defined in the child class
- append all new methods defined in the chil... | replace_class_node | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def find_file_type(class_name: str) -> str:
"""Based on a class name, find the file type corresponding to the class.
If the class name is `LlamaConfig` it will return `configuration`.
The list of suffixes is in `TYPE_TO_FILE_TYPE`. If there are no match, we match by default to `modeling`
"""
match_p... | Based on a class name, find the file type corresponding to the class.
If the class name is `LlamaConfig` it will return `configuration`.
The list of suffixes is in `TYPE_TO_FILE_TYPE`. If there are no match, we match by default to `modeling`
| find_file_type | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def append_new_import_node(
node: cst.CSTNode, unused_imports: set[str], added_names: set, imports_to_keep: list[cst.CSTNode]
):
"""Insert the new `node` to the list of `imports_to_keep` in-place, if it is not part of the `unused_imports` or `added_names`.
Also modifies `added_names` in-place accordingly.""... | Insert the new `node` to the list of `imports_to_keep` in-place, if it is not part of the `unused_imports` or `added_names`.
Also modifies `added_names` in-place accordingly. | append_new_import_node | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def get_needed_imports(body: dict[str, dict], all_imports: list[cst.CSTNode]) -> list[cst.CSTNode]:
"""Get all the imports needed in the `body`, from the list of `all_imports`.
`body` is a dict with the following structure `{str: {"insert_idx": int, "node": cst.CSTNode}}`.
Note: we need to use `isinstance` ... | Get all the imports needed in the `body`, from the list of `all_imports`.
`body` is a dict with the following structure `{str: {"insert_idx": int, "node": cst.CSTNode}}`.
Note: we need to use `isinstance` on scope assignments, m.matches apparently does not work here yet!
| get_needed_imports | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
def split_all_assignment(node: cst.CSTNode) -> dict[str, cst.CSTNode]:
"""Split the `__all__` assignment found in the modular between each corresponding files."""
all_all_per_file = {}
assign_node = node.body[0]
if isinstance(assign_node.value, cst.List):
# Extract the elements from the list
... | Split the `__all__` assignment found in the modular between each corresponding files. | split_all_assignment | python | huggingface/transformers | utils/modular_model_converter.py | https://github.com/huggingface/transformers/blob/master/utils/modular_model_converter.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.