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 _recreate_fsdp_param_groups_from_unwrapped_opt_info(
fsdp_wrapped_named_params: Iterator[tuple[str, torch.nn.Parameter]],
non_wrapped_param_names_to_group_num: dict[str, int],
group_num_to_optimizer_info: dict[int, dict[str, Any]],
) -> list[dict[str, Any]]:
"""Helper function to recreate optimizer ... | Helper function to recreate optimizer groups for FSDP wrapped modules.
Optimizer param groups are formatted as:
[
{'params': [p1, p2], 'lr' : lr1}, # group 0
{'params': [p3], 'lr' : lr2} # group 1
]
ie. there are multiple parameters per group. Here, we track the group number in order to... | _recreate_fsdp_param_groups_from_unwrapped_opt_info | python | mosaicml/composer | composer/distributed/dist_strategy.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/dist_strategy.py | Apache-2.0 |
def prepare_tp_module(
model: torch.nn.Module,
optimizers: Optional[Union[torch.optim.Optimizer, Sequence[torch.optim.Optimizer]]],
tp_config: TPConfig,
) -> None:
"""Prepare a module (assumed ComposerModel) for use with tensor parallel."""
optimizers_tuple = ensure_tuple(optimizers)
if len(opti... | Prepare a module (assumed ComposerModel) for use with tensor parallel. | prepare_tp_module | python | mosaicml/composer | composer/distributed/dist_strategy.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/dist_strategy.py | Apache-2.0 |
def prepare_fsdp_module(
model: torch.nn.Module,
optimizers: Optional[Union[torch.optim.Optimizer, Sequence[torch.optim.Optimizer]]],
fsdp_config: FSDPConfig,
precision: Optional[Union[str, Precision]] = None,
device: Optional[Union[str, Device]] = None,
auto_microbatching: bool = False,
te_... | Prepare a module (assumed ComposerModel) and optimizer for use with :class:`torch.distributed.fsdp.FullyShardedDataParallel`.
Args:
model (torch.nn.Module): The model to wrap.
optimizers (torch.optim.Optimizer | Sequence[torch.optim.Optimizer], optional): The optimizer for `model`, assumed to have ... | prepare_fsdp_module | python | mosaicml/composer | composer/distributed/dist_strategy.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/dist_strategy.py | Apache-2.0 |
def _recursive_apply_fully_shard(
root_module: nn.Module,
module: nn.Module,
visited_modules: set[nn.Module],
target_modules_to_kwargs: dict[nn.Module, dict],
) -> None:
"""Recursive helper to apply fully_shard based on policy and legalization.
Args:
root_module (nn.Module): The root mo... | Recursive helper to apply fully_shard based on policy and legalization.
Args:
root_module (nn.Module): The root module to check for parameter sharing.
module (nn.Module): The current module being processed.
visited_modules (set[nn.Module]): Set of modules that have already been visited so w... | _recursive_apply_fully_shard | python | mosaicml/composer | composer/distributed/fsdp2.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2.py | Apache-2.0 |
def apply_fully_shard(
model: nn.Module,
fsdp2_config: FSDP2Config,
auto_wrap_policy: CustomPolicy,
) -> None:
"""Applies FSDP2's `fully_shard` to the specified modules and then to the parent model.
NOTE FSDP are only applied to nn.Parameters not Buffers.
Args:
model (torch.nn.Module):... | Applies FSDP2's `fully_shard` to the specified modules and then to the parent model.
NOTE FSDP are only applied to nn.Parameters not Buffers.
Args:
model (torch.nn.Module): The parent model.
fsdp2_config (FSDP2Config): The FSDP2 configuration.
auto_wrap_policy (CustomPolicy): The polic... | apply_fully_shard | python | mosaicml/composer | composer/distributed/fsdp2.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2.py | Apache-2.0 |
def prepare_fully_shard(
model: nn.Module,
fsdp2_config: FSDP2Config,
auto_wrap_policy: Optional[CustomPolicy] = None,
) -> None:
"""Applies FSDP2's `fully_shard` to the model according to given fsdp2_config.
Args:
model (torch.nn.Module): The model to prepare.
fsdp2_config (FSDP2Co... | Applies FSDP2's `fully_shard` to the model according to given fsdp2_config.
Args:
model (torch.nn.Module): The model to prepare.
fsdp2_config (FSDP2Config): The FSDP2 configuration.
auto_wrap_policy (Optional[CustomPolicy]): The policy to apply to the model.
Returns:
None
| prepare_fully_shard | python | mosaicml/composer | composer/distributed/fsdp2.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2.py | Apache-2.0 |
def sync_module_states(model: nn.Module, full_state_dict: dict) -> None:
"""Syncs the module states of the model across all ranks using the full state dict.
This function synchronizes the module states of the model across all ranks using the full state dict.
This handles mixed initialization scenarios wher... | Syncs the module states of the model across all ranks using the full state dict.
This function synchronizes the module states of the model across all ranks using the full state dict.
This handles mixed initialization scenarios where different ranks have parameters on different devices.
Args:
model... | sync_module_states | python | mosaicml/composer | composer/distributed/fsdp2.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2.py | Apache-2.0 |
def get_standalone_and_tied_modules(modules: list[nn.Module]) -> tuple[list[nn.Module], set[nn.Module]]:
"""Filter modules that have standalone params thus can be fully sharded independently and those with tied params.
Note if a module is a child of another module, they are still considered to be tied modules.... | Filter modules that have standalone params thus can be fully sharded independently and those with tied params.
Note if a module is a child of another module, they are still considered to be tied modules.
If a module does not have any params, it is not included in the output.
Args:
modules (list[to... | get_standalone_and_tied_modules | python | mosaicml/composer | composer/distributed/fsdp2_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2_utils.py | Apache-2.0 |
def _get_param_tying_groups(model: nn.Module) -> list[set[str]]:
"""Identifies groups of tied parameters within a model based on object identity.
A parameter is considered tied if the same nn.Parameter object appears multiple
times when iterating through model.named_parameters().
NOTE: We take the rec... | Identifies groups of tied parameters within a model based on object identity.
A parameter is considered tied if the same nn.Parameter object appears multiple
times when iterating through model.named_parameters().
NOTE: We take the recursive approach since .named_parameters() has a weird behavior where if ... | _get_param_tying_groups | python | mosaicml/composer | composer/distributed/fsdp2_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2_utils.py | Apache-2.0 |
def check_param_tying(model: nn.Module):
"""Context manager to verify that parameter tying relationships remain consistent.
Checks parameter tying based on shared parameter object identity before and after the context.
"""
pre_shard_tying_groups = _get_param_tying_groups(model)
sorted_pre_shard_gro... | Context manager to verify that parameter tying relationships remain consistent.
Checks parameter tying based on shared parameter object identity before and after the context.
| check_param_tying | python | mosaicml/composer | composer/distributed/fsdp2_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2_utils.py | Apache-2.0 |
def sync_optimizer_and_model_params(
optimizer: torch.optim.Optimizer,
model: nn.Module,
):
"""Context manager that synchronizes optimizer parameters with model parameters.
This context manager builds a mapping between the original model parameters and their names,
yields control back to the caller... | Context manager that synchronizes optimizer parameters with model parameters.
This context manager builds a mapping between the original model parameters and their names,
yields control back to the caller, and then updates the optimizer's parameter groups to
use the (potentially sharded) model parameters a... | sync_optimizer_and_model_params | python | mosaicml/composer | composer/distributed/fsdp2_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2_utils.py | Apache-2.0 |
def update_optimizer_modules(
optimizer: torch.optim.Optimizer,
model: nn.Module,
orig_param_to_name: dict[torch.nn.Parameter, str],
) -> None:
"""Updates the optimizer's parameter groups to use the sharded model parameters.
Assumes no training has occurred yet and the optimizer state is empty. If ... | Updates the optimizer's parameter groups to use the sharded model parameters.
Assumes no training has occurred yet and the optimizer state is empty. If the optimizer state is not empty,
it will be cleared with a warning.
Args:
optimizer (Optimizer): The optimizer to update.
model (nn.Modul... | update_optimizer_modules | python | mosaicml/composer | composer/distributed/fsdp2_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2_utils.py | Apache-2.0 |
def generate_default_policy(parent_model: nn.Module) -> CustomPolicy:
"""Generates the default fsdp wrap policy for FSDP2.
This policy determines which modules should be wrapped with FSDP2 based on module attributes
or custom wrapping functions. It checks for:
1. The presence of an `_fsdp_wrap` attrib... | Generates the default fsdp wrap policy for FSDP2.
This policy determines which modules should be wrapped with FSDP2 based on module attributes
or custom wrapping functions. It checks for:
1. The presence of an `_fsdp_wrap` attribute on modules (deprecated)
2. A `fsdp_wrap_fn` callable on the parent mo... | generate_default_policy | python | mosaicml/composer | composer/distributed/fsdp2_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2_utils.py | Apache-2.0 |
def generate_composer_model_policy(composer_model: ComposerModel) -> CustomPolicy:
"""Generates a FSDP wrap policy for ComposerModel that mimics FSDP1 behavior.
This policy wraps all direct children of the ComposerModel but not the ComposerModel itself,
which matches the behavior of FSDP1's prepare_fsdp_mo... | Generates a FSDP wrap policy for ComposerModel that mimics FSDP1 behavior.
This policy wraps all direct children of the ComposerModel but not the ComposerModel itself,
which matches the behavior of FSDP1's prepare_fsdp_module function. It also respects
any _fsdp_wrap attributes or fsdp_wrap_fn functions de... | generate_composer_model_policy | python | mosaicml/composer | composer/distributed/fsdp2_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/fsdp2_utils.py | Apache-2.0 |
def meta_safe_apply(self, fn, ignored_modules: set, module_name: str):
"""Applies the function recursively to a module's children and the module itself.
This variant allows us to ignore modules to apply the function.
The function is a slightly modified version of the one from PyTorch:
https://github.co... | Applies the function recursively to a module's children and the module itself.
This variant allows us to ignore modules to apply the function.
The function is a slightly modified version of the one from PyTorch:
https://github.com/pytorch/pytorch/blob/v1.13.0/torch/nn/modules/module.py#L637
Args:
... | meta_safe_apply | python | mosaicml/composer | composer/distributed/meta_safe_apply.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/meta_safe_apply.py | Apache-2.0 |
def _get_torch_dtype(dtype: Union[Precision, str]):
"""Convert common string representations of dtypes to torch dtypes."""
dtype = dtype.value if isinstance(dtype, Precision) else dtype
if dtype in ['float32', 'torch.float32', 'fp32']:
return torch.float32
elif dtype in ['float16', 'torch.float1... | Convert common string representations of dtypes to torch dtypes. | _get_torch_dtype | python | mosaicml/composer | composer/distributed/mosaic_parallelism.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/mosaic_parallelism.py | Apache-2.0 |
def _get_process_group(pg, process_group_cache=None):
"""Helper function for configuring and/or retrieving process groups."""
if pg is None or isinstance(pg, ProcessGroup): # Return as is, no caching
return pg
world_size = dist.get_world_size()
local_world_size = dist.get_local_world_size()
... | Helper function for configuring and/or retrieving process groups. | _get_process_group | python | mosaicml/composer | composer/distributed/mosaic_parallelism.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/mosaic_parallelism.py | Apache-2.0 |
def meta_init(module: nn.Module, param_init_fn: Optional[Callable[[nn.Module], None]] = None) -> None:
"""Initialize a module's parameters if it has `meta` Parameters or Buffers.
This function initializes parameters for models with meta tensors by first converting
them to empty tensors on CUDA, then applyi... | Initialize a module's parameters if it has `meta` Parameters or Buffers.
This function initializes parameters for models with meta tensors by first converting
them to empty tensors on CUDA, then applying initialization functions.
Args:
module (torch.nn.Module): The module containing meta parameter... | meta_init | python | mosaicml/composer | composer/distributed/param_init.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/param_init.py | Apache-2.0 |
def log_execution_time(logger: logging.Logger, operation_name: str):
"""Log the execution time of a block of code."""
start_time = time.time()
try:
yield
finally:
end_time = time.time()
logger.info(f'{operation_name} took {end_time - start_time:.2f} seconds') | Log the execution time of a block of code. | log_execution_time | python | mosaicml/composer | composer/distributed/prepare_distributed.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/prepare_distributed.py | Apache-2.0 |
def _filter_state_dict_duplicates(model: torch.nn.Module) -> dict:
"""Filter out duplicate params in the state dict.
model.state_dict() can include multiple references to the same tensor/param
(for instance, if we have multiple references to the same module). On the
other hand, model.named_parameters()... | Filter out duplicate params in the state dict.
model.state_dict() can include multiple references to the same tensor/param
(for instance, if we have multiple references to the same module). On the
other hand, model.named_parameters() will not have duplicate references. As
sync_module_states requires a ... | _filter_state_dict_duplicates | python | mosaicml/composer | composer/distributed/prepare_distributed.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/prepare_distributed.py | Apache-2.0 |
def _parallelize_model_helper(
model: torch.nn.Module,
config: FSDP2Config,
fsdp_wrap_policy: Optional[CustomPolicy] = None,
param_init_fn: Callable[[torch.nn.Module], None] = lambda m: None,
) -> None:
"""Helper function for parallelizing a model.
There are two paths with how we parallelize a ... | Helper function for parallelizing a model.
There are two paths with how we parallelize a model:
1. Without sync_module_states: fully_shard first, then param_init. This prevents OOM by avoiding
redundant parameter copies across all ranks during param_init.
2. With sync_module_states: param_init on ra... | _parallelize_model_helper | python | mosaicml/composer | composer/distributed/prepare_distributed.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/prepare_distributed.py | Apache-2.0 |
def parallelize_model(
model: torch.nn.Module,
config: FSDP2Config,
optimizer: Optional[torch.optim.Optimizer] = None,
fsdp_wrap_policy: Optional[CustomPolicy] = None,
activation_checkpointing_check_fn: Optional[Callable] = None,
param_init_fn: Callable[[torch.nn.Module], None] = lambda m: None,... | Prepare a model for distributed training.
This function currently applies FSDP2 to the model, initializes parameters,
and optionally applies activation checkpointing. It handles parameter consistency between the optimizer
and model when an optimizer is provided.
Args:
model (torch.nn.Module): ... | parallelize_model | python | mosaicml/composer | composer/distributed/prepare_distributed.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/prepare_distributed.py | Apache-2.0 |
def parallelize_composer_model(
composer_model: ComposerModel,
optimizer: Optional[torch.optim.Optimizer],
config: FSDP2Config,
):
"""Prepare a ComposerModel for distributed training.
NOTE we apply parallelization to each of the composer model's submodules to provide compatibility with models defin... | Prepare a ComposerModel for distributed training.
NOTE we apply parallelization to each of the composer model's submodules to provide compatibility with models defined for FSDP1.
This is not strictly necessary for FSDP2 as it relies on DTensor so even if a module is not wrapped with FSDP2 and its params are sh... | parallelize_composer_model | python | mosaicml/composer | composer/distributed/prepare_distributed.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/prepare_distributed.py | Apache-2.0 |
def get_direct_children_from_composer_model(model: ComposerModel) -> list[torch.nn.Module]:
"""Returns a list of valid direct children from a ComposerModel.
A valid direct child for a ComposerModel is a module that's not a Metric or MetricCollection.
Returns:
list: List of valid direct children fr... | Returns a list of valid direct children from a ComposerModel.
A valid direct child for a ComposerModel is a module that's not a Metric or MetricCollection.
Returns:
list: List of valid direct children from a ComposerModel.
| get_direct_children_from_composer_model | python | mosaicml/composer | composer/distributed/shared_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/shared_utils.py | Apache-2.0 |
def add_fsdp_oom_hooks(model: torch.nn.Module, device: Optional[Device] = None) -> list[RemovableHandle]:
"""Add OOM hooks to the FSDP1-wrapped model and return the list of handles.
Note: This isn't supported for FSDP2 yet. For more details view the draft PR:
https://github.com/mosaicml/composer/pull/3866
... | Add OOM hooks to the FSDP1-wrapped model and return the list of handles.
Note: This isn't supported for FSDP2 yet. For more details view the draft PR:
https://github.com/mosaicml/composer/pull/3866
The following sync hooks are added to prevent FSDP1 deadlocks that are caused when some ranks OOM
and ot... | add_fsdp_oom_hooks | python | mosaicml/composer | composer/distributed/shared_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/shared_utils.py | Apache-2.0 |
def update_sync_module_states_if_needed(model: nn.Module, fsdp_config: FSDP2Config | FSDPConfig) -> None:
"""Updates sync_module_states configuration based on model initialization.
In cases where the model on rank 0 is on CPU/GPU and other ranks are on meta, this function
will automatically set sync_module... | Updates sync_module_states configuration based on model initialization.
In cases where the model on rank 0 is on CPU/GPU and other ranks are on meta, this function
will automatically set sync_module_states to True. It also adds a check to make sure that
the unexpected edge case where the model on rank 0 is... | update_sync_module_states_if_needed | python | mosaicml/composer | composer/distributed/shared_utils.py | https://github.com/mosaicml/composer/blob/master/composer/distributed/shared_utils.py | Apache-2.0 |
def _log_to_console(self, log_str: str):
"""Logs to the console, avoiding interleaving with a progress bar."""
# write directly to self.stream; no active progress bar
print(log_str, file=self.stream, flush=True) | Logs to the console, avoiding interleaving with a progress bar. | _log_to_console | python | mosaicml/composer | composer/loggers/console_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/console_logger.py | Apache-2.0 |
def _get_new_writer(self, prefix: str, original_writer: Callable[[str], int]):
"""Returns a writer that intercepts calls to the ``original_writer``."""
def new_write(s: str) -> int:
if not self._closed:
self.write(prefix, s)
return original_writer(s)
ret... | Returns a writer that intercepts calls to the ``original_writer``. | _get_new_writer | python | mosaicml/composer | composer/loggers/file_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/file_logger.py | Apache-2.0 |
def remote_file_name(self) -> str:
"""The remote file name for the logfile."""
if self._run_name is None:
raise RuntimeError('The run name is not set. The engine should have been set on Event.INIT')
name = format_name_with_dist(self.remote_file_name_format, run_name=self._run_name)
... | The remote file name for the logfile. | remote_file_name | python | mosaicml/composer | composer/loggers/file_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/file_logger.py | Apache-2.0 |
def write(self, prefix: str, s: str):
"""Write to the logfile.
.. note::
If the ``write`` occurs before the :attr:`.Event.INIT` event,
the write will be enqueued, as the file is not yet open.
Args:
prefix (str): A prefix for each line in the logfile.
... | Write to the logfile.
.. note::
If the ``write`` occurs before the :attr:`.Event.INIT` event,
the write will be enqueued, as the file is not yet open.
Args:
prefix (str): A prefix for each line in the logfile.
s (str): The string to write. Each line wil... | write | python | mosaicml/composer | composer/loggers/file_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/file_logger.py | Apache-2.0 |
def get_timeseries(self, metric: str) -> dict[str, Any]:
"""Returns logged data as dict containing values of a desired metric over time.
Args:
metric (str): Metric of interest. Must be present in self.data.keys().
Returns:
timeseries (dict[str, Any]): Dictionary in whic... | Returns logged data as dict containing values of a desired metric over time.
Args:
metric (str): Metric of interest. Must be present in self.data.keys().
Returns:
timeseries (dict[str, Any]): Dictionary in which one key is ``metric``,
and the associated value is... | get_timeseries | python | mosaicml/composer | composer/loggers/in_memory_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/in_memory_logger.py | Apache-2.0 |
def log_images(
self,
images: Union[np.ndarray, torch.Tensor, Sequence[Union[np.ndarray, torch.Tensor]]],
name: str = 'Images',
channels_last: bool = False,
step: Optional[int] = None,
masks: Optional[dict[str, Union[np.ndarray, torch.Tensor, Sequence[Union[np.ndarray, to... | Log images. Logs any tensors or arrays as images.
Args:
images (np.ndarray | torch.Tensor | Sequence[np.ndarray | torch.Tensor]): Dictionary mapping
image(s)' names (str) to an image of array of images.
name (str): The name of the image(s). (Default: ``'Images'``)
... | log_images | python | mosaicml/composer | composer/loggers/logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/logger.py | Apache-2.0 |
def upload_file(
self,
remote_file_name: str,
file_path: Union[pathlib.Path, str],
*,
overwrite: bool = False,
):
"""Upload ``file_path`` as a file named ``remote_file_name``.
Both ``file_path`` and ``remote_file_name`` can be specified as format strings.
... | Upload ``file_path`` as a file named ``remote_file_name``.
Both ``file_path`` and ``remote_file_name`` can be specified as format strings.
See :func:`~.composer.utils.file_helpers.format_name_with_dist` for more information.
.. seealso:: :doc:`Uploading Files</trainer/file_uploading>` for note... | upload_file | python | mosaicml/composer | composer/loggers/logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/logger.py | Apache-2.0 |
def has_file_upload_destination(self) -> bool:
"""Determines if the logger has a destination which supports uploading files.
Needed for checking if a model can be exported via this logger.
Returns:
bool: Whether any of the destinations support uploading files.
"""
... | Determines if the logger has a destination which supports uploading files.
Needed for checking if a model can be exported via this logger.
Returns:
bool: Whether any of the destinations support uploading files.
| has_file_upload_destination | python | mosaicml/composer | composer/loggers/logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/logger.py | Apache-2.0 |
def format_log_data_value(data: Any) -> str:
"""Recursively formats a given log data value into a string.
Args:
data: Data to format.
Returns:
str: ``data`` as a string.
"""
if data is None:
return 'None'
if isinstance(data, str):
return f"\"{data}\""
if isi... | Recursively formats a given log data value into a string.
Args:
data: Data to format.
Returns:
str: ``data`` as a string.
| format_log_data_value | python | mosaicml/composer | composer/loggers/logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/logger.py | Apache-2.0 |
def log_table(
self,
columns: list[str],
rows: list[list[Any]],
name: str = 'Table',
step: Optional[int] = None,
) -> None:
"""Log a table.
Args:
columns (list[str]): Names of the columns in the table.
rows (list[list[Any]]): 2D row-or... | Log a table.
Args:
columns (list[str]): Names of the columns in the table.
rows (list[list[Any]]): 2D row-oriented array of values.
name (str): Name of table. (Default: ``'Table'``)
step (Optional[int], optional): The current step or batch of training at the
... | log_table | python | mosaicml/composer | composer/loggers/logger_destination.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/logger_destination.py | Apache-2.0 |
def log_images(
self,
images: Union[np.ndarray, torch.Tensor, Sequence[Union[np.ndarray, torch.Tensor]]],
name: str = 'Images',
channels_last: bool = False,
step: Optional[int] = None,
masks: Optional[dict[str, Union[np.ndarray, torch.Tensor, Sequence[Union[np.ndarray, to... | Log images. Logs any tensors or arrays as images.
Args:
images (np.ndarray | torch.Tensor | Sequence[np.ndarray | torch.Tensor]): Dictionary mapping
image(s)' names (str) to an image of array of images.
name (str): The name of the image(s). (Default: ``'Images'``)
... | log_images | python | mosaicml/composer | composer/loggers/logger_destination.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/logger_destination.py | Apache-2.0 |
def upload_file(
self,
state: State,
remote_file_name: str,
file_path: pathlib.Path,
*,
overwrite: bool,
):
"""Handle uploading a file stored at ``file_path`` to a file named ``remote_file_name``.
Subclasses should implement this method to store logge... | Handle uploading a file stored at ``file_path`` to a file named ``remote_file_name``.
Subclasses should implement this method to store logged files (e.g. copy it to another folder or upload it to
an object store). However, not all loggers need to implement this method.
For example, the :class:`... | upload_file | python | mosaicml/composer | composer/loggers/logger_destination.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/logger_destination.py | Apache-2.0 |
def download_file(
self,
remote_file_name: str,
destination: str,
overwrite: bool = False,
progress_bar: bool = True,
):
"""Handle downloading a file named ``remote_file_name`` to ``destination``.
Args:
remote_file_name (str): The name of the file... | Handle downloading a file named ``remote_file_name`` to ``destination``.
Args:
remote_file_name (str): The name of the file.
destination (str): The destination filepath.
overwrite (bool): Whether to overwrite an existing file at ``destination``. Defaults to ``False``.
... | download_file | python | mosaicml/composer | composer/loggers/logger_destination.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/logger_destination.py | Apache-2.0 |
def register_model(
self,
model_uri: str,
name: str,
await_registration_for: int = 300,
tags: Optional[dict[str, Any]] = None,
) -> 'ModelVersion':
"""Register a model to model registry.
Args:
model_uri (str): The URI of the model to register.
... | Register a model to model registry.
Args:
model_uri (str): The URI of the model to register.
name (str): The name of the model to register. Will be appended to ``model_registry_prefix``.
await_registration_for (int, optional): The number of seconds to wait for the model to b... | register_model | python | mosaicml/composer | composer/loggers/mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/mlflow_logger.py | Apache-2.0 |
def save_model(self, flavor: Literal['transformers'], **kwargs):
"""Save a model to MLflow.
Args:
flavor (Literal['transformers']): The MLflow model flavor to use. Currently only ``'transformers'`` is supported.
**kwargs: Keyword arguments to pass to the MLflow model saving func... | Save a model to MLflow.
Args:
flavor (Literal['transformers']): The MLflow model flavor to use. Currently only ``'transformers'`` is supported.
**kwargs: Keyword arguments to pass to the MLflow model saving function.
Raises:
NotImplementedError: If ``flavor`` is not... | save_model | python | mosaicml/composer | composer/loggers/mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/mlflow_logger.py | Apache-2.0 |
def log_model(self, flavor: Literal['transformers'], **kwargs):
"""Log a model to MLflow.
Args:
flavor (Literal['transformers']): The MLflow model flavor to use. Currently only ``'transformers'`` is supported.
**kwargs: Keyword arguments to pass to the MLflow model logging funct... | Log a model to MLflow.
Args:
flavor (Literal['transformers']): The MLflow model flavor to use. Currently only ``'transformers'`` is supported.
**kwargs: Keyword arguments to pass to the MLflow model logging function.
Raises:
NotImplementedError: If ``flavor`` is not... | log_model | python | mosaicml/composer | composer/loggers/mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/mlflow_logger.py | Apache-2.0 |
def register_model_with_run_id(
self,
model_uri: str,
name: str,
await_creation_for: int = 300,
tags: Optional[dict[str, Any]] = None,
):
"""Similar to ``register_model``, but uses a different MLflow API to allow passing in the run id.
Args:
model... | Similar to ``register_model``, but uses a different MLflow API to allow passing in the run id.
Args:
model_uri (str): The URI of the model to register.
name (str): The name of the model to register. Will be appended to ``model_registry_prefix``.
await_creation_for (int, opti... | register_model_with_run_id | python | mosaicml/composer | composer/loggers/mlflow_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/mlflow_logger.py | Apache-2.0 |
def log_metadata(self, metadata: dict[str, Any], force_flush: bool = False) -> None:
"""Buffer metadata and prefix keys with mosaicml."""
if self._enabled:
for key, val in metadata.items():
if self.ignore_keys and any(fnmatch.fnmatch(key, pattern) for pattern in self.ignore_k... | Buffer metadata and prefix keys with mosaicml. | log_metadata | python | mosaicml/composer | composer/loggers/mosaicml_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/mosaicml_logger.py | Apache-2.0 |
def _flush_metadata(self, force_flush: bool = False, future: bool = True) -> None:
"""Flush buffered metadata to MosaicML if enough time has passed since last flush."""
if self._enabled and len(
self.buffered_metadata,
) > 0 and (time.time() - self.time_last_logged > self.log_interva... | Flush buffered metadata to MosaicML if enough time has passed since last flush. | _flush_metadata | python | mosaicml/composer | composer/loggers/mosaicml_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/mosaicml_logger.py | Apache-2.0 |
def format_data_to_json_serializable(data: Any):
"""Recursively formats data to be JSON serializable.
Args:
data: Data to format.
Returns:
str: ``data`` as a string.
"""
try:
ret = None
if data is None:
ret = 'None'
elif type(data) in (str, int, ... | Recursively formats data to be JSON serializable.
Args:
data: Data to format.
Returns:
str: ``data`` as a string.
| format_data_to_json_serializable | python | mosaicml/composer | composer/loggers/mosaicml_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/mosaicml_logger.py | Apache-2.0 |
def exception_to_json_serializable_dict(exc: Exception):
"""Converts exception into a JSON serializable dictionary for run metadata."""
default_exc_attrs = set(dir(Exception()))
exc_data = {'class': exc.__class__.__name__, 'message': str(exc), 'attributes': {}}
for attr in dir(exc):
# Exclude d... | Converts exception into a JSON serializable dictionary for run metadata. | exception_to_json_serializable_dict | python | mosaicml/composer | composer/loggers/mosaicml_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/mosaicml_logger.py | Apache-2.0 |
def neptune_run(self):
"""Gets the Neptune run object from a NeptuneLogger instance.
To log additional metadata to the run, access a path inside the run and assign metadata
with ``=`` or other `Neptune logging methods <https://docs.neptune.ai/logging/methods/>`_.
"""
from neptun... | Gets the Neptune run object from a NeptuneLogger instance.
To log additional metadata to the run, access a path inside the run and assign metadata
with ``=`` or other `Neptune logging methods <https://docs.neptune.ai/logging/methods/>`_.
| neptune_run | python | mosaicml/composer | composer/loggers/neptune_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/neptune_logger.py | Apache-2.0 |
def _sanitize_metrics(self, metrics: dict[str, float], step: Optional[int]) -> dict[str, float]:
"""Sanitize metrics to prevent duplicate step logging.
Args:
metrics (dict[str, float]): Metrics to log.
step (Optional[int]): Step to log metrics at.
Returns:
d... | Sanitize metrics to prevent duplicate step logging.
Args:
metrics (dict[str, float]): Metrics to log.
step (Optional[int]): Step to log metrics at.
Returns:
dict[str, float]: Sanitized metrics.
| _sanitize_metrics | python | mosaicml/composer | composer/loggers/neptune_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/neptune_logger.py | Apache-2.0 |
def _build_pbar(self, state: State, is_train: bool) -> _ProgressBar:
"""Builds a pbar.
* If ``state.max_duration.unit`` is :attr:`.TimeUnit.EPOCH`, then a new progress bar will be created for each epoch.
Mid-epoch evaluation progress bars will be labeled with the batch and epoch number.
... | Builds a pbar.
* If ``state.max_duration.unit`` is :attr:`.TimeUnit.EPOCH`, then a new progress bar will be created for each epoch.
Mid-epoch evaluation progress bars will be labeled with the batch and epoch number.
* Otherwise, one progress bar will be used for all of training. Evaluat... | _build_pbar | python | mosaicml/composer | composer/loggers/progress_bar_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/progress_bar_logger.py | Apache-2.0 |
def remote_backend(self) -> ObjectStore:
"""The :class:`.ObjectStore` instance for the main thread."""
if self._remote_backend is None:
self._remote_backend = build_remote_backend(self.remote_backend_name, self.backend_kwargs)
return self._remote_backend | The :class:`.ObjectStore` instance for the main thread. | remote_backend | python | mosaicml/composer | composer/loggers/remote_uploader_downloader.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/remote_uploader_downloader.py | Apache-2.0 |
def _enqueue_uploads(self):
"""Worker thread to enqueue uploads.
This thread does two things:
1. It enqueues objects from ``self._logged_objects`` onto ``self._file_upload_queue``.
2. It keeps ``self._enqueued_objects`` in sync with ``self._file_upload_queue`` by listening to ``self.... | Worker thread to enqueue uploads.
This thread does two things:
1. It enqueues objects from ``self._logged_objects`` onto ``self._file_upload_queue``.
2. It keeps ``self._enqueued_objects`` in sync with ``self._file_upload_queue`` by listening to ``self._completed_uploads``.
| _enqueue_uploads | python | mosaicml/composer | composer/loggers/remote_uploader_downloader.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/remote_uploader_downloader.py | Apache-2.0 |
def wait_for_workers(self, device: Device):
"""Wait for all tasks to be completed.
This is called after fit/eval/predict. If we don't wait, then a worker might not schedule
an upload before the interpreter is shutdown and garbage collection begins. While
post_close logic ensures existin... | Wait for all tasks to be completed.
This is called after fit/eval/predict. If we don't wait, then a worker might not schedule
an upload before the interpreter is shutdown and garbage collection begins. While
post_close logic ensures existing uploads are completed, trying to schedule new uploads... | wait_for_workers | python | mosaicml/composer | composer/loggers/remote_uploader_downloader.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/remote_uploader_downloader.py | Apache-2.0 |
def _upload_worker(
file_queue: Union[queue.Queue[tuple[str, str, bool]], multiprocessing.JoinableQueue[tuple[str, str, bool]]],
completed_queue: Union[queue.Queue[str], multiprocessing.JoinableQueue[str]],
exception_queue: Union[queue.Queue[Exception], multiprocessing.JoinableQueue[Exception]],
is_fini... | A long-running function to handle uploading files to the object store.
The worker will continuously poll ``file_queue`` for files to upload. Once ``is_finished`` is set, the worker will
exit once ``file_queue`` is empty.
| _upload_worker | python | mosaicml/composer | composer/loggers/remote_uploader_downloader.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/remote_uploader_downloader.py | Apache-2.0 |
def _log_to_buffer(
self,
data: dict[str, Any],
**kwargs, # can be used to pass additional arguments to the formatter function (eg for headers)
):
"""Flush the buffer to slack if the buffer size exceeds max_logs_per_message.
Buffer will replace existing keys with updated va... | Flush the buffer to slack if the buffer size exceeds max_logs_per_message.
Buffer will replace existing keys with updated values if keys exist.
Otherwise, add new key-value pairs.
If max_logs_per_message is exceeded, flush buffer.
Otherwise, wait for the next log_interval (batch end or ... | _log_to_buffer | python | mosaicml/composer | composer/loggers/slack_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/slack_logger.py | Apache-2.0 |
def _default_log_bold_key_normal_value_pair_with_header(
self,
data: dict[str, Any],
**kwargs,
) -> list[dict[str, Any]]:
"""Default formatter function if no formatter func is specified.
This function will:
1. Log the key-value pairs in bold (key) and normal (value) ... | Default formatter function if no formatter func is specified.
This function will:
1. Log the key-value pairs in bold (key) and normal (value) text.
2. When logging metrics, set the step number as the header of the section.
Args:
data (dict[str, Any]): Data to be logged.
... | _default_log_bold_key_normal_value_pair_with_header | python | mosaicml/composer | composer/loggers/slack_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/slack_logger.py | Apache-2.0 |
def _flush_logs_to_slack(self, **kwargs) -> None:
"""Flush buffered metadata to MosaicML.
Format slack messages through rich message layouts created using Slack Blocks Kit.
See documentation here: https://api.slack.com/messaging/composing/layouts.
"""
inx = 0
while inx <... | Flush buffered metadata to MosaicML.
Format slack messages through rich message layouts created using Slack Blocks Kit.
See documentation here: https://api.slack.com/messaging/composing/layouts.
| _flush_logs_to_slack | python | mosaicml/composer | composer/loggers/slack_logger.py | https://github.com/mosaicml/composer/blob/master/composer/loggers/slack_logger.py | Apache-2.0 |
def binary_cross_entropy_with_logits(
input: Tensor,
target: Tensor,
weight: Optional[Tensor] = None,
reduction: str = 'sum',
pos_weight: Optional[Tensor] = None,
scale_by_batch_size: Optional[bool] = True,
) -> torch.Tensor:
r"""Replacement for :class:`~F.binary_cross_entropy_with_logits` t... | Replacement for :class:`~F.binary_cross_entropy_with_logits` that handles class indices or one-hot labels.
:class:`~torch.nn.functional.binary_cross_entropy_with_logits` with ``reduction =
'mean'` will typically result in very small loss values (on the order of 1e-3), which
necessitates scaling the learnin... | binary_cross_entropy_with_logits | python | mosaicml/composer | composer/loss/loss.py | https://github.com/mosaicml/composer/blob/master/composer/loss/loss.py | Apache-2.0 |
def soft_cross_entropy(
input: Tensor,
target: Tensor,
weight: Optional[Tensor] = None,
ignore_index: int = -100,
reduction: str = 'mean',
):
r"""Drop-in replacement for :class:`~.F.cross_entropy` that handles class indices or one-hot labels.
.. note::
This function will be obsolet... | Drop-in replacement for :class:`~.F.cross_entropy` that handles class indices or one-hot labels.
.. note::
This function will be obsolete with `this update <https://github.com/pytorch/pytorch/pull/61044>`_.
Args:
input (torch.Tensor) : :math:`(N, C)` where `C = number of classes` or :math:`(N... | soft_cross_entropy | python | mosaicml/composer | composer/loss/loss.py | https://github.com/mosaicml/composer/blob/master/composer/loss/loss.py | Apache-2.0 |
def infer_target_type(input: torch.Tensor, targets: torch.Tensor) -> str:
"""Infers whether the target is in indices format or one_hot format.
Example indices format: [1, 4, 7] Example one_hot format [[0, 1, 0], [1, 0, 0], ...]
"""
if input.shape == targets.shape:
return 'one_hot'
elif inpu... | Infers whether the target is in indices format or one_hot format.
Example indices format: [1, 4, 7] Example one_hot format [[0, 1, 0], [1, 0, 0], ...]
| infer_target_type | python | mosaicml/composer | composer/loss/utils.py | https://github.com/mosaicml/composer/blob/master/composer/loss/utils.py | Apache-2.0 |
def ensure_targets_one_hot(
input: torch.Tensor,
targets: torch.Tensor,
num_classes: Optional[int] = None,
) -> torch.Tensor:
r"""Ensures that the targets are in a one-hot format rather than an index format.
Args:
input (torch.Tensor): :math:`(N, C)` where `C = number of classes` or :math:`... | Ensures that the targets are in a one-hot format rather than an index format.
Args:
input (torch.Tensor): :math:`(N, C)` where `C = number of classes` or :math:`(N, C, H, W)`
in case of 2D Loss, or :math:`(N, C, d_1, d_2, ..., d_K)` where :math:`K \geq 1`
in the case of K-dimensiona... | ensure_targets_one_hot | python | mosaicml/composer | composer/loss/utils.py | https://github.com/mosaicml/composer/blob/master/composer/loss/utils.py | Apache-2.0 |
def check_for_index_targets(targets: torch.Tensor) -> bool:
"""Checks if a given set of targets are indices by looking at the type."""
index_dtypes = [torch.uint8, torch.int8, torch.int16, torch.int32, torch.int64]
return targets.dtype in index_dtypes | Checks if a given set of targets are indices by looking at the type. | check_for_index_targets | python | mosaicml/composer | composer/loss/utils.py | https://github.com/mosaicml/composer/blob/master/composer/loss/utils.py | Apache-2.0 |
def _one_hot(tensor: torch.Tensor, num_classes: int = -1, dim: int = -1) -> torch.Tensor:
"""Converts a tensor of index class labels to a tensor of one-hot class labels.
Implementation is based on MONAI one-hot conversion function:
`<https://github.com/Project-MONAI/MONAI/blob/b390b0956334325edc0e5000afb58... | Converts a tensor of index class labels to a tensor of one-hot class labels.
Implementation is based on MONAI one-hot conversion function:
`<https://github.com/Project-MONAI/MONAI/blob/b390b0956334325edc0e5000afb58e2be7cbe550/monai/networks/utils.py#L49>`_.
Args:
tensor (torch.Tensor): Tensor cont... | _one_hot | python | mosaicml/composer | composer/loss/utils.py | https://github.com/mosaicml/composer/blob/master/composer/loss/utils.py | Apache-2.0 |
def update(self, preds: list[dict[str, Tensor]], target: list[dict[str, Tensor]]) -> None: # type: ignore
"""Add detections and groundtruth to the metric.
Args:
preds (list[dict[str, ~torch.Tensor]]): A list of dictionaries containing the key-values:
``boxes`` (torch.F... | Add detections and groundtruth to the metric.
Args:
preds (list[dict[str, ~torch.Tensor]]): A list of dictionaries containing the key-values:
``boxes`` (torch.FloatTensor): [num_boxes, 4] predicted boxes of the format [xmin, ymin, xmax, ymax] in absolute image coordinates.
... | update | python | mosaicml/composer | composer/metrics/map.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/map.py | Apache-2.0 |
def compute(self) -> dict:
"""Compute the Mean-Average-Precision (mAP) and Mean-Average-Recall (mAR) scores.
All detections added in the ``update()`` method are included.
Note:
Main `map` score is calculated with @[ IoU=0.50:0.95 | area=all | maxDets=100 ]
Returns:
... | Compute the Mean-Average-Precision (mAP) and Mean-Average-Recall (mAR) scores.
All detections added in the ``update()`` method are included.
Note:
Main `map` score is calculated with @[ IoU=0.50:0.95 | area=all | maxDets=100 ]
Returns:
MAPMetricResults (dict): containi... | compute | python | mosaicml/composer | composer/metrics/map.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/map.py | Apache-2.0 |
def _get_coco_format(
self,
boxes: list[torch.Tensor],
labels: list[torch.Tensor],
scores: Optional[list[torch.Tensor]] = None,
) -> dict:
"""Transforms and returns all cached targets or predictions in COCO format.
Format is defined at https://cocodataset.org/#format... | Transforms and returns all cached targets or predictions in COCO format.
Format is defined at https://cocodataset.org/#format-data.
| _get_coco_format | python | mosaicml/composer | composer/metrics/map.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/map.py | Apache-2.0 |
def update(self, logits: Tensor, targets: Tensor):
"""Update the state with new predictions and targets."""
preds = logits.argmax(dim=1)
for pred, target in zip(preds, targets):
mask = (target != self.ignore_index)
pred = pred[mask]
target = target[mask]
... | Update the state with new predictions and targets. | update | python | mosaicml/composer | composer/metrics/metrics.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/metrics.py | Apache-2.0 |
def compute(self):
"""Aggregate state across all processes and compute final metric."""
total_intersect = self.total_intersect[self.total_union != 0] # type: ignore (third-party)
total_union = self.total_union[self.total_union != 0] # type: ignore (third-party)
return 100 * (total_inte... | Aggregate state across all processes and compute final metric. | compute | python | mosaicml/composer | composer/metrics/metrics.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/metrics.py | Apache-2.0 |
def update(self, preds: Tensor, targets: Tensor):
"""Update the state based on new predictions and targets."""
self.n_updates += 1 # type: ignore
assert isinstance(self.dice, Tensor)
self.dice += self.compute_stats(preds, targets) | Update the state based on new predictions and targets. | update | python | mosaicml/composer | composer/metrics/metrics.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/metrics.py | Apache-2.0 |
def compute(self):
"""Aggregate the state over all processes to compute the metric."""
dice = 100 * self.dice / self.n_updates # type: ignore
best_sum_dice = dice[:]
top_dice = round(torch.mean(best_sum_dice).item(), 2)
return top_dice | Aggregate the state over all processes to compute the metric. | compute | python | mosaicml/composer | composer/metrics/metrics.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/metrics.py | Apache-2.0 |
def compute(self) -> Tensor:
"""Aggregate state over all processes and compute the metric."""
# Return average loss over entire validation dataset
assert isinstance(self.total_batches, Tensor)
assert isinstance(self.sum_loss, Tensor)
return self.sum_loss / self.total_batches | Aggregate state over all processes and compute the metric. | compute | python | mosaicml/composer | composer/metrics/metrics.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/metrics.py | Apache-2.0 |
def update(self, output: Union[Mapping, Tensor], target: Tensor) -> None:
"""Updates the internal state with results from a new batch.
Args:
output (Mapping): The output from the model, which must contain
either the Tensor or a Mapping type that contains the loss or model lo... | Updates the internal state with results from a new batch.
Args:
output (Mapping): The output from the model, which must contain
either the Tensor or a Mapping type that contains the loss or model logits.
target (~torch.Tensor): A Tensor of ground-truth values to compare ... | update | python | mosaicml/composer | composer/metrics/nlp.py | https://github.com/mosaicml/composer/blob/master/composer/metrics/nlp.py | Apache-2.0 |
def eval_forward(
self,
batch: Any,
outputs: Optional[Any] = None,
) -> Any:
"""Run the evaluation forward pass.
By default, it returns the ``outputs`` if they are not None. Otherwise,
``self(batch)`` is returned.
Override this method for models that require custom validation... | Run the evaluation forward pass.
By default, it returns the ``outputs`` if they are not None. Otherwise,
``self(batch)`` is returned.
Override this method for models that require custom validation logic -- e.g. self-supervised learning.
Args:
batch: The dataloader batch.
outputs (Any, optional): If tra... | eval_forward | python | mosaicml/composer | composer/models/base.py | https://github.com/mosaicml/composer/blob/master/composer/models/base.py | Apache-2.0 |
def update_metric(
self,
batch: Any,
outputs: Any,
metric: Metric,
) -> Optional[dict]:
"""Update the given metric.
Args:
batch: The dataloader batch
outputs: The output from :meth:`eval_forward`
metric (Metric): The metric to update.
Returns:
... | Update the given metric.
Args:
batch: The dataloader batch
outputs: The output from :meth:`eval_forward`
metric (Metric): The metric to update.
Returns:
Optional[dict]: Optionally return metric results to be stored in state.
| update_metric | python | mosaicml/composer | composer/models/base.py | https://github.com/mosaicml/composer/blob/master/composer/models/base.py | Apache-2.0 |
def _get_model_forward_args(self) -> set[str]:
"""Returns the arguments to the model's forward function."""
model_forward_args = inspect.signature(maybe_get_underlying_model(self.model).forward).parameters.keys()
if not model_forward_args:
raise ValueError('Could not determine the f... | Returns the arguments to the model's forward function. | _get_model_forward_args | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def state_dict(self, *args, **kwargs) -> dict[str, Any]:
"""Returns the state dict of the model."""
full_state_dict = super().state_dict(*args, **kwargs)
if self.using_peft and self.should_save_peft_only:
active_adapter = self.model.active_adapter
assert isinstance(activ... | Returns the state dict of the model. | state_dict | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def load_huggingface_tokenizer_from_saved_state(
hf_state: dict[str, Any],
trust_remote_code: bool = False,
tokenizer_save_dir: Optional[str] = None,
) -> Optional[transformers.PreTrainedTokenizer | transformers.PreTrainedTokenizerFast]:
"""A helper function that loads a HuggingFace ... | A helper function that loads a HuggingFace tokenizer from a loaded in hf state.
Args:
hf_state (dict[str, Any]): HF state loaded from a Composer checkpoint.
trust_remote_code (bool, optional): Whether to trust the remote code when loading the tokenizer. Defaults to False.
to... | load_huggingface_tokenizer_from_saved_state | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def load_huggingface_model_from_saved_state(
hf_state: dict[str, Any],
loaded_state_dict: dict[str, dict[str, dict[str, dict[str, Any]]]],
model_instantiation_class: type | str | None,
model_config_kwargs: dict[str, Any] | None,
) -> transformers.PreTrainedModel:
"""A helper ... | A helper function that loads a HuggingFace model class from a loaded in hf state.
Args:
hf_state (dict[str, Any]): HF state loaded from a Composer checkpoint.
model_instantiation_class (Union[Type[:class:`transformers.PreTrainedModel`], Type[:class:`transformers.AutoModel`], str]), opti... | load_huggingface_model_from_saved_state | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def hf_from_composer_checkpoint(
checkpoint_path: str,
model_instantiation_class: Optional[Union[
type[transformers.PreTrainedModel],
type['_BaseAutoModelClass'],
str,
]] = None,
model_config_kwargs: Optional[dict] = None,
local_checkpoint_save... | Loads a HuggingFace model (and tokenizer if present) from a composer checkpoint.
.. note:: This function does not load the weights from the checkpoint. It just loads the correctly configured
model and tokenizer classes.
.. testsetup::
import torch
dataset = Random... | hf_from_composer_checkpoint | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def generate(self, input_ids: torch.Tensor, **kwargs):
"""Generate from the underlying HuggingFace model.
Except for ``pad_token_id``, which is optionally read from ``self.tokenizer``, all args are passed along
to :meth:`transformers.GenerationMixin.generate` function.
Args:
... | Generate from the underlying HuggingFace model.
Except for ``pad_token_id``, which is optionally read from ``self.tokenizer``, all args are passed along
to :meth:`transformers.GenerationMixin.generate` function.
Args:
input_ids (torch.Tensor): Input ids to generate from.
... | generate | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def _maybe_get_peft_model(
peft_config: 'PeftConfig',
model: Union[transformers.PreTrainedModel, 'PeftModel'],
) -> 'PeftModel':
"""Creates a PEFT model if the model is not already a PEFT model.
Args:
peft_config (Optional[peft.PeftConfig]): The PEFT config to use to create the PEFT model
... | Creates a PEFT model if the model is not already a PEFT model.
Args:
peft_config (Optional[peft.PeftConfig]): The PEFT config to use to create the PEFT model
model (Union[transformers.PreTrainedModel, 'PeftModel']): The model to create the PEFT model from
Returns:
PeftModel: The PEFT m... | _maybe_get_peft_model | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def maybe_get_underlying_model(
model: Union[transformers.PreTrainedModel, 'PeftModel'],
) -> Union[transformers.PreTrainedModel, 'PeftModel']:
"""Get the underlying PreTrainedModel from a model if it is a PEFT model
Args:
model (Union[transformers.PreTrainedModel, 'PeftModel']): The model to get t... | Get the underlying PreTrainedModel from a model if it is a PEFT model
Args:
model (Union[transformers.PreTrainedModel, 'PeftModel']): The model to get the underlying model from
Returns:
Union[transformers.PreTrainedModel]: The underlying transformers model
| maybe_get_underlying_model | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def get_hf_config_from_composer_state_dict(
state_dict: dict[str, Any],
config_overrides: Optional[dict[str, Any]] = None,
) -> 'PretrainedConfig':
"""Get a HuggingFace config from a composer state dict with overrides applied
Args:
state_dict (dict[str, Any]): The state dict to get the config f... | Get a HuggingFace config from a composer state dict with overrides applied
Args:
state_dict (dict[str, Any]): The state dict to get the config from
config_overrides (dict[str, Any], optional): Any overrides to apply to the config
Returns:
transformers.PretrainedConfig: The HuggingFace ... | get_hf_config_from_composer_state_dict | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def get_peft_config_from_composer_state_dict(state_dict: dict[str, Any]) -> Optional['PeftConfig']:
"""Get a PEFT config from a composer state dict
Args:
state_dict (dict[str, Any]): The state dict to get the config from
Returns:
Optional[peft.PeftConfig]: The PEFT config. Will be ``None``... | Get a PEFT config from a composer state dict
Args:
state_dict (dict[str, Any]): The state dict to get the config from
Returns:
Optional[peft.PeftConfig]: The PEFT config. Will be ``None`` if the model is not a PEFT model.
| get_peft_config_from_composer_state_dict | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def write_huggingface_pretrained_from_composer_checkpoint(
checkpoint_path: Union[Path, str],
output_folder: Union[Path, str],
local_checkpoint_save_location: Optional[Union[Path, str]] = None,
) -> None:
"""Write a ``config.json`` and ``pytorch_model.bin``, like :meth:`transformers.PreTrainedModel.from... | Write a ``config.json`` and ``pytorch_model.bin``, like :meth:`transformers.PreTrainedModel.from_pretrained` expects, from a composer checkpoint
.. note:: This function will not work properly if you used surgery algorithms when you trained your model. In that case you will want to
load the model weights us... | write_huggingface_pretrained_from_composer_checkpoint | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def filter_state_dict_peft(
state_dict: dict[str, Any],
peft_config: 'PeftConfig',
adapter_name: str = 'default',
remove_adapter_names: bool = True,
) -> dict[str, Any]:
"""Filter a state dict to only include the weights needed for a PEFT model
Note: This function only works with LORA PEFT mode... | Filter a state dict to only include the weights needed for a PEFT model
Note: This function only works with LORA PEFT models right now.
Args:
state_dict (dict[str, Any]): The state dict to filter
peft_config (PeftConfig): The PEFT config to use to filter the state dict
adapter_name (st... | filter_state_dict_peft | python | mosaicml/composer | composer/models/huggingface.py | https://github.com/mosaicml/composer/blob/master/composer/models/huggingface.py | Apache-2.0 |
def get_initializer(self) -> Callable[[torch.nn.Module], None]:
"""Get the initializer function.
Returns:
(torch.nn.Module) -> None: The initializer function.
"""
def kaiming_normal(w: nn.Module):
if isinstance(w, (torch.nn.Linear, torch.nn.Conv2d)):
... | Get the initializer function.
Returns:
(torch.nn.Module) -> None: The initializer function.
| get_initializer | python | mosaicml/composer | composer/models/initializers.py | https://github.com/mosaicml/composer/blob/master/composer/models/initializers.py | Apache-2.0 |
def sgdw(
params: list[torch.Tensor],
d_p_list: list[torch.Tensor],
momentum_buffer_list: list[Optional[torch.Tensor]],
*,
weight_decay: float,
momentum: float,
lr: float,
initial_lr: float,
dampening: float,
nesterov: bool,
):
... | Functional API that performs SGDW algorithm computation.
Args:
params (list): list of parameters to update
d_p_list (list): list of parameter gradients
momentum_buffer_list (list): list of momentum buffers
weight_decay (float): Decoupled weight decay factor
... | sgdw | python | mosaicml/composer | composer/optim/decoupled_weight_decay.py | https://github.com/mosaicml/composer/blob/master/composer/optim/decoupled_weight_decay.py | Apache-2.0 |
def adamw(
params: list[torch.Tensor],
grads: list[torch.Tensor],
exp_avgs: list[torch.Tensor],
exp_avg_sqs: list[torch.Tensor],
max_exp_avg_sqs: list[torch.Tensor],
state_steps: list[torch.Tensor],
*,
amsgrad: bool,
beta1: float,
beta2: fl... | Functional API that performs AdamW algorithm computation with decoupled weight decay.
Args:
params (list): list of parameters to update.
grads (list): list of parameter gradients.
exp_avgs (list): list of average gradients.
exp_avg_sqs (list): list of average squ... | adamw | python | mosaicml/composer | composer/optim/decoupled_weight_decay.py | https://github.com/mosaicml/composer/blob/master/composer/optim/decoupled_weight_decay.py | Apache-2.0 |
def compile_composer_scheduler(scheduler: ComposerScheduler, state: State, ssr: float = 1.0) -> LRScheduler:
"""Converts a stateless scheduler into a PyTorch scheduler object.
While the resulting scheduler provides a ``.step()`` interface similar to other PyTorch schedulers, the scheduler is
also given a b... | Converts a stateless scheduler into a PyTorch scheduler object.
While the resulting scheduler provides a ``.step()`` interface similar to other PyTorch schedulers, the scheduler is
also given a bound reference to the current :class:`~composer.core.State`. This means that any internal state updated
by ``.st... | compile_composer_scheduler | python | mosaicml/composer | composer/optim/scheduler.py | https://github.com/mosaicml/composer/blob/master/composer/optim/scheduler.py | Apache-2.0 |
def _cosine_anneal(x: float, min_y: float = 0.0, max_y: float = 1.0) -> float:
"""Implements a cosine decay curve.
Curve is cos(x) on domain [0, pi], stretched to the domain [0, 1] and range [min_y, max_y]. Additionally, param x is
clipped to the interval [0, 1]
"""
x = min(max(x, 0.0), 1.0)
re... | Implements a cosine decay curve.
Curve is cos(x) on domain [0, pi], stretched to the domain [0, 1] and range [min_y, max_y]. Additionally, param x is
clipped to the interval [0, 1]
| _cosine_anneal | python | mosaicml/composer | composer/optim/scheduler.py | https://github.com/mosaicml/composer/blob/master/composer/optim/scheduler.py | Apache-2.0 |
def _raise_if_warmup_and_max_incompatible(t_warmup: Time[int], t_max: Time[int]):
"""Checks that t_warmup and t_max have the same units.
_convert_time should be called on both `t_warmup` and `t_max` before this function is called. As a a result, t_warmup and t_max will not
be TimeUnit.EPOCH.
"""
as... | Checks that t_warmup and t_max have the same units.
_convert_time should be called on both `t_warmup` and `t_max` before this function is called. As a a result, t_warmup and t_max will not
be TimeUnit.EPOCH.
| _raise_if_warmup_and_max_incompatible | python | mosaicml/composer | composer/optim/scheduler.py | https://github.com/mosaicml/composer/blob/master/composer/optim/scheduler.py | Apache-2.0 |
def _record_event(self, name: str, ph: str, wall_clock_ns: int, pid: int, tid: int, categories: str = '', **kwargs):
"""Helper function to record an event in the trace.
Args:
name (str): Event name
categories (str): Comma-separated string of event categories
ph (str)... | Helper function to record an event in the trace.
Args:
name (str): Event name
categories (str): Comma-separated string of event categories
ph (str): Event type. Should be one of the following
Duration Events: ``B`` (begin), ``E`` (end)
Complet... | _record_event | python | mosaicml/composer | composer/profiler/json_trace_handler.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/json_trace_handler.py | Apache-2.0 |
def merge_traces(output_file: Union[str, pathlib.Path], *trace_files: Union[str, pathlib.Path]):
"""Merge profiler output JSON trace files together.
This function will update the trace events such that:
- The ``pid`` will be set to the global rank.
- The ``ts`` is synchronized with that of the rank 0 ... | Merge profiler output JSON trace files together.
This function will update the trace events such that:
- The ``pid`` will be set to the global rank.
- The ``ts`` is synchronized with that of the rank 0 process.
- The backward pass process appears below the forward process.
Args:
output_fi... | merge_traces | python | mosaicml/composer | composer/profiler/json_trace_merger.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/json_trace_merger.py | Apache-2.0 |
def start(self) -> None:
"""Record the start of a duration event.
To record the duration of an event, invoke :meth:`.Marker.start` followed by :meth:`.Marker.finish`.
.. testsetup::
from composer.profiler import Profiler, cyclic_schedule
profiler = Profiler(schedule=cy... | Record the start of a duration event.
To record the duration of an event, invoke :meth:`.Marker.start` followed by :meth:`.Marker.finish`.
.. testsetup::
from composer.profiler import Profiler, cyclic_schedule
profiler = Profiler(schedule=cyclic_schedule(), trace_handlers=[], ... | start | python | mosaicml/composer | composer/profiler/marker.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/marker.py | Apache-2.0 |
def finish(self) -> None:
"""Record the end of a duration event.
See :meth:`.Marker.start()` for a usage example.
"""
if not self._started:
raise RuntimeError(
f'Attempted to finish profiler event {self.name}; however, this profiler event is not yet started',... | Record the end of a duration event.
See :meth:`.Marker.start()` for a usage example.
| finish | python | mosaicml/composer | composer/profiler/marker.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/marker.py | Apache-2.0 |
def instant(self) -> None:
"""Record an instant event.
To record an instant event:
.. testsetup::
from composer.profiler import Profiler, cyclic_schedule
profiler = Profiler(schedule=cyclic_schedule(), trace_handlers=[], torch_prof_memory_filename=None)
pro... | Record an instant event.
To record an instant event:
.. testsetup::
from composer.profiler import Profiler, cyclic_schedule
profiler = Profiler(schedule=cyclic_schedule(), trace_handlers=[], torch_prof_memory_filename=None)
profiler.bind_to_state(state)
..... | instant | python | mosaicml/composer | composer/profiler/marker.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/marker.py | Apache-2.0 |
def counter(self, values: dict[str, Union[float, int]]) -> None:
"""Record a counter event.
To record a counter event:
.. testsetup::
from composer.profiler import Profiler, cyclic_schedule
profiler = Profiler(schedule=cyclic_schedule(), trace_handlers=[], torch_prof_m... | Record a counter event.
To record a counter event:
.. testsetup::
from composer.profiler import Profiler, cyclic_schedule
profiler = Profiler(schedule=cyclic_schedule(), trace_handlers=[], torch_prof_memory_filename=None)
profiler.bind_to_state(state)
.. d... | counter | python | mosaicml/composer | composer/profiler/marker.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/marker.py | Apache-2.0 |
def bind_to_state(
self,
state: State,
):
"""Bind the profiler to the ``state``.
.. note::
The :class:`.Trainer` automatically invokes this method.
Args:
state (State): The training state.
"""
self.state = state
self.state.ca... | Bind the profiler to the ``state``.
.. note::
The :class:`.Trainer` automatically invokes this method.
Args:
state (State): The training state.
| bind_to_state | python | mosaicml/composer | composer/profiler/profiler.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/profiler.py | Apache-2.0 |
def marker(
self,
name: str,
actions: Sequence[ProfilerAction] = (
ProfilerAction.WARMUP,
ProfilerAction.ACTIVE,
ProfilerAction.ACTIVE_AND_SAVE,
),
record_instant_on_start: bool = False,
record_instant_on_finish: bool = False,
c... | Create and get an instance of a :class:`.Marker`.
If a :class:`.Marker` with the specified ``name`` does not already exist, it will be created.
Otherwise, the existing instance will be returned.
.. note::
:meth:`.Profiler.marker()` should be used to construct markers. :class:`.Ma... | marker | python | mosaicml/composer | composer/profiler/profiler.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/profiler.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.