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 is_uri(path: str) -> bool: """Check if the path is a URI. Args: path (str): The path to check. Returns: bool: Whether the path is a URI. """ backend, _, _ = parse_uri(path) return backend != ''
Check if the path is a URI. Args: path (str): The path to check. Returns: bool: Whether the path is a URI.
is_uri
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def parse_uri(uri: str) -> tuple[str, str, str]: """Uses :py:func:`urllib.parse.urlparse` to parse the provided URI. Args: uri (str): The provided URI string Returns: tuple[str, str, str]: A tuple containing the backend (e.g. s3), bucket name, and path. Backen...
Uses :py:func:`urllib.parse.urlparse` to parse the provided URI. Args: uri (str): The provided URI string Returns: tuple[str, str, str]: A tuple containing the backend (e.g. s3), bucket name, and path. Backend name will be empty string if the input is a local path...
parse_uri
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def maybe_create_object_store_from_uri(uri: str) -> Optional[ObjectStore]: """Automatically creates an :class:`composer.utils.ObjectStore` from supported URI formats. Currently supported backends are ``s3://``, ``oci://``, and local paths (in which case ``None`` will be returned) Args: uri (str): ...
Automatically creates an :class:`composer.utils.ObjectStore` from supported URI formats. Currently supported backends are ``s3://``, ``oci://``, and local paths (in which case ``None`` will be returned) Args: uri (str): The path to (maybe) create an :class:`composer.utils.ObjectStore` from. Raise...
maybe_create_object_store_from_uri
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def maybe_create_remote_uploader_downloader_from_uri( uri: str, loggers: list[LoggerDestination], ) -> Optional['RemoteUploaderDownloader']: """Automatically creates a :class:`composer.loggers.RemoteUploaderDownloader` from supported URI formats. Currently supported backends are ``s3://``, ``oci://``, ...
Automatically creates a :class:`composer.loggers.RemoteUploaderDownloader` from supported URI formats. Currently supported backends are ``s3://``, ``oci://``, and local paths (in which case ``None`` will be returned) Args: uri (str):The path to (maybe) create a :class:`composer.loggers.RemoteUploaderD...
maybe_create_remote_uploader_downloader_from_uri
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def list_remote_objects(remote_path: str) -> list[str]: """List objects at the remote path. Args: remote_path (str): Remote object store path. Returns: A list of objects at the remote path. """ object_store = maybe_create_object_store_from_uri(remote_path) if object_store is No...
List objects at the remote path. Args: remote_path (str): Remote object store path. Returns: A list of objects at the remote path.
list_remote_objects
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def validate_remote_path(): """Entry point to composer_validate_remote_path cli command. Validates a remote path. If the remote path is valid, prints a list of objects at the path. Otherwise, raises an error. """ import sys args = sys.argv if len(args) == 1: raise ValueError('Pl...
Entry point to composer_validate_remote_path cli command. Validates a remote path. If the remote path is valid, prints a list of objects at the path. Otherwise, raises an error.
validate_remote_path
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def get_file( path: str, destination: str, object_store: Optional[Union[ObjectStore, LoggerDestination]] = None, overwrite: bool = False, progress_bar: bool = True, ): """Get a file from a local folder, URL, or object store. Args: path (str): The path to the file to retrieve. ...
Get a file from a local folder, URL, or object store. Args: path (str): The path to the file to retrieve. * If ``object_store`` is specified, then the ``path`` should be the object name for the file to get. Do not include the cloud provider or bucket name. * If...
get_file
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def create_symlink_file( existing_path: str, destination_filename: Union[str, pathlib.Path], ): """Create a symlink file, which can be followed by :func:`get_file`. Unlike unix symlinks, symlink files can be created by this function are normal text files and can be uploaded to object stores via :me...
Create a symlink file, which can be followed by :func:`get_file`. Unlike unix symlinks, symlink files can be created by this function are normal text files and can be uploaded to object stores via :meth:`.ObjectStore.upload_object` or loggers via :meth:`.Logger.upload_file` that otherwise would not support...
create_symlink_file
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def validate_credentials( remote_backend: ObjectStore, remote_file_name_to_test: str, ): """Upload a tiny text file to test if the credentials are setup correctly.""" # Validates the credentials by attempting to touch a file in the bucket # raises an error if there was a credentials failure. wit...
Upload a tiny text file to test if the credentials are setup correctly.
validate_credentials
python
mosaicml/composer
composer/utils/file_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py
Apache-2.0
def count_op_instances(gm: GraphModule, ops: Union[Callable, str, list[Union[Callable, str]]]) -> int: """Counts the number of instances of ``op`` in ``gm``. .. rubric:: Example .. testsetup:: import operator import torch from torch.fx import symbolic_trace from composer.u...
Counts the number of instances of ``op`` in ``gm``. .. rubric:: Example .. testsetup:: import operator import torch from torch.fx import symbolic_trace from composer.utils.fx_utils import count_op_instances .. doctest:: >>> class M(torch.nn.Module): ... ...
count_op_instances
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def replace_op( gm: GraphModule, src_ops: Union[Callable, str, list[Union[Callable, str]]], tgt_op: Callable[..., Any], ) -> GraphModule: """Replace a single operator, torch method or function with another. .. rubric:: Example .. testsetup:: import operator import torch ...
Replace a single operator, torch method or function with another. .. rubric:: Example .. testsetup:: import operator import torch from torch.fx import symbolic_trace from composer.utils.fx_utils import replace_op, count_op_instances .. doctest:: >>> class M(torch...
replace_op
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def _get_residual_block_nodes(nodeLHS: Node, nodeRHS: Node) -> tuple[list[Node], list[Node]]: """Walk backwards from nodeLHS and nodeRSH to the root and construct lists of their parents. Arguments: nodeLHS (Node): left-hand side node for a binary operator nodeRHS (Node): right-hand side node fo...
Walk backwards from nodeLHS and nodeRSH to the root and construct lists of their parents. Arguments: nodeLHS (Node): left-hand side node for a binary operator nodeRHS (Node): right-hand side node for a binary operator Returns: (lhsAncestors, rhsAncestors): Two lists of nodes containing...
_get_residual_block_nodes
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def _attach_tag(nodes: list[Node], tag: str): """Attach tag to the given nodes for the splitter.""" for node in nodes: node.tag = tag # type: ignore[attr-defined]
Attach tag to the given nodes for the splitter.
_attach_tag
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def _get_residual_modules(gm: GraphModule, node: Node) -> tuple[Optional[GraphModule], Optional[GraphModule], int]: """Returns GraphModules for the main and residual branches. node.op is assumed to be a call_module """ pattern = re.compile(r'non_res_(\d+)|residual_(\d+)') matches = pattern.match(st...
Returns GraphModules for the main and residual branches. node.op is assumed to be a call_module
_get_residual_modules
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def _replace_residual_pattern( gm: GraphModule, original_node: Node, replacement_module: str, has_residual_ops: bool = False, ) -> None: """Replaces main, residual and add_node with the ``replacement_module``. ``replacement_module`` is already added to the gm. """ insert_node = original...
Replaces main, residual and add_node with the ``replacement_module``. ``replacement_module`` is already added to the gm.
_replace_residual_pattern
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def apply_stochastic_residual(gm: GraphModule, drop_rate: float = 0.2) -> tuple[GraphModule, int]: """Detect and replace residual pattern with their stochastic equivalent. Arguments: gm (GraphModule): The source FX-traced graph. It can be the whole model symbolically traced. Returns: Graph...
Detect and replace residual pattern with their stochastic equivalent. Arguments: gm (GraphModule): The source FX-traced graph. It can be the whole model symbolically traced. Returns: GraphModule: Modified GraphModule that has stochastic residual connections.
apply_stochastic_residual
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def _can_linears_be_fused(linear_nodes: list[Node], all_modules: Mapping[str, nn.Module]) -> bool: """Check if all the linears have bias.""" # Forcing node.target to str is fine here as we are dealing with nn.Modules # and their target is a str. bias = all_modules[str(linear_nodes[0].target)].bias is No...
Check if all the linears have bias.
_can_linears_be_fused
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def _create_fused_linear( linear_nodes: list[Node], all_modules: Mapping[str, nn.Module], keep_weights: bool = False, ) -> tuple[nn.Module, list[int]]: """Check if the linears can be fused. If the linears can be fused, create a fused nn.Linear instance and return it. """ if keep_weights: ...
Check if the linears can be fused. If the linears can be fused, create a fused nn.Linear instance and return it.
_create_fused_linear
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def fuse_parallel_linears(gm: GraphModule, keep_weights: bool = False) -> GraphModule: """If there are parallel linears in the model, fuse them together. .. rubric:: Example .. testsetup:: import torch import torch.nn as nn from torch.fx import symbolic_trace from composer...
If there are parallel linears in the model, fuse them together. .. rubric:: Example .. testsetup:: import torch import torch.nn as nn from torch.fx import symbolic_trace from composer.utils.fx_utils import count_op_instances, fuse_parallel_linears .. doctest:: >>...
fuse_parallel_linears
python
mosaicml/composer
composer/utils/fx_utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/fx_utils.py
Apache-2.0
def import_object(name: str) -> Any: """Dynamically import a Python object (e.g. class, function, ...). .. note:: To dynamically import a module, use :func:`importlib.import_module`. Args: name (str): The path to the Python object to import. Separate the module name and class...
Dynamically import a Python object (e.g. class, function, ...). .. note:: To dynamically import a module, use :func:`importlib.import_module`. Args: name (str): The path to the Python object to import. Separate the module name and class name with a ``':'`` (e.g. ``'path.to.module...
import_object
python
mosaicml/composer
composer/utils/import_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/import_helpers.py
Apache-2.0
def _move_sample_input_to_device( sample_input: Optional[Union[torch.Tensor, dict, list, tuple]], device: Device, ) -> Optional[Union[torch.Tensor, dict, list, tuple]]: """Handle moving sample_input of various types to a device. If possible, avoids creating copies of the input.""" output = None if i...
Handle moving sample_input of various types to a device. If possible, avoids creating copies of the input.
_move_sample_input_to_device
python
mosaicml/composer
composer/utils/inference.py
https://github.com/mosaicml/composer/blob/master/composer/utils/inference.py
Apache-2.0
def export_for_inference( model: nn.Module, save_format: Union[str, ExportFormat], save_path: str, save_object_store: Optional[ObjectStore] = None, sample_input: Optional[Any] = None, dynamic_axes: Optional[Any] = None, surgery_algs: Optional[Union[Callable[[nn.Module], nn.Module], Sequence[...
Export a model for inference. Args: model (nn.Module): An instance of nn.Module. Please note that model is not modified inplace. Instead, export-related transformations are applied to a copy of the model. save_format (Union[str, ExportFormat]): Format to export to. Either ``"torchscri...
export_for_inference
python
mosaicml/composer
composer/utils/inference.py
https://github.com/mosaicml/composer/blob/master/composer/utils/inference.py
Apache-2.0
def export_with_logger( model: nn.Module, save_format: Union[str, ExportFormat], save_path: str, logger: Logger, save_object_store: Optional[ObjectStore] = None, sample_input: Optional[Any] = None, transforms: Optional[Sequence[Transform]] = None, input_names: Optional[Sequence[str]] = N...
Helper method for exporting a model for inference. Exports the model to: 1) save_object_store, if one is provided, 2) logger.upload_file(save_path), if (1) does not apply and the logger has a destination that supports file uploading, 3) locally, if (1) and (2) do not apply. Args: model (nn...
export_with_logger
python
mosaicml/composer
composer/utils/inference.py
https://github.com/mosaicml/composer/blob/master/composer/utils/inference.py
Apache-2.0
def map_collection(collection, map_fn) -> Any: """Applies ``map_fn`` on each element in ``collection``. * If ``collection`` is a tuple or list of elements, ``map_fn`` is applied on each element, and a tuple or list, respectively, containing mapped values is returned. * If ``collection`` is a dictiona...
Applies ``map_fn`` on each element in ``collection``. * If ``collection`` is a tuple or list of elements, ``map_fn`` is applied on each element, and a tuple or list, respectively, containing mapped values is returned. * If ``collection`` is a dictionary, ``map_fn`` is applied on each value, and a diction...
map_collection
python
mosaicml/composer
composer/utils/iter_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/iter_helpers.py
Apache-2.0
def ensure_tuple(x) -> tuple[Any, ...]: """Converts ``x`` into a tuple. * If ``x`` is ``None``, then ``tuple()`` is returned. * If ``x`` is a tuple, then ``x`` is returned as-is. * If ``x`` is a list, then ``tuple(x)`` is returned. * If ``x`` is a dict, then ``tuple(v for v in x.values())`` is retu...
Converts ``x`` into a tuple. * If ``x`` is ``None``, then ``tuple()`` is returned. * If ``x`` is a tuple, then ``x`` is returned as-is. * If ``x`` is a list, then ``tuple(x)`` is returned. * If ``x`` is a dict, then ``tuple(v for v in x.values())`` is returned. Otherwise, a single element tuple of...
ensure_tuple
python
mosaicml/composer
composer/utils/iter_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/iter_helpers.py
Apache-2.0
def iterate_with_callback(iterator, total_len, callback=None): """Invoke ``callback`` after each chunk is yielded from ``iterator``. Args: iterator (Iterator): The iterator, which should yield chunks of data. total_len (int): The total length of the iterator. callback (Callable[[int, in...
Invoke ``callback`` after each chunk is yielded from ``iterator``. Args: iterator (Iterator): The iterator, which should yield chunks of data. total_len (int): The total length of the iterator. callback (Callable[[int, int], None], optional): The callback to invoke after each ch...
iterate_with_callback
python
mosaicml/composer
composer/utils/iter_helpers.py
https://github.com/mosaicml/composer/blob/master/composer/utils/iter_helpers.py
Apache-2.0
def create_interval_scheduler( interval: Union[str, int, 'Time'], include_end_of_training: bool = True, checkpoint_events: bool = True, final_events: Optional[set['Event']] = None, ) -> Callable[['State', 'Event'], bool]: """Helper function to create a scheduler according to a specified interval. ...
Helper function to create a scheduler according to a specified interval. Args: interval (Union[str, int, :class:`.Time`]): If an integer, it will be assumed to be in :attr:`.TimeUnit.EPOCH`. Otherwise, the unit must be either :attr:`.TimeUnit.ITERATION`, :attr:`.TimeUnit.EPOCH`, :at...
create_interval_scheduler
python
mosaicml/composer
composer/utils/misc.py
https://github.com/mosaicml/composer/blob/master/composer/utils/misc.py
Apache-2.0
def is_model_fsdp(model: torch.nn.Module) -> bool: """Whether ``model`` is an instance of a :class:`.FullyShardedDataParallel`.""" try: from torch.distributed.fsdp import FullyShardedDataParallel as FSDP if isinstance(model, FSDP): return True # Check if model is wrapped wi...
Whether ``model`` is an instance of a :class:`.FullyShardedDataParallel`.
is_model_fsdp
python
mosaicml/composer
composer/utils/misc.py
https://github.com/mosaicml/composer/blob/master/composer/utils/misc.py
Apache-2.0
def is_notebook(): """Whether Composer is running in a IPython/Jupyter Notebook.""" try: __IPYTHON__ # type: ignore return True except NameError: return False
Whether Composer is running in a IPython/Jupyter Notebook.
is_notebook
python
mosaicml/composer
composer/utils/misc.py
https://github.com/mosaicml/composer/blob/master/composer/utils/misc.py
Apache-2.0
def warning_on_one_line( message: str, category: type[Warning], filename: str, lineno: int, file=None, line=None, ): """Force Python warnings to consolidate into one line.""" # From https://stackoverflow.com/questions/26430861/make-pythons-warnings-warn-not-mention-itself return f'{c...
Force Python warnings to consolidate into one line.
warning_on_one_line
python
mosaicml/composer
composer/utils/misc.py
https://github.com/mosaicml/composer/blob/master/composer/utils/misc.py
Apache-2.0
def get_free_tcp_port() -> int: """Get free socket port to use as MASTER_PORT.""" # from https://www.programcreek.com/python/?CodeExample=get+free+port tcp = socket.socket(socket.AF_INET, socket.SOCK_STREAM) tcp.bind(('', 0)) _, port = tcp.getsockname() tcp.close() return port
Get free socket port to use as MASTER_PORT.
get_free_tcp_port
python
mosaicml/composer
composer/utils/misc.py
https://github.com/mosaicml/composer/blob/master/composer/utils/misc.py
Apache-2.0
def model_eval_mode(model: torch.nn.Module): """Set model.eval() for context duration, restoring model status at end.""" is_training = model.training try: model.eval() yield finally: model.train(mode=is_training)
Set model.eval() for context duration, restoring model status at end.
model_eval_mode
python
mosaicml/composer
composer/utils/misc.py
https://github.com/mosaicml/composer/blob/master/composer/utils/misc.py
Apache-2.0
def partial_format(s, *args, **kwargs) -> str: """Format a string with a partial set of arguments. Since `str.format()` raises a `KeyError` if a format key is missing from the arguments, this function allows for a partial set of arguments to be provided. Any missing arguments will be left as-is in the ...
Format a string with a partial set of arguments. Since `str.format()` raises a `KeyError` if a format key is missing from the arguments, this function allows for a partial set of arguments to be provided. Any missing arguments will be left as-is in the string.
partial_format
python
mosaicml/composer
composer/utils/misc.py
https://github.com/mosaicml/composer/blob/master/composer/utils/misc.py
Apache-2.0
def add_vision_dataset_transform(dataset: VisionDataset, transform: Callable, is_tensor_transform: bool = False): """Add a transform to a dataset's collection of transforms. Args: dataset (VisionDataset): A torchvision dataset. transform (Callable): Function to be added to the dataset's collect...
Add a transform to a dataset's collection of transforms. Args: dataset (VisionDataset): A torchvision dataset. transform (Callable): Function to be added to the dataset's collection of transforms. is_tensor_transform (bool): Whether ``transform`` acts on data of the type :class:...
add_vision_dataset_transform
python
mosaicml/composer
composer/utils/misc.py
https://github.com/mosaicml/composer/blob/master/composer/utils/misc.py
Apache-2.0
def replace_module_classes( module: torch.nn.Module, policies: Mapping[type[torch.nn.Module], ReplacementFunction], optimizers: Optional[Union[Optimizer, Sequence[Optimizer]]] = None, recurse_on_replacements: bool = False, indices: Optional[dict[Any, int]] = None, ) -> dict[torch.nn.Module, torch.nn...
Modify model in-place by recursively applying replacement policies. .. rubric:: Example The following example replaces all convolution layers with linear layers, and linear layers will be replaced if there are 16 input features. Recursion occurs on replacement. * The first replacement policy replaces...
replace_module_classes
python
mosaicml/composer
composer/utils/module_surgery.py
https://github.com/mosaicml/composer/blob/master/composer/utils/module_surgery.py
Apache-2.0
def _infer_device(module: torch.nn.Module) -> Optional[torch.device]: """Attempt to infer a module's device by inspecting its parameters and buffers.""" try: p = next(itertools.chain(module.parameters(), module.buffers())) except StopIteration: return None else: return p.device
Attempt to infer a module's device by inspecting its parameters and buffers.
_infer_device
python
mosaicml/composer
composer/utils/module_surgery.py
https://github.com/mosaicml/composer/blob/master/composer/utils/module_surgery.py
Apache-2.0
def count_module_instances( module: torch.nn.Module, module_class: Union[type[torch.nn.Module], tuple[type[torch.nn.Module], ...]], ) -> int: """Counts the number of instances of ``module_class`` in ``module``, recursively. .. rubric:: Example .. testsetup:: from composer.utils.module_sur...
Counts the number of instances of ``module_class`` in ``module``, recursively. .. rubric:: Example .. testsetup:: from composer.utils.module_surgery import count_module_instances .. doctest:: >>> from torch import nn >>> module = nn.Sequential(nn.Linear(16, 32), nn.Linear(32, 64...
count_module_instances
python
mosaicml/composer
composer/utils/module_surgery.py
https://github.com/mosaicml/composer/blob/master/composer/utils/module_surgery.py
Apache-2.0
def _recur_count_module_instances( module: torch.nn.Module, module_class: Union[type[torch.nn.Module], tuple[type[torch.nn.Module], ...]], found_instances: set, ): """Counts instances of ``module_class`` in ``module``, recursively, using a set to deduplicate. We require creating a set of all found ...
Counts instances of ``module_class`` in ``module``, recursively, using a set to deduplicate. We require creating a set of all found modules of instance module_class since a model might have duplicate references to a particular module.
_recur_count_module_instances
python
mosaicml/composer
composer/utils/module_surgery.py
https://github.com/mosaicml/composer/blob/master/composer/utils/module_surgery.py
Apache-2.0
def _find_param_in_optimizer(param: torch.nn.parameter.Parameter, optimizer: Optimizer) -> int: """Returns the index of the optimizer ``param_group`` containing ``param``. Optimizers store their parameters within an iterable of ``dict``s called :attr:`~torch.optim.Optimizer.param_groups`. By default, t...
Returns the index of the optimizer ``param_group`` containing ``param``. Optimizers store their parameters within an iterable of ``dict``s called :attr:`~torch.optim.Optimizer.param_groups`. By default, there is only one group in :attr:`~torch.optim.Optimizer.param_groups` that containing all the param...
_find_param_in_optimizer
python
mosaicml/composer
composer/utils/module_surgery.py
https://github.com/mosaicml/composer/blob/master/composer/utils/module_surgery.py
Apache-2.0
def _ordered_diff(first: list, second: list) -> list: """Returns first - second while maintaining the order in first.""" second_list = set(second) return [item for item in first if item not in second_list]
Returns first - second while maintaining the order in first.
_ordered_diff
python
mosaicml/composer
composer/utils/module_surgery.py
https://github.com/mosaicml/composer/blob/master/composer/utils/module_surgery.py
Apache-2.0
def update_params_in_optimizer( old_params: Iterable[torch.nn.parameter.Parameter], new_params: Iterable[torch.nn.parameter.Parameter], optimizers: Union[Optimizer, Sequence[Optimizer]], ) -> None: r"""Remove ``old_params`` from the ``optimizers`` and insert ``new_params``. Newly added parameters w...
Remove ``old_params`` from the ``optimizers`` and insert ``new_params``. Newly added parameters will be added to the same :attr:`~torch.optim.Optimizer.param_group` as the removed parameters. A :class:`RuntimeError` will be raised if ``old_params`` is split across multiple parameter groups. This function ...
update_params_in_optimizer
python
mosaicml/composer
composer/utils/module_surgery.py
https://github.com/mosaicml/composer/blob/master/composer/utils/module_surgery.py
Apache-2.0
def from_compatible_attrs(cls, attrs: dict[str, Any]) -> 'FSDP2Config': """Create an FSDP2Config by filtering FSDP2 compatible attributes from given attrs. Only attributes that are valid for FSDP2Config will be used, and warnings will be issued for any attributes that cannot be transferred. The...
Create an FSDP2Config by filtering FSDP2 compatible attributes from given attrs. Only attributes that are valid for FSDP2Config will be used, and warnings will be issued for any attributes that cannot be transferred. Therefore it supports both FSDP1 and FSDP2 attributes, and main use case is FS...
from_compatible_attrs
python
mosaicml/composer
composer/utils/parallelism.py
https://github.com/mosaicml/composer/blob/master/composer/utils/parallelism.py
Apache-2.0
def check_workers(self): """Non-blocking call to check workers are either running or done. Traverse self.futures, and check if it's completed 1. if it completed with exception, raise that exception 2. if it completed without exception, remove it from self.futures """ don...
Non-blocking call to check workers are either running or done. Traverse self.futures, and check if it's completed 1. if it completed with exception, raise that exception 2. if it completed without exception, remove it from self.futures
check_workers
python
mosaicml/composer
composer/utils/remote_uploader.py
https://github.com/mosaicml/composer/blob/master/composer/utils/remote_uploader.py
Apache-2.0
def wait(self): """Blocking call to wait all the futures to complete. If a future is done successfully, remove it from self.futures(), otherwise, raise the exception """ for future in self.futures: exception_or_none = future.exception() if exception_or_no...
Blocking call to wait all the futures to complete. If a future is done successfully, remove it from self.futures(), otherwise, raise the exception
wait
python
mosaicml/composer
composer/utils/remote_uploader.py
https://github.com/mosaicml/composer/blob/master/composer/utils/remote_uploader.py
Apache-2.0
def seed_context(seed: int): """Context manager to store rng_state and reseed for duration of context.""" rng_state = get_rng_state() seed_all(seed) yield load_rng_state(rng_state)
Context manager to store rng_state and reseed for duration of context.
seed_context
python
mosaicml/composer
composer/utils/reproducibility.py
https://github.com/mosaicml/composer/blob/master/composer/utils/reproducibility.py
Apache-2.0
def configure_deterministic_mode(): """Configure PyTorch deterministic mode. .. note:: When using the :class:`.Trainer`, you can use the ``deterministic_mode`` flag instead of invoking this function directly. For example: .. testsetup:: import warnings ...
Configure PyTorch deterministic mode. .. note:: When using the :class:`.Trainer`, you can use the ``deterministic_mode`` flag instead of invoking this function directly. For example: .. testsetup:: import warnings warnings.filterwarnings(action="ignore", ...
configure_deterministic_mode
python
mosaicml/composer
composer/utils/reproducibility.py
https://github.com/mosaicml/composer/blob/master/composer/utils/reproducibility.py
Apache-2.0
def get_random_seed() -> int: """Get a randomly created seed to use for seeding rng objects. .. warning:: This random seed is NOT cryptographically secure. Returns: int: A random seed. """ rng = random.Random(int(time.time_ns())) # get a new RNG does not respect the current seed ...
Get a randomly created seed to use for seeding rng objects. .. warning:: This random seed is NOT cryptographically secure. Returns: int: A random seed.
get_random_seed
python
mosaicml/composer
composer/utils/reproducibility.py
https://github.com/mosaicml/composer/blob/master/composer/utils/reproducibility.py
Apache-2.0
def seed_all(seed: int): """Seed all rng objects. .. note:: When using the :class:`.Trainer`, you can use the ``seed`` parameter instead of invoking this function directly. For example: .. doctest:: >>> trainer = Trainer(seed=42) However, to configure the...
Seed all rng objects. .. note:: When using the :class:`.Trainer`, you can use the ``seed`` parameter instead of invoking this function directly. For example: .. doctest:: >>> trainer = Trainer(seed=42) However, to configure the random seed for operations befo...
seed_all
python
mosaicml/composer
composer/utils/reproducibility.py
https://github.com/mosaicml/composer/blob/master/composer/utils/reproducibility.py
Apache-2.0
def get_rng_state() -> list[dict[str, Any]]: """The state of the RNG objects. Returns: list[dict[str, Any]]: A list of RNG State Dicts, indexed by global rank. """ rng_state = { 'python': random.getstate(), 'numpy': np.random.get_state(), 'torch': torch.random.get_rng_st...
The state of the RNG objects. Returns: list[dict[str, Any]]: A list of RNG State Dicts, indexed by global rank.
get_rng_state
python
mosaicml/composer
composer/utils/reproducibility.py
https://github.com/mosaicml/composer/blob/master/composer/utils/reproducibility.py
Apache-2.0
def load_rng_state(rng_state_dicts: list[dict[str, Any]]): """Restore the RNG state. Args: rng_state_dicts (list[dict[str, Any]]): The list of RNG state dicts to restore, as returned by :func:`get_rng_state`. """ if dist.get_world_size() > len(rng_state_dicts): warnings.warn...
Restore the RNG state. Args: rng_state_dicts (list[dict[str, Any]]): The list of RNG state dicts to restore, as returned by :func:`get_rng_state`.
load_rng_state
python
mosaicml/composer
composer/utils/reproducibility.py
https://github.com/mosaicml/composer/blob/master/composer/utils/reproducibility.py
Apache-2.0
def retry( # type: ignore exc_class: Union[TCallable, type[Exception], Sequence[type[Exception]]] = Exception, num_attempts: int = 3, initial_backoff: float = 1.0, max_jitter: float = 0.5, ): """Decorator to retry a function with backoff and jitter. Attempts are spaced out with ``initial_backo...
Decorator to retry a function with backoff and jitter. Attempts are spaced out with ``initial_backoff + 2**num_attempts + random.random() * max_jitter`` seconds. Optionally, the decorated function can specify `retry_index` as an argument to receive the current attempt number. Example: .. testcode:: ...
retry
python
mosaicml/composer
composer/utils/retrying.py
https://github.com/mosaicml/composer/blob/master/composer/utils/retrying.py
Apache-2.0
def get_object_size(self, object_name: str) -> int: """Retrieves the size of an object stored in the cloud storage bucket. Args: object_name (str): The name of the object in the cloud storage bucket whose size is to be retrieved. Returns: int: The size of the object in ...
Retrieves the size of an object stored in the cloud storage bucket. Args: object_name (str): The name of the object in the cloud storage bucket whose size is to be retrieved. Returns: int: The size of the object in bytes. Raises: FileNotFoundError: If the s...
get_object_size
python
mosaicml/composer
composer/utils/object_store/gcs_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/gcs_object_store.py
Apache-2.0
def upload_object( self, object_name: str, filename: Union[str, pathlib.Path], callback: Optional[Callable[[int, int], None]] = None, ): """Uploads a file to the cloud storage bucket. Args: object_name (str, optional): The destination path in the cloud st...
Uploads a file to the cloud storage bucket. Args: object_name (str, optional): The destination path in the cloud storage bucket where the file will be saved. If not provided or an empty string is given, the file will be uploaded to the root of the bucket with the same ...
upload_object
python
mosaicml/composer
composer/utils/object_store/gcs_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/gcs_object_store.py
Apache-2.0
def download_object( self, object_name: str, filename: Union[str, pathlib.Path], overwrite: bool = False, callback: Optional[Callable[[int, int], None]] = None, ): """Downloads an object from the specified source in the cloud storage bucket and saves it to the given d...
Downloads an object from the specified source in the cloud storage bucket and saves it to the given destination. Args: object_name (str): The path to the object in the cloud storage bucket that needs to be downloaded. filename (Union[str, pathlib.Path]): The destination path where the o...
download_object
python
mosaicml/composer
composer/utils/object_store/gcs_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/gcs_object_store.py
Apache-2.0
def _get_object(self, object_name: str): """Get object from object store. Args: object_name (str): The name of the object. """ from libcloud.storage.types import ObjectDoesNotExistError try: return self._provider.get_object(self._container.name, object_na...
Get object from object store. Args: object_name (str): The name of the object.
_get_object
python
mosaicml/composer
composer/utils/object_store/libcloud_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/libcloud_object_store.py
Apache-2.0
def _wrap_mlflow_exceptions(uri: str, e: Exception): """Wraps retryable MLflow errors in ObjectStoreTransientError for automatic retry handling.""" from mlflow.exceptions import ( ABORTED, DATA_LOSS, DEADLINE_EXCEEDED, ENDPOINT_NOT_FOUND, INTERNAL_ERROR, INVALID_S...
Wraps retryable MLflow errors in ObjectStoreTransientError for automatic retry handling.
_wrap_mlflow_exceptions
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def _patch_adls_file_upload_with_timeout(sas_url, local_file, start_byte, size, position, headers, is_single): """Performs an ADLS Azure file create `Patch` operation. (https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update) Args: sas_url: A shared access signatu...
Performs an ADLS Azure file create `Patch` operation. (https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/update) Args: sas_url: A shared access signature URL referring to the Azure ADLS server to which the file update command should be issued. local...
_patch_adls_file_upload_with_timeout
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def _put_adls_file_creation_with_timeout(sas_url, headers): """Performs an ADLS Azure file create `Put` operation. (https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create) :param sas_url: A shared access signature URL referring to the Azure ADLS server ...
Performs an ADLS Azure file create `Put` operation. (https://docs.microsoft.com/en-us/rest/api/storageservices/datalakestoragegen2/path/create) :param sas_url: A shared access signature URL referring to the Azure ADLS server to which the file creation command should be issued. :param h...
_put_adls_file_creation_with_timeout
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def _init_run_info(self, experiment_id: Optional[str], run_id: Optional[str]) -> tuple[str, str]: """Returns the experiment ID and run ID for the MLflow run backing this object store. In a distributed setting, this should only be called on the rank 0 process. """ import mlflow ...
Returns the experiment ID and run ID for the MLflow run backing this object store. In a distributed setting, this should only be called on the rank 0 process.
_init_run_info
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def parse_dbfs_path(path: str) -> tuple[str, str, str]: """Parses a DBFS path to extract the MLflow experiment ID, run ID, and relative artifact path. The path is expected to be of the format `databricks/mlflow-tracking/<experiment_id>/<run_id>/artifacts/<artifact_path>`. Args: ...
Parses a DBFS path to extract the MLflow experiment ID, run ID, and relative artifact path. The path is expected to be of the format `databricks/mlflow-tracking/<experiment_id>/<run_id>/artifacts/<artifact_path>`. Args: path (str): The DBFS path to parse. Returns: ...
parse_dbfs_path
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def get_artifact_path(self, object_name: str) -> str: """Converts an object name into an MLflow relative artifact path. Args: object_name (str): The object name to convert. If the object name is a DBFS path beginning with ``MLFLOW_DBFS_PATH_PREFIX``, the path will be parsed ...
Converts an object name into an MLflow relative artifact path. Args: object_name (str): The object name to convert. If the object name is a DBFS path beginning with ``MLFLOW_DBFS_PATH_PREFIX``, the path will be parsed to extract the MLflow relative artifact path. Oth...
get_artifact_path
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def list_objects(self, prefix: Optional[str] = None) -> list[str]: """See :meth:`~composer.utils.ObjectStore.list_objects`. MLFlowObjectStore does not support listing objects with a prefix, so the ``prefix`` argument is ignored. """ del prefix # not supported for MLFlowObjectStore ...
See :meth:`~composer.utils.ObjectStore.list_objects`. MLFlowObjectStore does not support listing objects with a prefix, so the ``prefix`` argument is ignored.
list_objects
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def _list_objects_helper(self, prefix: Optional[str], objects: list[str]) -> None: """Helper to recursively populate the full list of objects for ``list_objects``. Args: prefix (str | None): An artifact path prefix for artifacts to find. objects (list[str]): The list of DBFS obj...
Helper to recursively populate the full list of objects for ``list_objects``. Args: prefix (str | None): An artifact path prefix for artifacts to find. objects (list[str]): The list of DBFS object paths to populate.
_list_objects_helper
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def _get_artifact_info(self, object_name): """Get the :class:`~mlflow.entities.FileInfo` for the given object name. Args: object_name (str): The name of the object, either as an absolute DBFS path or a relative MLflow artifact path. Returns: Optional[FileInfo]: The :cla...
Get the :class:`~mlflow.entities.FileInfo` for the given object name. Args: object_name (str): The name of the object, either as an absolute DBFS path or a relative MLflow artifact path. Returns: Optional[FileInfo]: The :class:`~mlflow.entities.FileInfo` for the object, or None...
_get_artifact_info
python
mosaicml/composer
composer/utils/object_store/mlflow_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/mlflow_object_store.py
Apache-2.0
def upload_object( self, object_name: str, filename: Union[str, pathlib.Path], callback: Optional[Callable[[int, int], None]] = None, **kwargs, ) -> None: """Upload an object currently located on a disk. Args: object_name (str): Object name (where...
Upload an object currently located on a disk. Args: object_name (str): Object name (where object will be stored in the container) filename (str | pathlib.Path): Path to the object on disk callback ((int, int) -> None, optional): If specified, the callback is periodically cal...
upload_object
python
mosaicml/composer
composer/utils/object_store/object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/object_store.py
Apache-2.0
def download_object( self, object_name: str, filename: Union[str, pathlib.Path], overwrite: bool = False, callback: Optional[Callable[[int, int], None]] = None, ) -> None: """Download an object to the specified destination path. Args: object_name ...
Download an object to the specified destination path. Args: object_name (str): The name of the object to download. filename (str | pathlib.Path): Full path to a file or a directory where the incoming file will be saved. overwrite (bool, optional): Whether to overwrite an exi...
download_object
python
mosaicml/composer
composer/utils/object_store/object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/object_store.py
Apache-2.0
def list_objects(self, prefix: Optional[str]) -> list[str]: """List all objects in the object store with the given prefix. Args: prefix (str): The prefix to search for. Returns: list[str]: A list of object names that match the prefix. """ del prefix # u...
List all objects in the object store with the given prefix. Args: prefix (str): The prefix to search for. Returns: list[str]: A list of object names that match the prefix.
list_objects
python
mosaicml/composer
composer/utils/object_store/object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/object_store.py
Apache-2.0
def _wrap_errors(uri: str, e: Exception): """Wrap an exception in ObjectStoreTransientError if it's retryable. Oherwise, raise the exception. """ # Wrap DatabricksError in ObjectStoreTransientError. # If the file is not found, raise FileNotFoundError. from databricks.sdk.errors import Databrick...
Wrap an exception in ObjectStoreTransientError if it's retryable. Oherwise, raise the exception.
_wrap_errors
python
mosaicml/composer
composer/utils/object_store/uc_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/uc_object_store.py
Apache-2.0
def validate_path(path: str) -> str: """Parses the given path to extract the UC Volume prefix from the path. .. note:: This function only uses the first 4 directories from the path to construct the UC Volumes prefix and will ignore the rest of the directories in the path ...
Parses the given path to extract the UC Volume prefix from the path. .. note:: This function only uses the first 4 directories from the path to construct the UC Volumes prefix and will ignore the rest of the directories in the path Args: path (str): The Databricks ...
validate_path
python
mosaicml/composer
composer/utils/object_store/uc_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/uc_object_store.py
Apache-2.0
def _get_object_path(self, object_name: Optional[str] = None) -> str: """Return the absolute Single Path Namespace for the given object_name. Args: object_name (optional, str): Absolute or relative path of the object w.r.t. the UC Volumes root. If None, the prefix path is return...
Return the absolute Single Path Namespace for the given object_name. Args: object_name (optional, str): Absolute or relative path of the object w.r.t. the UC Volumes root. If None, the prefix path is returned.
_get_object_path
python
mosaicml/composer
composer/utils/object_store/uc_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/uc_object_store.py
Apache-2.0
def upload_object( self, object_name: str, filename: str | pathlib.Path, callback: Callable[[int, int], None] | None = None, ) -> None: """Upload a file from local to UC volumes. Args: object_name (str): Name of the stored object in UC volumes w.r.t. volu...
Upload a file from local to UC volumes. Args: object_name (str): Name of the stored object in UC volumes w.r.t. volume root. filename (str | pathlib.Path): Path to the object on disk callback ((int, int) -> None, optional): Unused
upload_object
python
mosaicml/composer
composer/utils/object_store/uc_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/uc_object_store.py
Apache-2.0
def download_object( self, object_name: str, filename: str | pathlib.Path, overwrite: bool = False, callback: Callable[[int, int], None] | None = None, ) -> None: """Download the given object from UC Volumes to the specified filename. Args: object...
Download the given object from UC Volumes to the specified filename. Args: object_name (str): The name of the object to download i.e. path relative to the root of the volume. filename (str | pathlib.Path): The local path where a the file needs to be downloaded. overwrite(boo...
download_object
python
mosaicml/composer
composer/utils/object_store/uc_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/uc_object_store.py
Apache-2.0
def get_object_size(self, object_name: str) -> int: """Get the size of the object in UC volumes in bytes. Args: object_name (str): The name of the object. Returns: int: The object size, in bytes. Raises: FileNotFoundError: If the file was not found ...
Get the size of the object in UC volumes in bytes. Args: object_name (str): The name of the object. Returns: int: The object size, in bytes. Raises: FileNotFoundError: If the file was not found in the object store. IsADirectoryError: If the obje...
get_object_size
python
mosaicml/composer
composer/utils/object_store/uc_object_store.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/uc_object_store.py
Apache-2.0
def build_remote_backend(remote_backend_name: str, backend_kwargs: dict[str, Any]): """Build object store given the backend name and kwargs.""" remote_backend_cls = None remote_backend_name_to_cls = { 's3': S3ObjectStore, 'oci': OCIObjectStore, 'sftp': SFTPObjectStore, 'libcl...
Build object store given the backend name and kwargs.
build_remote_backend
python
mosaicml/composer
composer/utils/object_store/utils.py
https://github.com/mosaicml/composer/blob/master/composer/utils/object_store/utils.py
Apache-2.0
def skip_redundant_namedtuple_attributes( app: sphinx.application.Sphinx, what: str, name: str, obj: Any, skip: bool, options: sphinx.ext.autodoc.Options, ): """Hide the default, duplicate attributes for named tuples.""" del app, what, name, skip, options if '_tuplegetter' in obj.__c...
Hide the default, duplicate attributes for named tuples.
skip_redundant_namedtuple_attributes
python
mosaicml/composer
docs/source/conf.py
https://github.com/mosaicml/composer/blob/master/docs/source/conf.py
Apache-2.0
def rstjinja(app, docname, source): """Render our pages as a jinja template for fancy templating goodness.""" # Make sure we're outputting HTML if app.builder.format != 'html': return src = source[0] rendered = app.builder.templates.render_string(src, app.config.html_context) source[0] =...
Render our pages as a jinja template for fancy templating goodness.
rstjinja
python
mosaicml/composer
docs/source/conf.py
https://github.com/mosaicml/composer/blob/master/docs/source/conf.py
Apache-2.0
def get_algorithms_metadata() -> dict[str, dict[str, str]]: """Get the metadata for algorithms from the ``metadata.json`` files.""" EXCLUDE = ['no_op_model'] root = os.path.join(os.path.dirname(__file__), '..', '..', 'composer', 'algorithms') algorithms = next(os.walk(root))[1] algorithms = [algo f...
Get the metadata for algorithms from the ``metadata.json`` files.
get_algorithms_metadata
python
mosaicml/composer
docs/source/conf.py
https://github.com/mosaicml/composer/blob/master/docs/source/conf.py
Apache-2.0
def _auto_rst_for_module(module: types.ModuleType, exclude_members: list[Any]) -> str: """Generate the content of an rst file documenting a module. Includes the module docstring, followed by tables for the functions, classes, and exceptions Args: module: The module object to document e...
Generate the content of an rst file documenting a module. Includes the module docstring, followed by tables for the functions, classes, and exceptions Args: module: The module object to document exclude_members: A list of Python objects to exclude from the documentation. Provid...
_auto_rst_for_module
python
mosaicml/composer
docs/source/conf.py
https://github.com/mosaicml/composer/blob/master/docs/source/conf.py
Apache-2.0
def _modules_to_rst() -> list[types.ModuleType]: """Return the list of modules for which to generate API reference rst files.""" # adding composer.functional to the below list yields: # AttributeError: module 'composer' has no attribute 'functional' import composer.functional as cf document_modul...
Return the list of modules for which to generate API reference rst files.
_modules_to_rst
python
mosaicml/composer
docs/source/conf.py
https://github.com/mosaicml/composer/blob/master/docs/source/conf.py
Apache-2.0
def _generate_rst_files_for_modules() -> None: """Generate .rst files for each module to include in the API reference. These files contain the module docstring followed by tables listing all the functions, classes, etc. """ docs_dir = os.path.abspath(os.path.dirname(__file__)) module_rst_save_d...
Generate .rst files for each module to include in the API reference. These files contain the module docstring followed by tables listing all the functions, classes, etc.
_generate_rst_files_for_modules
python
mosaicml/composer
docs/source/conf.py
https://github.com/mosaicml/composer/blob/master/docs/source/conf.py
Apache-2.0
def _add_directive_header_no_object_base(self, *args, **kwargs): """Hide that all classes inherit from the base class ``object``.""" self.add_line = _add_line_no_object_base.__get__(self) result = add_directive_header(self, *args, **kwargs) del self.add_line return result
Hide that all classes inherit from the base class ``object``.
_add_directive_header_no_object_base
python
mosaicml/composer
docs/source/conf.py
https://github.com/mosaicml/composer/blob/master/docs/source/conf.py
Apache-2.0
def generate_graph(filename, light_mode=True): """Generate Graphs. Args: filename (_type_): Name of output image SVG file light_mode (bool, optional): Render in light mode. Defaults to True. """ font_color = 'black' if light_mode else 'white' mpl.rcParams['text.color'] = font_color ...
Generate Graphs. Args: filename (_type_): Name of output image SVG file light_mode (bool, optional): Render in light mode. Defaults to True.
generate_graph
python
mosaicml/composer
docs/source/tables/generate_cost_graphs.py
https://github.com/mosaicml/composer/blob/master/docs/source/tables/generate_cost_graphs.py
Apache-2.0
def list_dirs(folder): """Lists all dirs for a given folder. Args: folder (str): The folder to list dirs for. """ return sorted( child.name for child in folder.iterdir() if child.is_dir() and ('__pycache__' not in str(child.absolute())) )
Lists all dirs for a given folder. Args: folder (str): The folder to list dirs for.
list_dirs
python
mosaicml/composer
docs/source/tables/utils.py
https://github.com/mosaicml/composer/blob/master/docs/source/tables/utils.py
Apache-2.0
def assert_attributes_exist(name, module_dict, attributes): """Assert that module has the provided attributes. Args: name (str): The class name. module_dict (dict): The dict form of the class. attributes (list): The attributes to check for. """ for attribute in attributes: ...
Assert that module has the provided attributes. Args: name (str): The class name. module_dict (dict): The dict form of the class. attributes (list): The attributes to check for.
assert_attributes_exist
python
mosaicml/composer
docs/source/tables/utils.py
https://github.com/mosaicml/composer/blob/master/docs/source/tables/utils.py
Apache-2.0
def get_metadata(names, attributes, module_basepath): """Returns a nested dict of metadata with names as keys. Checks that all attributes exist in module given by module_basepath.name. Args: names (str): The module names. attributes (list): The attributes to check for. module_basep...
Returns a nested dict of metadata with names as keys. Checks that all attributes exist in module given by module_basepath.name. Args: names (str): The module names. attributes (list): The attributes to check for. module_basepath (str): The import path of the module. Example:: ...
get_metadata
python
mosaicml/composer
docs/source/tables/utils.py
https://github.com/mosaicml/composer/blob/master/docs/source/tables/utils.py
Apache-2.0
def build_markdown_table(header, metadata, sorted_keys, row_format): """Builds a markdown table, formatting `row_format` with the `metadata`. Entries in the table are ordered by `sorted_keys`. Args: header (list): list of header strings metadata (dict): nested dict of metadata sort...
Builds a markdown table, formatting `row_format` with the `metadata`. Entries in the table are ordered by `sorted_keys`. Args: header (list): list of header strings metadata (dict): nested dict of metadata sorted_keys (list): order of rows in table row_format (list): list of le...
build_markdown_table
python
mosaicml/composer
docs/source/tables/utils.py
https://github.com/mosaicml/composer/blob/master/docs/source/tables/utils.py
Apache-2.0
def index_tag_in_lines(lines, tag): """Returns line number where tag is found. Args: lines (list): list of lines to check. tag (str): Tag to find. """ for index, line in enumerate(lines): if tag in line: return index raise ValueError(f'{tag} not found.')
Returns line number where tag is found. Args: lines (list): list of lines to check. tag (str): Tag to find.
index_tag_in_lines
python
mosaicml/composer
docs/source/tables/utils.py
https://github.com/mosaicml/composer/blob/master/docs/source/tables/utils.py
Apache-2.0
def update_table_in_file(table, source_file): """Updates the table content based on a source file. Given a `source file`, updates the table. Searches the file for 'Table Start' and 'Table End' tags, and replaces the content between those tags. The original file is retained with the `.bkp` suffix. ...
Updates the table content based on a source file. Given a `source file`, updates the table. Searches the file for 'Table Start' and 'Table End' tags, and replaces the content between those tags. The original file is retained with the `.bkp` suffix. Args: table (list): list of strings ...
update_table_in_file
python
mosaicml/composer
docs/source/tables/utils.py
https://github.com/mosaicml/composer/blob/master/docs/source/tables/utils.py
Apache-2.0
def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None: """Filter tests by world_size (for multi-GPU tests) and duration (short, long, or all)""" world_size = int(os.environ.get('WORLD_SIZE', '1')) conditions = [ lambda item: _get_world_size(item) == world_size,...
Filter tests by world_size (for multi-GPU tests) and duration (short, long, or all)
pytest_collection_modifyitems
python
mosaicml/composer
tests/conftest.py
https://github.com/mosaicml/composer/blob/master/tests/conftest.py
Apache-2.0
def generate_maskrcnn_sample(num_detections, image_height=1, image_width=1, num_classes=1): """Generates a maskrcnn style sample: (Tensor, dict[Tensor]).""" image = torch.randn(size=(3, image_height, image_width)).type(torch.float) target = { 'boxes': torch.randint(si...
Generates a maskrcnn style sample: (Tensor, dict[Tensor]).
generate_maskrcnn_sample
python
mosaicml/composer
tests/test_device.py
https://github.com/mosaicml/composer/blob/master/tests/test_device.py
Apache-2.0
def test_docker_build_matrix(): """Test that the docker build matrix is up to date.""" docker_folder = os.path.join(os.path.dirname(__file__), '..', 'docker') # Capture the existing readme and build matrix contents with open(os.path.join(docker_folder, 'README.md'), 'r') as f: existing_readme =...
Test that the docker build matrix is up to date.
test_docker_build_matrix
python
mosaicml/composer
tests/test_docs.py
https://github.com/mosaicml/composer/blob/master/tests/test_docs.py
Apache-2.0
def test_logging( caplog: pytest.LogCaptureFixture, dummy_state: State, dummy_logger: Logger, monkeypatch: pytest.MonkeyPatch, ): """Test that engine logs statements as expected""" caplog.clear() with caplog.at_level(logging.DEBUG, logger=Engine.__module__): # Include a callback, sin...
Test that engine logs statements as expected
test_logging
python
mosaicml/composer
tests/test_engine.py
https://github.com/mosaicml/composer/blob/master/tests/test_engine.py
Apache-2.0
def test_full_nlp_pipeline( model_type, algorithms, save_format, onnx_opset_version, tmp_path, device, tiny_bert_tokenizer, ): """This test is intended to exercise our full pipeline for NLP. To this end, it performs pretraining, loads the pretrained model with a classification head ...
This test is intended to exercise our full pipeline for NLP. To this end, it performs pretraining, loads the pretrained model with a classification head for finetuning and finetunes it, exports the model for inference, and loads it back in to make predictions.
test_full_nlp_pipeline
python
mosaicml/composer
tests/test_full_nlp.py
https://github.com/mosaicml/composer/blob/master/tests/test_full_nlp.py
Apache-2.0
def get_alg_model(alg_cls: type[Algorithm]) -> ComposerModel: """Return an instance of the model for an algorithm.""" settings = _get_alg_settings(alg_cls)['model'] if isinstance(settings, tuple): (cls, kwargs) = settings else: (cls, kwargs) = (settings, {}) return cls(**kwargs)
Return an instance of the model for an algorithm.
get_alg_model
python
mosaicml/composer
tests/algorithms/algorithm_settings.py
https://github.com/mosaicml/composer/blob/master/tests/algorithms/algorithm_settings.py
Apache-2.0
def get_alg_dataloader(alg_cls: type[Algorithm], multigpu=False) -> DataLoader: """Return an instance of the dataset for an algorithm.""" settings = _get_alg_settings(alg_cls) if 'dataloader' in settings: dataloader_cls, kwargs = settings['dataloader'] if 'dataset' in kwargs and multigpu: ...
Return an instance of the dataset for an algorithm.
get_alg_dataloader
python
mosaicml/composer
tests/algorithms/algorithm_settings.py
https://github.com/mosaicml/composer/blob/master/tests/algorithms/algorithm_settings.py
Apache-2.0
def get_algs_with_marks(): """Returns a list of algorithms appropriate markers for a subsequent call to pytest.mark.parameterize. It applies markers as appropriate (e.g. XFAIL for algs missing config) It reads from the algorithm registry E.g. @pytest.mark.parametrize("alg_class", get_algs_with_marks())...
Returns a list of algorithms appropriate markers for a subsequent call to pytest.mark.parameterize. It applies markers as appropriate (e.g. XFAIL for algs missing config) It reads from the algorithm registry E.g. @pytest.mark.parametrize("alg_class", get_algs_with_marks())
get_algs_with_marks
python
mosaicml/composer
tests/algorithms/algorithm_settings.py
https://github.com/mosaicml/composer/blob/master/tests/algorithms/algorithm_settings.py
Apache-2.0
def test_myalgo_logging(state): """Test that the logging is as expected. Example: logger_mock = Mock() algorithm = AlgorithmThatLogsSomething() algorithm.apply(Event.INIT, state, logger=logger_mock) logger_mock.log_hyperparameters.assert_called_one_with({ 'some_key...
Test that the logging is as expected. Example: logger_mock = Mock() algorithm = AlgorithmThatLogsSomething() algorithm.apply(Event.INIT, state, logger=logger_mock) logger_mock.log_hyperparameters.assert_called_one_with({ 'some_key': some_value })
test_myalgo_logging
python
mosaicml/composer
tests/algorithms/algorithm_test_template.py
https://github.com/mosaicml/composer/blob/master/tests/algorithms/algorithm_test_template.py
Apache-2.0
def encountered_alibi_warning(caplog): """Return true if the caplog shows an alibi warning in the log""" for (logger_name, level, _) in caplog.record_tuples: if 'alibi' in logger_name and level >= 30: # Warnings are level 30 return True return False
Return true if the caplog shows an alibi warning in the log
encountered_alibi_warning
python
mosaicml/composer
tests/algorithms/test_alibi.py
https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_alibi.py
Apache-2.0
def test_warning_is_triggered(caplog): """Test that Alibi triggers a warning when it has no effect.""" pytest.importorskip('transformers') apply_alibi( model=torch.nn.Sequential(torch.nn.Linear(20, 10), torch.nn.Linear(10, 5)), max_sequence_length=64, ) assert encountered_alibi_warni...
Test that Alibi triggers a warning when it has no effect.
test_warning_is_triggered
python
mosaicml/composer
tests/algorithms/test_alibi.py
https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_alibi.py
Apache-2.0
def test_registry(caplog): """Test that registry additions are used by Alibi.""" pytest.importorskip('transformers') from composer.algorithms.alibi.attention_surgery_functions import policy_registry @policy_registry.register(torch.nn.Linear) def zero_linear_weights( # pyright: ignore[reportUnusedF...
Test that registry additions are used by Alibi.
test_registry
python
mosaicml/composer
tests/algorithms/test_alibi.py
https://github.com/mosaicml/composer/blob/master/tests/algorithms/test_alibi.py
Apache-2.0