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 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 |
def visit_ImportFrom(self, node: cst.ImportFrom) -> None:
"""When visiting imports from modeling files (i.e. `transformers.models.xxx`) we get the code, parse it,
and save it in `self.model_specific_modules` to later visit. The imported objects are saved in `self.model_specific_imported_objects`.
... | When visiting imports from modeling files (i.e. `transformers.models.xxx`) we get the code, parse it,
and save it in `self.model_specific_modules` to later visit. The imported objects are saved in `self.model_specific_imported_objects`.
| 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):
"""If we visit an import statement not previously visited, record it. If we visit a module-scope assignment,
simply record it or, if it is `__all__`, split it between files where we should dispatch it.
"""
parent_node = self.get_metadata(cst.met... | If we visit an import statement not previously visited, record it. If we visit a module-scope assignment,
simply record it or, if it is `__all__`, split it between files where we should dispatch it.
| 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 leave_Module(self, node):
"""When we leave the modular file, we do the following in order:
1. for each modeling file found in the imports, rename it with the new model name, visit it, and update
its dependency graph with the new function and assignment definitions found in the modular
... | When we leave the modular file, we do the following in order:
1. for each modeling file found in the imports, rename it with the new model name, visit it, and update
its dependency graph with the new function and assignment definitions found in the modular
2. update the modular dependency graph ... | 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 merge_model_specific_imports(self, visited_modules):
"""Merge the functions and assignments imported from the modeling files to the modular nodes and dependency graph,
based on the visited files."""
self.start_lines_file_mapping = {}
self.added_objects_file_mapping = {}
for o... | Merge the functions and assignments imported from the modeling files to the modular nodes and dependency graph,
based on the visited files. | merge_model_specific_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 compute_relative_order(self, missing_dependencies: set) -> dict[str, int]:
"""Compute in which relative order the `missing_dependencies` should appear when the nodes are added to the final file that
will be created based on the modular.
"""
relative_order = {}
idx = 0
... | 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 infer_new_model_name(self) -> dict:
"""Infer whether we are using a model name prefix different from the usual model name as defined from the filename.
This is useful e.g. when we define a new multi-modal model, and only the text part inherits from `LlamaModel`,
so we have something like:
... | Infer whether we are using a model name prefix different from the usual model name as defined from the filename.
This is useful e.g. when we define a new multi-modal model, and only the text part inherits from `LlamaModel`,
so we have something like:
```python
class NewModelNameTextDecod... | infer_new_model_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 check_dependencies_and_create_import_node(
file_type: str, new_dependencies: set[str], mapper: ModuleMapper, new_name: str
) -> tuple[set[str], dict[str, cst.CSTNode]]:
"""Check that all class nodes in the `new_dependencies` belong to the correct `file_type`. If this is not the case,
we need to remove i... | Check that all class nodes in the `new_dependencies` belong to the correct `file_type`. If this is not the case,
we need to remove it from the dependencies, and create a new import to it instead.
This scenario may appear in the following case:
If a new class in the `modular_xxx.py` file does not belong to `... | check_dependencies_and_create_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_class_node_and_dependencies(
modular_mapper: ModularFileMapper, class_name: str, node: cst.CSTNode, files: dict[str, dict]
) -> tuple[dict, str, dict]:
"""Return a single class node (and all its dependency nodes), to be added to the `files`. It creates the new
class node based on the inherited class... | Return a single class node (and all its dependency nodes), to be added to the `files`. It creates the new
class node based on the inherited classes if needed. Also returns any new imports of a new class defined in
the modular that we nay need.
| get_class_node_and_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 create_modules(modular_mapper: ModularFileMapper) -> dict[str, cst.Module]:
"""Create all the new modules based on visiting the modular file. It replaces all classes as necessary."""
files = defaultdict(dict)
current_file_indices = defaultdict(lambda: 0)
# For each class defined in modular, potenti... | Create all the new modules based on visiting the modular file. It replaces all classes as necessary. | create_modules | 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_reply_blocks(self, job_name, job_result, failures, device, text):
"""
failures: A list with elements of the form {"line": full test name, "trace": error trace}
"""
# `text` must be less than 3001 characters in Slack SDK
# keep some room for adding "[Truncated]" when neces... |
failures: A list with elements of the form {"line": full test name, "trace": error trace}
| get_reply_blocks | python | huggingface/transformers | utils/notification_service.py | https://github.com/huggingface/transformers/blob/master/utils/notification_service.py | Apache-2.0 |
def get_release_branch_name():
"""Derive branch name from transformers version."""
major, minor, *_ = transformers.__version__.split(".")
major = int(major)
minor = int(minor)
if minor == 0:
# Handle major version rollback, e.g., from 5.0 to 4.latest (if ever needed)
major -= 1
... | Derive branch name from transformers version. | get_release_branch_name | python | huggingface/transformers | utils/patch_helper.py | https://github.com/huggingface/transformers/blob/master/utils/patch_helper.py | Apache-2.0 |
def get_prs_by_label(label):
"""Call gh CLI to get PRs with a specific label."""
cmd = [
"gh",
"pr",
"list",
"--label",
label,
"--state",
"all",
"--json",
"number,title,mergeCommit,url",
"--limit",
"100",
]
result = ... | Call gh CLI to get PRs with a specific label. | get_prs_by_label | python | huggingface/transformers | utils/patch_helper.py | https://github.com/huggingface/transformers/blob/master/utils/patch_helper.py | Apache-2.0 |
def count_lines(filepath):
"""Count the number of lines in a file."""
try:
with open(filepath, "r") as f:
return len(f.read().split("\n"))
except FileNotFoundError:
return 0 | Count the number of lines in a file. | count_lines | python | huggingface/transformers | utils/process_test_artifacts.py | https://github.com/huggingface/transformers/blob/master/utils/process_test_artifacts.py | Apache-2.0 |
def compute_parallel_nodes(line_count, max_tests_per_node=10):
"""Compute the number of parallel nodes required."""
num_nodes = math.ceil(line_count / AVERAGE_TESTS_PER_NODES)
if line_count < 4:
return 1
return min(MAX_PARALLEL_NODES, num_nodes) | Compute the number of parallel nodes required. | compute_parallel_nodes | python | huggingface/transformers | utils/process_test_artifacts.py | https://github.com/huggingface/transformers/blob/master/utils/process_test_artifacts.py | Apache-2.0 |
def get_new_python_files(diff_with_last_commit=False) -> List[str]:
"""
Return a list of python files that have been added between the current head and the main branch.
Returns:
`List[str]`: The list of python files added.
"""
repo = Repo(PATH_TO_REPO)
try:
# For the cases wher... |
Return a list of python files that have been added between the current head and the main branch.
Returns:
`List[str]`: The list of python files added.
| get_new_python_files | python | huggingface/transformers | utils/pr_slow_ci_models.py | https://github.com/huggingface/transformers/blob/master/utils/pr_slow_ci_models.py | Apache-2.0 |
def parse_message(message: str) -> str:
"""
Parses a GitHub pull request's comment to find the models specified in it to run slow CI.
Args:
message (`str`): The body of a GitHub pull request's comment.
Returns:
`str`: The substring in `message` after `run-slow`, run_slow` or run slow`.... |
Parses a GitHub pull request's comment to find the models specified in it to run slow CI.
Args:
message (`str`): The body of a GitHub pull request's comment.
Returns:
`str`: The substring in `message` after `run-slow`, run_slow` or run slow`. If no such prefix is found, the
empty ... | parse_message | python | huggingface/transformers | utils/pr_slow_ci_models.py | https://github.com/huggingface/transformers/blob/master/utils/pr_slow_ci_models.py | Apache-2.0 |
def update_version_in_file(fname: str, version: str, file_type: str):
"""
Update the version of Transformers in one file.
Args:
fname (`str`): The path to the file where we want to update the version.
version (`str`): The new version to set in the file.
file_type (`str`): The type o... |
Update the version of Transformers in one file.
Args:
fname (`str`): The path to the file where we want to update the version.
version (`str`): The new version to set in the file.
file_type (`str`): The type of the file (should be a key in `REPLACE_PATTERNS`).
| update_version_in_file | python | huggingface/transformers | utils/release.py | https://github.com/huggingface/transformers/blob/master/utils/release.py | Apache-2.0 |
def update_version_in_examples(version: str):
"""
Update the version in all examples files.
Args:
version (`str`): The new version to set in the examples.
"""
for folder, directories, fnames in os.walk(PATH_TO_EXAMPLES):
# Removing some of the folders with non-actively maintained ex... |
Update the version in all examples files.
Args:
version (`str`): The new version to set in the examples.
| update_version_in_examples | python | huggingface/transformers | utils/release.py | https://github.com/huggingface/transformers/blob/master/utils/release.py | Apache-2.0 |
def global_version_update(version: str, patch: bool = False):
"""
Update the version in all needed files.
Args:
version (`str`): The new version to set everywhere.
patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
"""
for pattern, fname in REPL... |
Update the version in all needed files.
Args:
version (`str`): The new version to set everywhere.
patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
| global_version_update | python | huggingface/transformers | utils/release.py | https://github.com/huggingface/transformers/blob/master/utils/release.py | Apache-2.0 |
def remove_conversion_scripts():
"""
Delete the scripts that convert models from older, unsupported formats. We don't want to include these
in release wheels because they often have to open insecure file types (pickle, Torch .bin models). This results in
vulnerability scanners flagging us and can cause ... |
Delete the scripts that convert models from older, unsupported formats. We don't want to include these
in release wheels because they often have to open insecure file types (pickle, Torch .bin models). This results in
vulnerability scanners flagging us and can cause compliance issues for users with strict ... | remove_conversion_scripts | python | huggingface/transformers | utils/release.py | https://github.com/huggingface/transformers/blob/master/utils/release.py | Apache-2.0 |
def get_version() -> packaging.version.Version:
"""
Reads the current version in the main __init__.
"""
with open(REPLACE_FILES["init"], "r") as f:
code = f.read()
default_version = REPLACE_PATTERNS["init"][0].search(code).groups()[0]
return packaging.version.parse(default_version) |
Reads the current version in the main __init__.
| get_version | python | huggingface/transformers | utils/release.py | https://github.com/huggingface/transformers/blob/master/utils/release.py | Apache-2.0 |
def pre_release_work(patch: bool = False):
"""
Do all the necessary pre-release steps:
- figure out the next minor release version and ask confirmation
- update the version everywhere
- clean-up the model list in the main README
Args:
patch (`bool`, *optional*, defaults to `False`): Whe... |
Do all the necessary pre-release steps:
- figure out the next minor release version and ask confirmation
- update the version everywhere
- clean-up the model list in the main README
Args:
patch (`bool`, *optional*, defaults to `False`): Whether or not this is a patch release.
| pre_release_work | python | huggingface/transformers | utils/release.py | https://github.com/huggingface/transformers/blob/master/utils/release.py | Apache-2.0 |
def post_release_work():
"""
Do all the necessary post-release steps:
- figure out the next dev version and ask confirmation
- update the version everywhere
- clean-up the model list in the main README
"""
# First let's get the current version
current_version = get_version()
dev_vers... |
Do all the necessary post-release steps:
- figure out the next dev version and ask confirmation
- update the version everywhere
- clean-up the model list in the main README
| post_release_work | python | huggingface/transformers | utils/release.py | https://github.com/huggingface/transformers/blob/master/utils/release.py | Apache-2.0 |
def sort_auto_mapping(fname: str, overwrite: bool = False) -> Optional[bool]:
"""
Sort all auto mappings in a file.
Args:
fname (`str`): The name of the file where we want to sort auto-mappings.
overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the fil... |
Sort all auto mappings in a file.
Args:
fname (`str`): The name of the file where we want to sort auto-mappings.
overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file.
Returns:
`Optional[bool]`: Returns `None` if `overwrite=True`. Otherw... | sort_auto_mapping | python | huggingface/transformers | utils/sort_auto_mappings.py | https://github.com/huggingface/transformers/blob/master/utils/sort_auto_mappings.py | Apache-2.0 |
def sort_all_auto_mappings(overwrite: bool = False):
"""
Sort all auto mappings in the library.
Args:
overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file.
"""
fnames = [os.path.join(PATH_TO_AUTO_MODULE, f) for f in os.listdir(PATH_TO_AUTO_MODULE... |
Sort all auto mappings in the library.
Args:
overwrite (`bool`, *optional*, defaults to `False`): Whether or not to fix and overwrite the file.
| sort_all_auto_mappings | python | huggingface/transformers | utils/sort_auto_mappings.py | https://github.com/huggingface/transformers/blob/master/utils/sort_auto_mappings.py | Apache-2.0 |
def clean_code(content: str) -> str:
"""
Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern
comments or docstings).
Args:
content (`str`): The code to clean
Returns:
`str`: The cleaned code.
"""
# We need to deactivate... |
Remove docstrings, empty line or comments from some code (used to detect if a diff is real or only concern
comments or docstings).
Args:
content (`str`): The code to clean
Returns:
`str`: The cleaned code.
| clean_code | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def keep_doc_examples_only(content: str) -> str:
"""
Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc
tests or not).
Args:
content (`str`): The code to clean
Returns:
`str`: The cleaned code.
"""
# Keep doc exa... |
Remove everything from the code content except the doc examples (used to determined if a diff should trigger doc
tests or not).
Args:
content (`str`): The code to clean
Returns:
`str`: The cleaned code.
| keep_doc_examples_only | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def get_all_tests() -> List[str]:
"""
Walks the `tests` folder to return a list of files/subfolders. This is used to split the tests to run when using
parallelism. The split is:
- folders under `tests`: (`tokenization`, `pipelines`, etc) except the subfolder `models` is excluded.
- folders under `t... |
Walks the `tests` folder to return a list of files/subfolders. This is used to split the tests to run when using
parallelism. The split is:
- folders under `tests`: (`tokenization`, `pipelines`, etc) except the subfolder `models` is excluded.
- folders under `tests/models`: `bert`, `gpt2`, etc.
- ... | get_all_tests | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def get_all_doctest_files() -> List[str]:
"""
Return the complete list of python and Markdown files on which we run doctest.
At this moment, we restrict this to only take files from `src/` or `docs/source/en/` that are not in `utils/not_doctested.txt`.
Returns:
`List[str]`: The complete list o... |
Return the complete list of python and Markdown files on which we run doctest.
At this moment, we restrict this to only take files from `src/` or `docs/source/en/` that are not in `utils/not_doctested.txt`.
Returns:
`List[str]`: The complete list of Python and Markdown files on which we run docte... | get_all_doctest_files | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def extract_imports(module_fname: str, cache: Optional[Dict[str, List[str]]] = None) -> List[str]:
"""
Get the imports a given module makes.
Args:
module_fname (`str`):
The name of the file of the module where we want to look at the imports (given relative to the root of
the... |
Get the imports a given module makes.
Args:
module_fname (`str`):
The name of the file of the module where we want to look at the imports (given relative to the root of
the repo).
cache (Dictionary `str` to `List[str]`, *optional*):
To speed up this function... | extract_imports | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def get_module_dependencies(module_fname: str, cache: Optional[Dict[str, List[str]]] = None) -> List[str]:
"""
Refines the result of `extract_imports` to remove subfolders and get a proper list of module filenames: if a file
as an import `from utils import Foo, Bar`, with `utils` being a subfolder containin... |
Refines the result of `extract_imports` to remove subfolders and get a proper list of module filenames: if a file
as an import `from utils import Foo, Bar`, with `utils` being a subfolder containing many files, this will traverse
the `utils` init file to check where those dependencies come from: for instan... | get_module_dependencies | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def create_reverse_dependency_tree() -> List[Tuple[str, str]]:
"""
Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files.
"""
cache = {}
all_modules = list(PATH_TO_TRANFORMERS.glob("**/*.py"))
all_modules = [x for x in all_modules if ... |
Create a list of all edges (a, b) which mean that modifying a impacts b with a going over all module and test files.
| create_reverse_dependency_tree | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def get_tree_starting_at(module: str, edges: List[Tuple[str, str]]) -> List[Union[str, List[str]]]:
"""
Returns the tree starting at a given module following all edges.
Args:
module (`str`): The module that will be the root of the subtree we want.
eges (`List[Tuple[str, str]]`): The list of... |
Returns the tree starting at a given module following all edges.
Args:
module (`str`): The module that will be the root of the subtree we want.
eges (`List[Tuple[str, str]]`): The list of all edges of the tree.
Returns:
`List[Union[str, List[str]]]`: The tree to print in the follo... | get_tree_starting_at | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def print_tree_deps_of(module, all_edges=None):
"""
Prints the tree of modules depending on a given module.
Args:
module (`str`): The module that will be the root of the subtree we want.
all_eges (`List[Tuple[str, str]]`, *optional*):
The list of all edges of the tree. Will be s... |
Prints the tree of modules depending on a given module.
Args:
module (`str`): The module that will be the root of the subtree we want.
all_eges (`List[Tuple[str, str]]`, *optional*):
The list of all edges of the tree. Will be set to `create_reverse_dependency_tree()` if not passed.... | print_tree_deps_of | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def init_test_examples_dependencies() -> Tuple[Dict[str, List[str]], List[str]]:
"""
The test examples do not import from the examples (which are just scripts, not modules) so we need some extra
care initializing the dependency map, which is the goal of this function. It initializes the dependency map for
... |
The test examples do not import from the examples (which are just scripts, not modules) so we need some extra
care initializing the dependency map, which is the goal of this function. It initializes the dependency map for
example files by linking each example to the example test file for the example framew... | init_test_examples_dependencies | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def create_reverse_dependency_map() -> Dict[str, List[str]]:
"""
Create the dependency map from module/test filename to the list of modules/tests that depend on it recursively.
Returns:
`Dict[str, List[str]]`: The reverse dependency map as a dictionary mapping filenames to all the filenames
... |
Create the dependency map from module/test filename to the list of modules/tests that depend on it recursively.
Returns:
`Dict[str, List[str]]`: The reverse dependency map as a dictionary mapping filenames to all the filenames
depending on it recursively. This way the tests impacted by a chang... | create_reverse_dependency_map | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def create_module_to_test_map(
reverse_map: Optional[Dict[str, List[str]]] = None, filter_models: bool = False
) -> Dict[str, List[str]]:
"""
Extract the tests from the reverse_dependency_map and potentially filters the model tests.
Args:
reverse_map (`Dict[str, List[str]]`, *optional*):
... |
Extract the tests from the reverse_dependency_map and potentially filters the model tests.
Args:
reverse_map (`Dict[str, List[str]]`, *optional*):
The reverse dependency map as created by `create_reverse_dependency_map`. Will default to the result of
that function if not provid... | create_module_to_test_map | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def filter_tests(output_file: str, filters: List[str]):
"""
Reads the content of the output file and filters out all the tests in a list of given folders.
Args:
output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher.
filters (`List[str]`): A list of folders t... |
Reads the content of the output file and filters out all the tests in a list of given folders.
Args:
output_file (`str` or `os.PathLike`): The path to the output file of the tests fetcher.
filters (`List[str]`): A list of folders to filter.
| filter_tests | python | huggingface/transformers | utils/tests_fetcher.py | https://github.com/huggingface/transformers/blob/master/utils/tests_fetcher.py | Apache-2.0 |
def camel_case_split(identifier: str) -> List[str]:
"""
Split a camel-cased name into words.
Args:
identifier (`str`): The camel-cased name to parse.
Returns:
`List[str]`: The list of words in the identifier (as separated by capital letters).
Example:
```py
>>> camel_case... |
Split a camel-cased name into words.
Args:
identifier (`str`): The camel-cased name to parse.
Returns:
`List[str]`: The list of words in the identifier (as separated by capital letters).
Example:
```py
>>> camel_case_split("CamelCasedClass")
["Camel", "Cased", "Class"]
... | camel_case_split | python | huggingface/transformers | utils/update_metadata.py | https://github.com/huggingface/transformers/blob/master/utils/update_metadata.py | Apache-2.0 |
def get_frameworks_table() -> pd.DataFrame:
"""
Generates a dataframe containing the supported auto classes for each model type, using the content of the auto
modules.
"""
# Dictionary model names to config.
config_maping_names = transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_... |
Generates a dataframe containing the supported auto classes for each model type, using the content of the auto
modules.
| get_frameworks_table | python | huggingface/transformers | utils/update_metadata.py | https://github.com/huggingface/transformers/blob/master/utils/update_metadata.py | Apache-2.0 |
def update_pipeline_and_auto_class_table(table: Dict[str, Tuple[str, str]]) -> Dict[str, Tuple[str, str]]:
"""
Update the table mapping models to pipelines and auto classes without removing old keys if they don't exist anymore.
Args:
table (`Dict[str, Tuple[str, str]]`):
The existing ta... |
Update the table mapping models to pipelines and auto classes without removing old keys if they don't exist anymore.
Args:
table (`Dict[str, Tuple[str, str]]`):
The existing table mapping model names to a tuple containing the pipeline tag and the auto-class name with
which they... | update_pipeline_and_auto_class_table | python | huggingface/transformers | utils/update_metadata.py | https://github.com/huggingface/transformers/blob/master/utils/update_metadata.py | Apache-2.0 |
def check_pipeline_tags():
"""
Check all pipeline tags are properly defined in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant of this script.
"""
in_table = {tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS}
pipeline_tasks = transformers_module.pipelines.SUPPORTED_TASKS
missing = []
f... |
Check all pipeline tags are properly defined in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant of this script.
| check_pipeline_tags | python | huggingface/transformers | utils/update_metadata.py | https://github.com/huggingface/transformers/blob/master/utils/update_metadata.py | Apache-2.0 |
async def lifespan(app: FastAPI):
"""
An asynchronous context manager for managing the lifecycle of the FastAPI app.
It ensures that GPU memory is cleared after the app's lifecycle ends, which is essential for efficient resource management in GPU environments.
"""
yield
if torch.cuda.is_availabl... |
An asynchronous context manager for managing the lifecycle of the FastAPI app.
It ensures that GPU memory is cleared after the app's lifecycle ends, which is essential for efficient resource management in GPU environments.
| lifespan | python | THUDM/CogVLM2 | basic_demo/openai_api_demo.py | https://github.com/THUDM/CogVLM2/blob/master/basic_demo/openai_api_demo.py | Apache-2.0 |
async def list_models():
"""
An endpoint to list available models. It returns a list of model cards.
This is useful for clients to query and understand what models are available for use.
"""
model_card = ModelCard(id="cogvlm2-19b")
return ModelList(data=[model_card]) |
An endpoint to list available models. It returns a list of model cards.
This is useful for clients to query and understand what models are available for use.
| list_models | python | THUDM/CogVLM2 | basic_demo/openai_api_demo.py | https://github.com/THUDM/CogVLM2/blob/master/basic_demo/openai_api_demo.py | Apache-2.0 |
def generate_cogvlm(model: AutoModelForCausalLM, tokenizer: AutoTokenizer, params: dict):
"""
Generates a response using the CogVLM2 model. It processes the chat history and image data, if any,
and then invokes the model to generate a response.
"""
response = None
for response in generate_stre... |
Generates a response using the CogVLM2 model. It processes the chat history and image data, if any,
and then invokes the model to generate a response.
| generate_cogvlm | python | THUDM/CogVLM2 | basic_demo/openai_api_demo.py | https://github.com/THUDM/CogVLM2/blob/master/basic_demo/openai_api_demo.py | Apache-2.0 |
def unboxn(vin, n):
"""vin = (batch, h, w, depth), returns vout = (batch, n*h, n*w, depth), each pixel is duplicated."""
s = tf.shape(vin)
vout = tf.concat([vin] * (n ** 2), 0) # Poor man's replacement for tf.tile (required for Adversarial Training support).
vout = tf.reshape(vout, [s[0] * (n ** 2), s[... | vin = (batch, h, w, depth), returns vout = (batch, n*h, n*w, depth), each pixel is duplicated. | unboxn | python | carpedm20/BEGAN-tensorflow | layers.py | https://github.com/carpedm20/BEGAN-tensorflow/blob/master/layers.py | Apache-2.0 |
def boxn(vin, n):
"""vin = (batch, h, w, depth), returns vout = (batch, h//n, w//n, depth), each pixel is averaged."""
if n == 1:
return vin
s = tf.shape(vin)
vout = tf.reshape(vin, [s[0], s[1] // n, n, s[2] // n, n, s[3]])
vout = tf.reduce_mean(vout, [2, 4])
return vout | vin = (batch, h, w, depth), returns vout = (batch, h//n, w//n, depth), each pixel is averaged. | boxn | python | carpedm20/BEGAN-tensorflow | layers.py | https://github.com/carpedm20/BEGAN-tensorflow/blob/master/layers.py | Apache-2.0 |
def make_grid(tensor, nrow=8, padding=2,
normalize=False, scale_each=False):
"""Code based on https://github.com/pytorch/vision/blob/master/torchvision/utils.py"""
nmaps = tensor.shape[0]
xmaps = min(nrow, nmaps)
ymaps = int(math.ceil(float(nmaps) / xmaps))
height, width = int(tensor.s... | Code based on https://github.com/pytorch/vision/blob/master/torchvision/utils.py | make_grid | python | carpedm20/BEGAN-tensorflow | utils.py | https://github.com/carpedm20/BEGAN-tensorflow/blob/master/utils.py | Apache-2.0 |
def index():
"""Searches the database for entries, then displays them."""
entries = db.session.query(models.Post)
return render_template("index.html", entries=entries) | Searches the database for entries, then displays them. | index | python | mjhea0/flaskr-tdd | project/app.py | https://github.com/mjhea0/flaskr-tdd/blob/master/project/app.py | MIT |
def add_entry():
"""Adds new post to the database."""
if not session.get("logged_in"):
abort(401)
new_entry = models.Post(request.form["title"], request.form["text"])
db.session.add(new_entry)
db.session.commit()
flash("New entry was successfully posted")
return redirect(url_for("ind... | Adds new post to the database. | add_entry | python | mjhea0/flaskr-tdd | project/app.py | https://github.com/mjhea0/flaskr-tdd/blob/master/project/app.py | MIT |
def test_login_logout(client):
"""Test login and logout using helper functions"""
rv = login(client, app.config["USERNAME"], app.config["PASSWORD"])
assert b"You were logged in" in rv.data
rv = logout(client)
assert b"You were logged out" in rv.data
rv = login(client, app.config["USERNAME"] + "x... | Test login and logout using helper functions | test_login_logout | python | mjhea0/flaskr-tdd | tests/app_test.py | https://github.com/mjhea0/flaskr-tdd/blob/master/tests/app_test.py | MIT |
def test_messages(client):
"""Ensure that user can post messages"""
login(client, app.config["USERNAME"], app.config["PASSWORD"])
rv = client.post(
"/add",
data=dict(title="<Hello>", text="<strong>HTML</strong> allowed here"),
follow_redirects=True,
)
assert b"No entries here... | Ensure that user can post messages | test_messages | python | mjhea0/flaskr-tdd | tests/app_test.py | https://github.com/mjhea0/flaskr-tdd/blob/master/tests/app_test.py | MIT |
def test_delete_message(client):
"""Ensure the messages are being deleted"""
rv = client.get("/delete/1")
data = json.loads(rv.data)
assert data["status"] == 0
login(client, app.config["USERNAME"], app.config["PASSWORD"])
rv = client.get("/delete/1")
data = json.loads(rv.data)
assert dat... | Ensure the messages are being deleted | test_delete_message | python | mjhea0/flaskr-tdd | tests/app_test.py | https://github.com/mjhea0/flaskr-tdd/blob/master/tests/app_test.py | MIT |
def unique_config_sections(config_file):
"""Convert all config sections to have unique names.
Adds unique suffixes to config sections for compability with configparser.
"""
section_counters = defaultdict(int)
output_stream = io.StringIO()
with open(config_file) as fin:
for line in fin:
... | Convert all config sections to have unique names.
Adds unique suffixes to config sections for compability with configparser.
| unique_config_sections | python | qqwweee/keras-yolo3 | convert.py | https://github.com/qqwweee/keras-yolo3/blob/master/convert.py | MIT |
def create_tiny_model(input_shape, anchors, num_classes, load_pretrained=True, freeze_body=2,
weights_path='model_data/tiny_yolo_weights.h5'):
'''create the training model, for Tiny YOLOv3'''
K.clear_session() # get a new session
image_input = Input(shape=(None, None, 3))
h, w = input_shape
... | create the training model, for Tiny YOLOv3 | create_tiny_model | python | qqwweee/keras-yolo3 | train.py | https://github.com/qqwweee/keras-yolo3/blob/master/train.py | MIT |
def DarknetConv2D(*args, **kwargs):
"""Wrapper to set Darknet parameters for Convolution2D."""
darknet_conv_kwargs = {'kernel_regularizer': l2(5e-4)}
darknet_conv_kwargs['padding'] = 'valid' if kwargs.get('strides')==(2,2) else 'same'
darknet_conv_kwargs.update(kwargs)
return Conv2D(*args, **darknet... | Wrapper to set Darknet parameters for Convolution2D. | DarknetConv2D | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def DarknetConv2D_BN_Leaky(*args, **kwargs):
"""Darknet Convolution2D followed by BatchNormalization and LeakyReLU."""
no_bias_kwargs = {'use_bias': False}
no_bias_kwargs.update(kwargs)
return compose(
DarknetConv2D(*args, **no_bias_kwargs),
BatchNormalization(),
LeakyReLU(alpha=... | Darknet Convolution2D followed by BatchNormalization and LeakyReLU. | DarknetConv2D_BN_Leaky | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def resblock_body(x, num_filters, num_blocks):
'''A series of resblocks starting with a downsampling Convolution2D'''
# Darknet uses left and top padding instead of 'same' mode
x = ZeroPadding2D(((1,0),(1,0)))(x)
x = DarknetConv2D_BN_Leaky(num_filters, (3,3), strides=(2,2))(x)
for i in range(num_blo... | A series of resblocks starting with a downsampling Convolution2D | resblock_body | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def yolo_body(inputs, num_anchors, num_classes):
"""Create YOLO_V3 model CNN body in Keras."""
darknet = Model(inputs, darknet_body(inputs))
x, y1 = make_last_layers(darknet.output, 512, num_anchors*(num_classes+5))
x = compose(
DarknetConv2D_BN_Leaky(256, (1,1)),
UpSampling2D(2... | Create YOLO_V3 model CNN body in Keras. | yolo_body | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def tiny_yolo_body(inputs, num_anchors, num_classes):
'''Create Tiny YOLO_v3 model CNN body in keras.'''
x1 = compose(
DarknetConv2D_BN_Leaky(16, (3,3)),
MaxPooling2D(pool_size=(2,2), strides=(2,2), padding='same'),
DarknetConv2D_BN_Leaky(32, (3,3)),
MaxPooling2D(... | Create Tiny YOLO_v3 model CNN body in keras. | tiny_yolo_body | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def yolo_head(feats, anchors, num_classes, input_shape, calc_loss=False):
"""Convert final layer features to bounding box parameters."""
num_anchors = len(anchors)
# Reshape to batch, height, width, num_anchors, box_params.
anchors_tensor = K.reshape(K.constant(anchors), [1, 1, 1, num_anchors, 2])
... | Convert final layer features to bounding box parameters. | yolo_head | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def yolo_eval(yolo_outputs,
anchors,
num_classes,
image_shape,
max_boxes=20,
score_threshold=.6,
iou_threshold=.5):
"""Evaluate YOLO model on given input and return filtered boxes."""
num_layers = len(yolo_outputs)
anchor_ma... | Evaluate YOLO model on given input and return filtered boxes. | yolo_eval | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def preprocess_true_boxes(true_boxes, input_shape, anchors, num_classes):
'''Preprocess true boxes to training input format
Parameters
----------
true_boxes: array, shape=(m, T, 5)
Absolute x_min, y_min, x_max, y_max, class_id relative to input_shape.
input_shape: array-like, hw, multiples ... | Preprocess true boxes to training input format
Parameters
----------
true_boxes: array, shape=(m, T, 5)
Absolute x_min, y_min, x_max, y_max, class_id relative to input_shape.
input_shape: array-like, hw, multiples of 32
anchors: array, shape=(N, 2), wh
num_classes: integer
Returns
... | preprocess_true_boxes | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def box_iou(b1, b2):
'''Return iou tensor
Parameters
----------
b1: tensor, shape=(i1,...,iN, 4), xywh
b2: tensor, shape=(j, 4), xywh
Returns
-------
iou: tensor, shape=(i1,...,iN, j)
'''
# Expand dim to apply broadcasting.
b1 = K.expand_dims(b1, -2)
b1_xy = b1[..., :... | Return iou tensor
Parameters
----------
b1: tensor, shape=(i1,...,iN, 4), xywh
b2: tensor, shape=(j, 4), xywh
Returns
-------
iou: tensor, shape=(i1,...,iN, j)
| box_iou | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def yolo_loss(args, anchors, num_classes, ignore_thresh=.5, print_loss=False):
'''Return yolo_loss tensor
Parameters
----------
yolo_outputs: list of tensor, the output of yolo_body or tiny_yolo_body
y_true: list of array, the output of preprocess_true_boxes
anchors: array, shape=(N, 2), wh
... | Return yolo_loss tensor
Parameters
----------
yolo_outputs: list of tensor, the output of yolo_body or tiny_yolo_body
y_true: list of array, the output of preprocess_true_boxes
anchors: array, shape=(N, 2), wh
num_classes: integer
ignore_thresh: float, the iou threshold whether to ignore ob... | yolo_loss | python | qqwweee/keras-yolo3 | yolo3/model.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/model.py | MIT |
def compose(*funcs):
"""Compose arbitrarily many functions, evaluated left to right.
Reference: https://mathieularose.com/function-composition-in-python/
"""
# return lambda x: reduce(lambda v, f: f(v), funcs, x)
if funcs:
return reduce(lambda f, g: lambda *a, **kw: g(f(*a, **kw)), funcs)
... | Compose arbitrarily many functions, evaluated left to right.
Reference: https://mathieularose.com/function-composition-in-python/
| compose | python | qqwweee/keras-yolo3 | yolo3/utils.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/utils.py | MIT |
def letterbox_image(image, size):
'''resize image with unchanged aspect ratio using padding'''
iw, ih = image.size
w, h = size
scale = min(w/iw, h/ih)
nw = int(iw*scale)
nh = int(ih*scale)
image = image.resize((nw,nh), Image.BICUBIC)
new_image = Image.new('RGB', size, (128,128,128))
... | resize image with unchanged aspect ratio using padding | letterbox_image | python | qqwweee/keras-yolo3 | yolo3/utils.py | https://github.com/qqwweee/keras-yolo3/blob/master/yolo3/utils.py | MIT |
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.