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 cyclic_schedule(
skip_first: int = 0,
wait: int = 0,
warmup: int = 1,
active: int = 4,
repeat: int = 1,
) -> Callable[[State], ProfilerAction]:
"""Profiler schedule function for a cyclic profiling window.
This function returns a schedule function that uses a cyclic profiling window. The... | Profiler schedule function for a cyclic profiling window.
This function returns a schedule function that uses a cyclic profiling window. The resulting function can be
passed as the ``prof_schedule`` argument to the :class:`.Trainer`.
The cyclic window skips the first ``skip_first`` + ``resumption_batch_id... | cyclic_schedule | python | mosaicml/composer | composer/profiler/profiler_schedule.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/profiler_schedule.py | Apache-2.0 |
def process_instant_event(
self,
name: str,
categories: Union[list[str], tuple[str, ...]],
timestamp: Timestamp,
wall_clock_time_ns: int,
) -> None:
"""Invoked whenever there is an instant event to record.
Args:
name (str): The name of the event.
... | Invoked whenever there is an instant event to record.
Args:
name (str): The name of the event.
categories (list[str] | tuple[str, ...]): The categories for the event.
timestamp (Timestamp): Snapshot of current training time.
wall_clock_time_ns (int): The :py:func... | process_instant_event | python | mosaicml/composer | composer/profiler/trace_handler.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/trace_handler.py | Apache-2.0 |
def process_counter_event(
self,
name: str,
categories: Union[list[str], tuple[str, ...]],
timestamp: Timestamp,
wall_clock_time_ns: int,
values: dict[str, Union[int, float]],
) -> None:
"""Invoked whenever there is an counter event to record.
Args:
... | Invoked whenever there is an counter event to record.
Args:
name (str): The name of the event.
categories (list[str] | tuple[str, ...]): The categories for the event.
timestamp (Timestamp): The timestamp.
wall_clock_time_ns (int): The :py:func:`time.time_ns` corr... | process_counter_event | python | mosaicml/composer | composer/profiler/trace_handler.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/trace_handler.py | Apache-2.0 |
def export_memory_timeline_html(
prof: TorchProfile,
path: str,
device: Optional[str] = None,
figsize=(20, 12),
title=None,
yxis_step_size: float = 1.0,
return_fig: bool = False,
) -> Optional[Union[None, Any]]:
"""Exports a memory timeline to an HTML file. Similar to the PyTorch plottin... | Exports a memory timeline to an HTML file. Similar to the PyTorch plotting function, but with adjusted axis tickers and grids. | export_memory_timeline_html | python | mosaicml/composer | composer/profiler/utils.py | https://github.com/mosaicml/composer/blob/master/composer/profiler/utils.py | Apache-2.0 |
def _filter_metrics(metrics: dict[str, Metric], metric_names: Optional[list[str]]) -> dict[str, Metric]:
"""Filter the metrics based on the given metric_names as regex strings (e.g. 'Accuracy', 'f1' for 'BinaryF1Score', 'Top-.' for 'Top-1 Accuracy' and 'Top-2 Accuracy', etc). If no metric_names are provided, all me... | Filter the metrics based on the given metric_names as regex strings (e.g. 'Accuracy', 'f1' for 'BinaryF1Score', 'Top-.' for 'Top-1 Accuracy' and 'Top-2 Accuracy', etc). If no metric_names are provided, all metrics will be returned. | _filter_metrics | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _get_initial_device_train_microbatch_size(
device_train_microbatch_size: Optional[Union[int, float, str]],
auto_microbatching: bool,
train_dataloader: Optional[Iterable],
) -> Optional[Union[int, float]]:
"""Sets initial value of device_train_microbatch_size.
If auto_microbatching, sets initial... | Sets initial value of device_train_microbatch_size.
If auto_microbatching, sets initial `device_train_microbatch_size` to per rank batch size. If
`train_dataloader` is not set yet, returns None and this function will be called again when
`train_dataloader` is set, such as when `fit()` is called.
| _get_initial_device_train_microbatch_size | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _is_cuda_oom(e: RuntimeError):
"""Determines if error is CUDA Out of Memory and if auto_microbatching is enabled."""
if any(s in str(e) for s in ['CUDA out of memory', 'CUDA error: out of memory']):
return True
# With batch_norm, large batch sizes sometimes result in cuDNN instead of Cuda OOMs.
... | Determines if error is CUDA Out of Memory and if auto_microbatching is enabled. | _is_cuda_oom | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _fsdp_reshard_and_cleanup(model: torch.nn.Module):
"""Manually reshard and clean up FSDP model.
When an exception like OOM happens, _post_backward_final_callback, which
is registered as a backward callback, will not run. We manually call it to cleanup
loose memory.
"""
for __, module in mod... | Manually reshard and clean up FSDP model.
When an exception like OOM happens, _post_backward_final_callback, which
is registered as a backward callback, will not run. We manually call it to cleanup
loose memory.
| _fsdp_reshard_and_cleanup | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _clear_incomplete_train_states(state: State):
"""Manually clear gradients when automicrobatching reruns a batch.
Before automicrobatching tries a lower microbatch size, clear the
training states and memory of the previous run of the batch to reset the memory to
before the batch was run.
"""
... | Manually clear gradients when automicrobatching reruns a batch.
Before automicrobatching tries a lower microbatch size, clear the
training states and memory of the previous run of the batch to reset the memory to
before the batch was run.
| _clear_incomplete_train_states | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _adjust_device_train_microbatch_size(state: State):
"""Adjust device_train_microbatch_size if we encounter OOM.
Args:
state (State): State of trainer.
"""
# If any rank hit CUDA OOM, update device_train_microbatch_size and retry. Raise runtime error
# if training 1 sample at a time stil... | Adjust device_train_microbatch_size if we encounter OOM.
Args:
state (State): State of trainer.
| _adjust_device_train_microbatch_size | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _adjust_device_eval_microbatch_size(evaluator: Evaluator):
"""Adjust device_eval_microbatch_size if we encounter OOM.
Args:
evaluator (State): Current evaluator
"""
# If any rank hit CUDA OOM, update device_eval_microbatch_size and retry. Raise runtime error
# if evaluating 1 sample at ... | Adjust device_eval_microbatch_size if we encounter OOM.
Args:
evaluator (State): Current evaluator
| _adjust_device_eval_microbatch_size | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _readd_fsdp_sync_hooks(fsdp_modules: dict[str, torch.nn.Module], sync_hook):
"""Readds previously removed sync hooks back to FSDP modules.
Called when preparing to search for or searching for new microbatch size during automicrobatching.
"""
automicrobatch_fsdp_hook_handles = []
patch_unshard_f... | Readds previously removed sync hooks back to FSDP modules.
Called when preparing to search for or searching for new microbatch size during automicrobatching.
| _readd_fsdp_sync_hooks | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _validate_evaluator(evaluator: Evaluator, device: Device):
"""Ensure automicrobatching is only on GPU.
Unlike `device_train_microbatch_size`, this validation must be done separately from the
`_is_auto_microbatching` check because `device` is not available during `Evaluator`
initialization.
"""
... | Ensure automicrobatching is only on GPU.
Unlike `device_train_microbatch_size`, this validation must be done separately from the
`_is_auto_microbatching` check because `device` is not available during `Evaluator`
initialization.
| _validate_evaluator | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _get_distributed_sampler(dataloader: DataLoader) -> Optional[DistributedSampler]:
"""Fetch a distributed sampler from a `dataloader` if it exists."""
if isinstance(dataloader.batch_sampler, DistributedSampler):
return dataloader.batch_sampler
if isinstance(dataloader.sampler, DistributedSampler)... | Fetch a distributed sampler from a `dataloader` if it exists. | _get_distributed_sampler | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _wrap_model_for_distributed(
self,
model: ComposerModel,
optimizers: Optional[torch.optim.Optimizer],
precision: Union[str, Precision],
device: Device,
auto_microbatching: bool,
):
"""Wrap the model for distributed training (TP, FSDP, etc.).
Args:... | Wrap the model for distributed training (TP, FSDP, etc.).
Args:
model (ComposerModel): The model to wrap.
optimizers (Optional[torch.optim.Optimizer]): The optimizer(s) to use.
precision (Union[str, Precision]): The precision to use.
device (Device): The device t... | _wrap_model_for_distributed | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def saved_checkpoints(self) -> list[str]:
"""Returns list of saved checkpoints.
.. note::
For sharded checkpointing, which saves file on every rank, only the files corresponding
to the process's rank will be shown.
"""
if self._checkpoint_saver is None:
... | Returns list of saved checkpoints.
.. note::
For sharded checkpointing, which saves file on every rank, only the files corresponding
to the process's rank will be shown.
| saved_checkpoints | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _try_checkpoint_download(
self,
latest_checkpoint_path: str,
save_latest_remote_file_name: str,
loggers: Sequence[Union[LoggerDestination, ObjectStore]],
load_progress_bar: bool,
) -> None:
"""Attempts to download the checkpoint from the logger destinations."""
... | Attempts to download the checkpoint from the logger destinations. | _try_checkpoint_download | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _get_autoresume_checkpoint(
self,
save_folder: str,
save_latest_filename: str,
save_latest_remote_file_name: str,
loggers: Sequence[LoggerDestination],
load_progress_bar: bool,
) -> Optional[str]:
"""Determines the load path when using autoresume.
... | Determines the load path when using autoresume.
First, check the ``save_folder`` for the latest checkpoint.
If no latest checkpoint is found locally, then check each logger for the latest checkpoint, and download
it to the ``save_folder``.
Returns:
Optional[str]: The path t... | _get_autoresume_checkpoint | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def fit(
self,
*,
# Train Dataloader
train_dataloader: Optional[Union[Iterable, DataSpec, dict[str, Any]]] = None,
train_dataloader_label: str = 'train',
train_subset_num_batches: Optional[int] = None,
spin_dataloaders: Optional[bool] = None,
# Timing
... | Train the model.
The Composer :class:`.Trainer` supports multiple calls to :meth:`.fit`. Any arguments specified during
the call to :meth:`.fit` will override the values specified when constructing the :class:`.Trainer`.
All arguments are optional, with the following exceptions:
* Th... | fit | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _compute_and_log_metrics(self, dataloader_label: str, metrics: dict[str, Metric]):
"""Computes metrics, logs the results, and updates the state with the metrics.
Args:
dataloader_label (str): The dataloader label.
metrics (dict[str, Metric]): The metrics to compute.
... | Computes metrics, logs the results, and updates the state with the metrics.
Args:
dataloader_label (str): The dataloader label.
metrics (dict[str, Metric]): The metrics to compute.
| _compute_and_log_metrics | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _spin_dataloaders_to_cur_epoch(self):
"""Spin the dataloaders to restore sampler state for current epoch.
Only one batch must be loaded to seed the sampler's generator. since only the first batch is being loaded, the
dataloader may not be completely iterated through.
"""
log... | Spin the dataloaders to restore sampler state for current epoch.
Only one batch must be loaded to seed the sampler's generator. since only the first batch is being loaded, the
dataloader may not be completely iterated through.
| _spin_dataloaders_to_cur_epoch | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _accumulate_time_across_ranks(
self,
num_samples: Union[int, float],
num_tokens: int,
batch_time: datetime.timedelta,
) -> tuple[int, int, datetime.timedelta]:
"""Accumulate the number of samples and tokens across ranks.
Returns a (num_samples, num_tokens, batch_... | Accumulate the number of samples and tokens across ranks.
Returns a (num_samples, num_tokens, batch_time) tuple.
| _accumulate_time_across_ranks | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _train_loop(self) -> None:
"""Run training for the specified number of epochs and log results."""
# Log training start
log.info('Using precision %s', self.state.precision)
self.logger.log_hyperparameters({
'enabled_algorithms/' + algo.__class__.__name__: True for algo in ... | Run training for the specified number of epochs and log results. | _train_loop | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _train_batch(self, use_grad_scaling: bool) -> dict[str, torch.Tensor]:
"""Compute loss by training on a full batch of data.
Adaptively change microbatch size if enabled to maximize GPU usage.
Args:
use_grad_scaling (bool): Enables gradient scaling.
Returns:
... | Compute loss by training on a full batch of data.
Adaptively change microbatch size if enabled to maximize GPU usage.
Args:
use_grad_scaling (bool): Enables gradient scaling.
Returns:
dict[str, torch.Tensor]: a dictionary containing the total loss and individual losses... | _train_batch | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _train_microbatches(
self,
microbatches: Sequence[Batch],
total_loss_dict: dict[str, torch.Tensor],
ddp_sync: bool = True,
) -> torch.Tensor:
"""Iterate over microbatches and compute the loss that will be used to step the optimizer.
Args:
microbatches... | Iterate over microbatches and compute the loss that will be used to step the optimizer.
Args:
microbatches (Sequence[Batch]): The microbatches which make up the batch.
total_loss_dict (dict[str, torch.tensor]): Dictionary containing individual losses
and their sum aggreg... | _train_microbatches | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _train_microbatch(
self,
use_grad_scaling: bool,
current_batch_size: Union[int, float],
is_final_microbatch: bool,
) -> dict[str, torch.Tensor]:
"""Train and compute the loss of ``state.batch``, which is assumed to be a single microbatch.
Args:
use_gr... | Train and compute the loss of ``state.batch``, which is assumed to be a single microbatch.
Args:
use_grad_scaling (bool): Whether to use gradient scaling.
current_batch_size (int, float): The current batch size.
minibatch_num_samples (int): Number of samples in the minibatch... | _train_microbatch | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def predict(
self,
dataloader: Union[DataLoader, DataSpec],
subset_num_batches: int = -1,
*,
return_outputs: bool = True,
):
"""Output model prediction on the provided data.
There are two ways to access the prediction outputs.
1. With ``return_outpu... | Output model prediction on the provided data.
There are two ways to access the prediction outputs.
1. With ``return_outputs`` set to True, the batch predictions will be collected into a list and returned.
2. Via a custom callback, which can be used with ``return_outputs`` set to False.
... | predict | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def eval(
self,
eval_dataloader: Optional[Union[Iterable, DataSpec, Evaluator, Sequence[Evaluator]]] = None,
subset_num_batches: int = -1,
):
"""Run evaluation loop.
Results are stored in ``trainer.state.eval_metrics``. The ``eval_dataloader`` can be provided to
eith... | Run evaluation loop.
Results are stored in ``trainer.state.eval_metrics``. The ``eval_dataloader`` can be provided to
either the eval() method or during training init().
Examples:
.. testcode::
trainer = Trainer(
model=model,
train_dataloade... | eval | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _eval_loop(
self,
evaluator: Evaluator,
metrics: dict[str, Metric],
subset_num_batches: Optional[int] = None,
):
"""Evaluate the model and log appropriate metrics.
Args:
evaluator (Evaluator): The evaluator to use for evaluation.
metrics (... | Evaluate the model and log appropriate metrics.
Args:
evaluator (Evaluator): The evaluator to use for evaluation.
metrics (dict[str, Metric]): Dictionary mapping metric names to metrics to evaluate against.
subset_num_batches (int, optional): If specified, evaluate on this m... | _eval_loop | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _use_grad_scaling(self, precision: Union[str, Precision], scaler: Optional[GradScaler]) -> bool:
"""Determines based on precision when to use grad scaling.
By default, the pytorch GradScaler is a no-op if running on
unsupported hardware. Here we raise a RuntimeError instead.
Args:
... | Determines based on precision when to use grad scaling.
By default, the pytorch GradScaler is a no-op if running on
unsupported hardware. Here we raise a RuntimeError instead.
Args:
precision (Precision): Numerical precision, based on the Precision Enum.
scaler (GradSca... | _use_grad_scaling | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _iter_dataloader(self, trainer_mode: TrainerMode):
"""Helper method to iterate over the dataloader.
This method yields up to :attr:`.State.dataloader_len`` batches from the dataloader. In addition, if the
profiler is enabled, the dataloader latency recorded via the :class:`.Marker` API.
... | Helper method to iterate over the dataloader.
This method yields up to :attr:`.State.dataloader_len`` batches from the dataloader. In addition, if the
profiler is enabled, the dataloader latency recorded via the :class:`.Marker` API.
Args:
trainer_mode (TrainerMode): Specifies whic... | _iter_dataloader | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _use_closures(self) -> bool:
"""Determines based on precision and optimizers whether to use closures.
We default to using closures unless AMP is enabled, in which case we only allow closures when using optimizers
with the _step_supports_amp_closure flag.
"""
if self.state.de... | Determines based on precision and optimizers whether to use closures.
We default to using closures unless AMP is enabled, in which case we only allow closures when using optimizers
with the _step_supports_amp_closure flag.
| _use_closures | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def save_checkpoint(
self,
name: str = 'ep{epoch}-ba{batch}-rank{rank}',
*,
weights_only: bool = False,
):
"""Checkpoint the training :class:`~.State`.
Args:
name (str, optional): See :func:`.save_checkpoint`.
weights_only (bool, optional): Se... | Checkpoint the training :class:`~.State`.
Args:
name (str, optional): See :func:`.save_checkpoint`.
weights_only (bool, optional): See :func:`.save_checkpoint`.
Returns:
str or None: See :func:`.save_checkpoint`.
| save_checkpoint | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def save_checkpoint_to_save_folder(self):
"""Checkpoints the training :class:`~.State` using a CheckpointSaver if it exists.
Raises:
ValueError: If ``_checkpoint_saver`` does not exist.
Returns:
None
"""
if self._checkpoint_saver is None:
rai... | Checkpoints the training :class:`~.State` using a CheckpointSaver if it exists.
Raises:
ValueError: If ``_checkpoint_saver`` does not exist.
Returns:
None
| save_checkpoint_to_save_folder | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def export_for_inference(
self,
save_format: Union[str, ExportFormat],
save_path: str,
save_object_store: Optional[ObjectStore] = None,
sample_input: Optional[Any] = None,
transforms: Optional[Sequence[Transform]] = None,
input_names: Optional[Sequence[str]] = Non... | Export a model for inference.
Args:
save_format (Union[str, ExportFormat]): Format to export to. Either ``"torchscript"`` or ``"onnx"``.
save_path: (str): The path for storing the exported model. It can be a path to a file on the local disk,
a URL, or if ``save_object_store... | export_for_inference | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def _parse_parallelism_config(
self,
parallelism_config: Optional[dict[str, Any] | ParallelismConfig],
) -> Optional[ParallelismConfig]:
"""Parse parallelism configuration into a ParallelismConfig object.
Args:
parallelism_config: Configuration for parallelism options (F... | Parse parallelism configuration into a ParallelismConfig object.
Args:
parallelism_config: Configuration for parallelism options (FSDP, tensor parallelism)
Returns:
ParallelismConfig: A properly formatted parallelism configuration, or None
| _parse_parallelism_config | python | mosaicml/composer | composer/trainer/trainer.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/trainer.py | Apache-2.0 |
def patch_unshard_for_automicrobatching(auto_microbatch_size_found=False):
"""Monkey patches sync hook into unshard when searching during automicrobatching."""
from torch.distributed.fsdp._flat_param import FlatParamHandle
if auto_microbatch_size_found:
global original_unshard
FlatParamHandl... | Monkey patches sync hook into unshard when searching during automicrobatching. | patch_unshard_for_automicrobatching | python | mosaicml/composer | composer/trainer/_patch_pytorch.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/_patch_pytorch.py | Apache-2.0 |
def patch_pytorch():
"""Monkey patches pytorch functions based on pytorch version."""
if version.parse(torch.__version__) < version.parse('2.7.1'):
# Monkey patch for torch < 2.7.1 ie torch == 2.7.0
# No monkeypatches besides unshard (below)!
pass | Monkey patches pytorch functions based on pytorch version. | patch_pytorch | python | mosaicml/composer | composer/trainer/_patch_pytorch.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/_patch_pytorch.py | Apache-2.0 |
def unshard_with_sync(self):
"""Run the unshard logic, but with a sync after a :meth:`_alloc_padded_unsharded_flat_param`.
This prevents deadlocks when some ranks OOM after the alloc call and others do not.
This is a patched method from pytorch, meant to be called when automicrobatching
... | Run the unshard logic, but with a sync after a :meth:`_alloc_padded_unsharded_flat_param`.
This prevents deadlocks when some ranks OOM after the alloc call and others do not.
This is a patched method from pytorch, meant to be called when automicrobatching
turns on hooks in its search process fo... | unshard_with_sync | python | mosaicml/composer | composer/trainer/_patch_pytorch.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/_patch_pytorch.py | Apache-2.0 |
def step(self, optimizer: Optimizer, *args, **kwargs):
"""Step the optimizer with amp.
Always called before the optimizer step. Checks if the optimizer can handle AMP closures (currently only
Composer's SAM optimizer) If so, it passes an AMP-modified closure to the optimizer.
"""
... | Step the optimizer with amp.
Always called before the optimizer step. Checks if the optimizer can handle AMP closures (currently only
Composer's SAM optimizer) If so, it passes an AMP-modified closure to the optimizer.
| step | python | mosaicml/composer | composer/trainer/_scaler.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/_scaler.py | Apache-2.0 |
def update(self, new_scale: Optional[Union[float, torch.FloatTensor]] = None):
"""Updates the scale factor.
If any optimizer steps were skipped, the scale is multiplied by ``backoff_factor``
to reduce it. If ``growth_interval`` non-skipped iterations occurred consecutively,
the scale is... | Updates the scale factor.
If any optimizer steps were skipped, the scale is multiplied by ``backoff_factor``
to reduce it. If ``growth_interval`` non-skipped iterations occurred consecutively,
the scale is multiplied by ``growth_factor`` to increase it.
Passing ``new_scale`` sets the n... | update | python | mosaicml/composer | composer/trainer/_scaler.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/_scaler.py | Apache-2.0 |
def scale_pytorch_scheduler(scheduler: LRScheduler, ssr: float):
"""Makes a learning rate schedule take a different number of epochs.
Training for less time is a strong baseline approach to speeding up
training, provided that the training still gets through the entire
learning rate schedule. E.g., trai... | Makes a learning rate schedule take a different number of epochs.
Training for less time is a strong baseline approach to speeding up
training, provided that the training still gets through the entire
learning rate schedule. E.g., training for half as long often yields
little accuracy degredation, prov... | scale_pytorch_scheduler | python | mosaicml/composer | composer/trainer/_scale_schedule.py | https://github.com/mosaicml/composer/blob/master/composer/trainer/_scale_schedule.py | Apache-2.0 |
def extract_hparams(locals_dict: dict[str, Any]) -> dict[str, Any]:
"""Takes in local symbol table and recursively grabs any hyperparameter.
Args:
locals_dict (dict[str, Any]): The local symbol table returned when calling locals(),
which maps any free local variables' names to their values.... | Takes in local symbol table and recursively grabs any hyperparameter.
Args:
locals_dict (dict[str, Any]): The local symbol table returned when calling locals(),
which maps any free local variables' names to their values.
Returns:
dict[str, Any]: A nested dictionary with every eleme... | extract_hparams | python | mosaicml/composer | composer/utils/auto_log_hparams.py | https://github.com/mosaicml/composer/blob/master/composer/utils/auto_log_hparams.py | Apache-2.0 |
def _grab_hparams(obj) -> Any:
"""Helper function parses objects for their hyperparameters going only one level deep."""
# If the object has already grabbed its hyperparameters (it calls extract_hparams inside __init__)
# then parse hparams attribute (which is a dict) and name those sub-hyperparameters
... | Helper function parses objects for their hyperparameters going only one level deep. | _grab_hparams | python | mosaicml/composer | composer/utils/auto_log_hparams.py | https://github.com/mosaicml/composer/blob/master/composer/utils/auto_log_hparams.py | Apache-2.0 |
def _get_obj_repr(obj: Any):
"""Returns best representation of object.
Args:
obj (Any): the object.
Returns:
obj if obj is None or it is a int, float, str, bool type.
obj.value if obj is an Enum. Otherwise returns obj.__class__.__name__.
"""
if any(isinstance(obj, type_) fo... | Returns best representation of object.
Args:
obj (Any): the object.
Returns:
obj if obj is None or it is a int, float, str, bool type.
obj.value if obj is an Enum. Otherwise returns obj.__class__.__name__.
| _get_obj_repr | python | mosaicml/composer | composer/utils/auto_log_hparams.py | https://github.com/mosaicml/composer/blob/master/composer/utils/auto_log_hparams.py | Apache-2.0 |
def convert_nested_dict_to_flat_dict(nested_dict: dict, prefix='') -> dict:
"""Takes in a nested dict converts it to a flat dict with keys separated by slashes.
Args:
nested_dict (dict): A dictionary containing at least one other dictionary.
prefix (str, optional): A prefix to left append to th... | Takes in a nested dict converts it to a flat dict with keys separated by slashes.
Args:
nested_dict (dict): A dictionary containing at least one other dictionary.
prefix (str, optional): A prefix to left append to the keys in the dictionary.
'Defaults to ''.
Returns:
dict: ... | convert_nested_dict_to_flat_dict | python | mosaicml/composer | composer/utils/auto_log_hparams.py | https://github.com/mosaicml/composer/blob/master/composer/utils/auto_log_hparams.py | Apache-2.0 |
def convert_flat_dict_to_nested_dict(flat_dict: dict) -> dict:
"""Converts flat dictionary separated by slashes to nested dictionary.
Args:
flat_dict (dict): flat dictionary containing no sub-dictionary with keys
separated by slashes. e.g. {'a':1, 'b/c':2}
Returns:
dict: a nest... | Converts flat dictionary separated by slashes to nested dictionary.
Args:
flat_dict (dict): flat dictionary containing no sub-dictionary with keys
separated by slashes. e.g. {'a':1, 'b/c':2}
Returns:
dict: a nested dict.
| convert_flat_dict_to_nested_dict | python | mosaicml/composer | composer/utils/auto_log_hparams.py | https://github.com/mosaicml/composer/blob/master/composer/utils/auto_log_hparams.py | Apache-2.0 |
def batch_get(batch: Any, key: Union[str, int, tuple[Callable, Callable], Callable, Any]):
"""Indexes into the batch given the key.
>>> from composer.utils.batch_helpers import batch_get
>>> batch_get([1,2,3], 1)
2
>>> batch_get({'a':1, 'b':7}, 'b')
7
>>> batch_get([{'a':1, 'b':7},{'c':5}],... | Indexes into the batch given the key.
>>> from composer.utils.batch_helpers import batch_get
>>> batch_get([1,2,3], 1)
2
>>> batch_get({'a':1, 'b':7}, 'b')
7
>>> batch_get([{'a':1, 'b':7},{'c':5}], lambda x: x[1]['c'])
5
>>> batch_get([{'a':1, 'b':7},{'c':5}], (lambda x: x[1]['c'], lamb... | batch_get | python | mosaicml/composer | composer/utils/batch_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/batch_helpers.py | Apache-2.0 |
def batch_set(batch: Any, key: Union[str, int, tuple[Callable, Callable], Callable, Any], value: Any) -> Any:
"""Indexes into the batch given the key and sets the element at that index to value.
This is not an in-place operation for batches of type tuple as tuples are not mutable.
>>> from composer.utils.... | Indexes into the batch given the key and sets the element at that index to value.
This is not an in-place operation for batches of type tuple as tuples are not mutable.
>>> from composer.utils.batch_helpers import batch_set
>>> batch_set([1,2,3], key=1, value=8)
[1, 8, 3]
>>> batch_set({'a':1, 'b'... | batch_set | python | mosaicml/composer | composer/utils/batch_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/batch_helpers.py | Apache-2.0 |
def _batch_set(batch: Any, key: Any, value: Any) -> Any:
"""Sets a key value pair in a non-tuple batch."""
if isinstance(batch, tuple):
return _batch_set_tuple(batch, key, value)
try:
# Check if one can do a __getitem__ before doing a __setitem__ because dicts can
# do __setitem__ f... | Sets a key value pair in a non-tuple batch. | _batch_set | python | mosaicml/composer | composer/utils/batch_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/batch_helpers.py | Apache-2.0 |
def _batch_set_multiple(batch: Any, key: Any, value: Any) -> Any:
"""Sets multiple key value pairs in a non-tuple batch."""
# Numpy arrays and Torch tensors can take tuples and lists as keys, so try to do a normal
# __getitem__ call before resulting to list comprehension.
try:
# Check if one can... | Sets multiple key value pairs in a non-tuple batch. | _batch_set_multiple | python | mosaicml/composer | composer/utils/batch_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/batch_helpers.py | Apache-2.0 |
def _batch_set_tuple(batch: Any, key: Union[int, str], value: Any) -> Any:
"""Sets key value pairs in tuples and NamedTuples."""
if hasattr(batch, '_fields'): # Namedtuple
if isinstance(key, str):
batch = batch._replace(**{key: value})
else:
batch_list = list(batch)
... | Sets key value pairs in tuples and NamedTuples. | _batch_set_tuple | python | mosaicml/composer | composer/utils/batch_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/batch_helpers.py | Apache-2.0 |
def _get_checkpoint_validation_function(
) -> Optional[Callable[[Union[Path, str], Optional[list[tuple[int, int]]]], bool]]:
"""Get the validation function specified by the environment variable `CHECKPOINT_VALIDATION_FUNCTION`.
Returns:
Callable[[Union[Path, str], Optional[int], Optional[int]], bool] T... | Get the validation function specified by the environment variable `CHECKPOINT_VALIDATION_FUNCTION`.
Returns:
Callable[[Union[Path, str], Optional[int], Optional[int]], bool] The checkpoint validation function that returns
True given a valid checkpoint and optionally a list of offsets and length... | _get_checkpoint_validation_function | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _ensure_valid_checkpoint(checkpoint_filepath: Union[Path, str],
specs: Optional[list[tuple[int, int]]] = None) -> Union[Path, str]:
"""Ensures that the checkpoint at checkpoint_filepath is valid.
using the function specified by the CHECKPOINT_VALIDATION_FUNCTION environment var... | Ensures that the checkpoint at checkpoint_filepath is valid.
using the function specified by the CHECKPOINT_VALIDATION_FUNCTION environment variable.
If CHECKPOINT_VALIDATION_FUNCTION is not set, we skip validation.
Args:
checkpoint_filepath (Union[Path,str]): The path to the checkpoint file.
... | _ensure_valid_checkpoint | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _format_path_with_rank_zero(path: str) -> str:
"""Formats ``path`` with the rank zero values."""
return path.format(
rank=0,
local_rank=0,
node_rank=0,
) | Formats ``path`` with the rank zero values. | _format_path_with_rank_zero | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _get_write_mode(name: str) -> str:
"""Get the write mode to use with :func:`tarfile.open`."""
if name.endswith('.tar'):
return 'w'
if name.endswith('.tar.gz') or name.endswith('.tgz'):
return 'w:gz'
if name.endswith('.tar.bz2'):
return 'w:bz2'
if name.endswith('.tar.lzma'... | Get the write mode to use with :func:`tarfile.open`. | _get_write_mode | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _is_rng_key(key: str, value: tuple) -> bool:
"""Check if the key is an RNG key.
We expect the RNG key to be of the form 'rng.{rank}.cuda|torch|python|numpy'.
This function ensures that we don't accidentally pick up other keys.
"""
starts_with_rng = key.startswith('rng')
ends_with_expected =... | Check if the key is an RNG key.
We expect the RNG key to be of the form 'rng.{rank}.cuda|torch|python|numpy'.
This function ensures that we don't accidentally pick up other keys.
| _is_rng_key | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def read_data(self, plan: LoadPlan, planner: LoadPlanner):
"""Reads data file.
Raises:
ValueError if the data file is invalid.
"""
path_to_specs: dict[str, list[tuple[int, int]]] = {}
for read_item in plan.items:
item_md = self.storage_data[read_item.stor... | Reads data file.
Raises:
ValueError if the data file is invalid.
| read_data | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def read_metadata(self) -> Metadata:
"""Reads metadata file.
Raises:
ValueError if the metadata file is invalid.
"""
metadata_file_path = os.path.join(self.path, '.metadata')
_ensure_valid_checkpoint(metadata_file_path)
return super().read_metadata() | Reads metadata file.
Raises:
ValueError if the metadata file is invalid.
| read_metadata | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def load_checkpoint(
path: str,
state: State,
logger: Logger,
object_store: Optional[Union[ObjectStore, LoggerDestination]] = None,
load_weights_only: bool = False,
strict_model_weights: bool = True,
progress_bar: bool = True,
ignore_keys: Optional[Union[list[str], Callable[[dict], None]... | Load a checkpoint from a local file, URI, or cloud object store into ``state``.
Args:
path (str): The path format string to an existing checkpoint file.
It can be a path to a file on the local disk, a URL, or if ``object_store`` is set, the object name
for a checkpoint in a cloud b... | load_checkpoint | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _get_local_rank_zero_path(path: Optional[str]) -> str:
"""Broadcasts the ``path`` from the LOCAL rank zero to all LOCAL ranks."""
local_rank_zero = dist.get_global_rank() - dist.get_local_rank()
paths = dist.all_gather_object(path)
local_rank_zero_path = paths[local_rank_zero]
assert local_rank_... | Broadcasts the ``path`` from the LOCAL rank zero to all LOCAL ranks. | _get_local_rank_zero_path | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def download_checkpoint(
path: str,
node_checkpoint_folder: str,
object_store: Optional[Union[ObjectStore, LoggerDestination]],
progress_bar: bool,
) -> tuple[str, Optional[str], bool]:
"""Download the checkpoint stored at ``path``, potentially in ``object_store``, to ``node_checkpoint_folder``.
... | Download the checkpoint stored at ``path``, potentially in ``object_store``, to ``node_checkpoint_folder``.
Returns a tuple of (``composer_states_filepath``, ``extracted_checkpoint_folder``, ``extracted_rank_n``).
* The ``composer_states_filepath``, is the path to the composer states, which can be passed i... | download_checkpoint | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _flatten_keys(obj: Any, paths: list[str], existing_path: str):
"""Recursively flatten the keys of a dictionary or list into a set of paths."""
# Store path when we reach end, which is either non-dict or empty dict
if isinstance(obj, list) and len(obj) > 0:
for i, elm in enumerate(obj):
... | Recursively flatten the keys of a dictionary or list into a set of paths. | _flatten_keys | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def glob_filter(exclude_globs: list[str]) -> Callable[[dict], None]:
"""Provides a function which deletes all subparts of a dictionary based on a list of paths."""
def filter_func(state_dict: dict) -> None:
# Flatten dictionary into paths
paths = []
_flatten_keys(state_dict, paths, '/')... | Provides a function which deletes all subparts of a dictionary based on a list of paths. | glob_filter | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def safe_torch_load(
composer_states_filepath: Union[Path, str],
map_location: str = 'cpu',
load_monolith_rank0_only: bool = False,
) -> dict[str, Any]:
"""Load a torch checkpoint, catching errors due to backwards compatibility issues.
Args:
composer_states_filepath: The path to the checkpo... | Load a torch checkpoint, catching errors due to backwards compatibility issues.
Args:
composer_states_filepath: The path to the checkpoint file.
map_location: The location to load the checkpoint to.
load_monolith_rank0_only: Whether the checkpoint is a monolith FSDP checkpoint.
| safe_torch_load | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _restore_checkpoint(
state: State,
logger: Logger,
composer_states_filepath: str,
extracted_rank_n: bool,
extracted_checkpoint_folder: Optional[str],
load_weights_only: bool,
strict_model_weights: bool,
ignore_keys: Optional[Union[list[str], Callable[[dict], None]]],
exclude_algo... | Restore a checkpoint into ``state`` and returns the rng state dicts (if ``load_weights_only`` is False). | _restore_checkpoint | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def get_save_filename(
state: State,
filename: str = 'ep{epoch}-ba{batch}-rank{rank}',
) -> str:
"""Gets full filename of save filename.
Args:
state (State): The :class:`~composer.core.State` to load the checkpoint into.
filename (filename): The name of the save file.
Returns:
... | Gets full filename of save filename.
Args:
state (State): The :class:`~composer.core.State` to load the checkpoint into.
filename (filename): The name of the save file.
Returns:
Full filename of save file.
| get_save_filename | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _write_checkpoint_file(state_dict: dict[str, Any], filename: str) -> None:
"""Write the given checkpoint state to the given path. Compressing if indicated to do so by the file extension."""
if is_tar(filename):
log.debug('Writing checkpoint tar file %s', filename)
write_mode = _get_write_mod... | Write the given checkpoint state to the given path. Compressing if indicated to do so by the file extension. | _write_checkpoint_file | python | mosaicml/composer | composer/utils/checkpoint.py | https://github.com/mosaicml/composer/blob/master/composer/utils/checkpoint.py | Apache-2.0 |
def _exc_report(exc_type) -> None:
"""Produces exception report (exception message + environment report).
Args:
exc_type (Exception): Type of exception.
"""
EXCEPTION_MSG = f'Bugs can be reported at: {COMPOSER_OPEN_ISSUE_URL}\n'
# Don't print exception report for KeyboardInterrupt
if n... | Produces exception report (exception message + environment report).
Args:
exc_type (Exception): Type of exception.
| _exc_report | python | mosaicml/composer | composer/utils/collect_env.py | https://github.com/mosaicml/composer/blob/master/composer/utils/collect_env.py | Apache-2.0 |
def enable_env_report() -> None:
"""Enable environment report generation on exception."""
global _ENV_EXCEPTION_REPORT
_ENV_EXCEPTION_REPORT = True | Enable environment report generation on exception. | enable_env_report | python | mosaicml/composer | composer/utils/collect_env.py | https://github.com/mosaicml/composer/blob/master/composer/utils/collect_env.py | Apache-2.0 |
def disable_env_report() -> None:
"""Disable environment report generation on exception."""
global _ENV_EXCEPTION_REPORT
_ENV_EXCEPTION_REPORT = False | Disable environment report generation on exception. | disable_env_report | python | mosaicml/composer | composer/utils/collect_env.py | https://github.com/mosaicml/composer/blob/master/composer/utils/collect_env.py | Apache-2.0 |
def _custom_exception_handler(type, value, tb) -> None:
"""Custom exception wrapper for sys.excepthook."""
_exc_report(exc_type=type)
assert _orig_excepthook
_orig_excepthook(type, value, tb) | Custom exception wrapper for sys.excepthook. | _custom_exception_handler | python | mosaicml/composer | composer/utils/collect_env.py | https://github.com/mosaicml/composer/blob/master/composer/utils/collect_env.py | Apache-2.0 |
def configure_excepthook() -> None:
"""Collect and print system information when :func:`sys.excepthook` is called.
The custom exception handler causes an exception message to be printed when :func:`sys.excepthook`
is called. The exception message provides the user with information on the nature of the exc... | Collect and print system information when :func:`sys.excepthook` is called.
The custom exception handler causes an exception message to be printed when :func:`sys.excepthook`
is called. The exception message provides the user with information on the nature of the exception
and directs the user to file Git... | configure_excepthook | python | mosaicml/composer | composer/utils/collect_env.py | https://github.com/mosaicml/composer/blob/master/composer/utils/collect_env.py | Apache-2.0 |
def get_composer_env_dict() -> dict:
"""Query Composer pertinent system information as a dict."""
return {
'composer_version': get_composer_version(),
'composer_commit_hash': get_composer_commit_hash(),
'cpu_model': get_cpu_model(),
'cpu_count': get_cpu_count(),
'num_node... | Query Composer pertinent system information as a dict. | get_composer_env_dict | python | mosaicml/composer | composer/utils/collect_env.py | https://github.com/mosaicml/composer/blob/master/composer/utils/collect_env.py | Apache-2.0 |
def is_compressed_pt(filename: str) -> bool:
"""Whether the filename is for a directly compressed pt file.
Whether the extension of the given filename indicates that the file contains a raw compressed stream
of a single pt file without a container (like tar).
"""
parts = filename.split('.')
ret... | Whether the filename is for a directly compressed pt file.
Whether the extension of the given filename indicates that the file contains a raw compressed stream
of a single pt file without a container (like tar).
| is_compressed_pt | python | mosaicml/composer | composer/utils/compression.py | https://github.com/mosaicml/composer/blob/master/composer/utils/compression.py | Apache-2.0 |
def compress(self, out_filename: str) -> Iterator[IO[bytes]]:
"""Compress some data, saving to the given file."""
self.check_exists()
with open(out_filename, 'wb') as f:
proc = subprocess.Popen(
self._compress_cmd(),
stdin=subprocess.PIPE,
... | Compress some data, saving to the given file. | compress | python | mosaicml/composer | composer/utils/compression.py | https://github.com/mosaicml/composer/blob/master/composer/utils/compression.py | Apache-2.0 |
def decompress(self, in_filename: str) -> Iterator[IO[bytes]]:
"""Decompress the content of the given file, providing the output as a file-like object."""
self.check_exists()
proc = subprocess.Popen(
self._decompress_cmd(in_filename),
stdout=subprocess.PIPE,
)
... | Decompress the content of the given file, providing the output as a file-like object. | decompress | python | mosaicml/composer | composer/utils/compression.py | https://github.com/mosaicml/composer/blob/master/composer/utils/compression.py | Apache-2.0 |
def get_compressor(filename: str) -> CliCompressor:
"""Obtain the compressor that supports the format of the given file."""
if not is_compressed_pt(filename):
raise ValueError(f'The given filename does not correspond to a compressed file: "{filename}".')
extension = filename.split('.')[-1]
for c... | Obtain the compressor that supports the format of the given file. | get_compressor | python | mosaicml/composer | composer/utils/compression.py | https://github.com/mosaicml/composer/blob/master/composer/utils/compression.py | Apache-2.0 |
def get_device(device: Optional[Union[str, 'Device']] = None) -> 'Device':
"""Takes string or Device and returns the corresponding :class:`~composer.devices.Device`.
Args:
device (str | Device, optional): A string corresponding to a device (one of
``'cpu'``, ``'gpu'``, ``'mps'``, or ``'tpu'... | Takes string or Device and returns the corresponding :class:`~composer.devices.Device`.
Args:
device (str | Device, optional): A string corresponding to a device (one of
``'cpu'``, ``'gpu'``, ``'mps'``, or ``'tpu'``) or a :class:`.Device`.
(default: ``None``)
Returns:
D... | get_device | python | mosaicml/composer | composer/utils/device.py | https://github.com/mosaicml/composer/blob/master/composer/utils/device.py | Apache-2.0 |
def is_hpu_installed() -> bool:
"""Determines whether the module needed for training on HPUs (Gaudi, Gaudi2) is installed.
Returns:
bool: Whether habana-torch-plugin is installed.
"""
try:
import habana_frameworks
del habana_frameworks
return True
except ModuleNotFou... | Determines whether the module needed for training on HPUs (Gaudi, Gaudi2) is installed.
Returns:
bool: Whether habana-torch-plugin is installed.
| is_hpu_installed | python | mosaicml/composer | composer/utils/device.py | https://github.com/mosaicml/composer/blob/master/composer/utils/device.py | Apache-2.0 |
def get_world_size() -> int:
"""Returns the world size, which is the number of processes participating in this training run.
Returns:
int: The world size.
"""
return _get_distributed_config_var(
env_var='WORLD_SIZE',
human_name='world size',
default=1,
fetch_fn_n... | Returns the world size, which is the number of processes participating in this training run.
Returns:
int: The world size.
| get_world_size | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def get_global_rank(group: Optional[dist.ProcessGroup] = None) -> int:
"""Returns the global rank of the current process in the input PG, which is on ``[0; group.WORLD_SIZE - 1]``.
Args:
group (ProcessGroup, optional): The process group. If ``None``, it will return env_var ``RANK``
Returns:
... | Returns the global rank of the current process in the input PG, which is on ``[0; group.WORLD_SIZE - 1]``.
Args:
group (ProcessGroup, optional): The process group. If ``None``, it will return env_var ``RANK``
Returns:
int: The global rank in input process group.
| get_global_rank | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def barrier(group=None) -> None:
"""Synchronizes all processes.
This function blocks until all processes reach this function.
.. seealso:: :func:`torch.distributed.barrier`
Args:
group (ProcessGroup, optional): The process group to work on. If ``None``,
the default process group w... | Synchronizes all processes.
This function blocks until all processes reach this function.
.. seealso:: :func:`torch.distributed.barrier`
Args:
group (ProcessGroup, optional): The process group to work on. If ``None``,
the default process group will be used. Default is ``None``.
| barrier | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def all_reduce(
tensor: torch.Tensor,
reduce_operation: str = 'SUM',
group=None,
) -> None:
"""Reduce a ``tensor`` by applying the ``reduce_operation``.
All ranks get the same, bitwise-identical result.
.. seealso:: :func:`torch.distributed.all_reduce`
Args:
tensor (torch.Tensor):... | Reduce a ``tensor`` by applying the ``reduce_operation``.
All ranks get the same, bitwise-identical result.
.. seealso:: :func:`torch.distributed.all_reduce`
Args:
tensor (torch.Tensor): Input and output of the collective. The function
operates in-place.
op (optional): One of ... | all_reduce | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def broadcast(tensor: torch.Tensor, src: int, group=None) -> None:
"""Broadcasts the tensor to the whole group.
``tensor`` must have the same number of elements in all processes participating in the collective.
See :func:`torch.distributed.broadcast`.
Args:
tensor (torch.Tensor): Data to be se... | Broadcasts the tensor to the whole group.
``tensor`` must have the same number of elements in all processes participating in the collective.
See :func:`torch.distributed.broadcast`.
Args:
tensor (torch.Tensor): Data to be sent if ``src`` is the rank of current process,
and tensor to be... | broadcast | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def broadcast_object_list(object_list: list[Any], src: int = 0, group=None) -> None:
"""Broadcasts picklable objects in ``object_list`` to the whole group.
Similar to :func:`broadcast`, but Python objects can be passed in.
Note that all objects in ``object_list`` must be picklable in order to be broadcaste... | Broadcasts picklable objects in ``object_list`` to the whole group.
Similar to :func:`broadcast`, but Python objects can be passed in.
Note that all objects in ``object_list`` must be picklable in order to be broadcasted.
.. seealso:: :func:`torch.distributed.broadcast`.
Args:
object_list (to... | broadcast_object_list | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def all_gather(tensor: torch.Tensor, group=None) -> Sequence[torch.Tensor]:
"""Collects a :class:`~torch.Tensor` from each rank.
.. seealso:: :func:`torch.distributed.all_gather`
Args:
tensor (torch.Tensor): Tensor from each rank to be gathered.
group (ProcessGroup, optional): The process ... | Collects a :class:`~torch.Tensor` from each rank.
.. seealso:: :func:`torch.distributed.all_gather`
Args:
tensor (torch.Tensor): Tensor from each rank to be gathered.
group (ProcessGroup, optional): The process group to work on. If ``None``,
the default process group will be used. ... | all_gather | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def all_gather_object(obj: TObj, group=None) -> list[TObj]:
"""Collect a pickleable object from each rank and return a list of these objects indexed by rank.
.. seealso:: :func:`torch.distributed.all_gather_object`
Args:
obj (TObj): Object to be gathered.
group (ProcessGroup, optional): Th... | Collect a pickleable object from each rank and return a list of these objects indexed by rank.
.. seealso:: :func:`torch.distributed.all_gather_object`
Args:
obj (TObj): Object to be gathered.
group (ProcessGroup, optional): The process group to work on. If ``None``,
the default pr... | all_gather_object | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def initialize_dist(device: Optional[Union[str, Device]] = None, timeout: float = 300.0) -> None:
"""Initialize the default PyTorch distributed process group.
This function assumes that the following environment variables are set:
* ``RANK``: The global rank of the process, which should be on ``[0; WORLD_... | Initialize the default PyTorch distributed process group.
This function assumes that the following environment variables are set:
* ``RANK``: The global rank of the process, which should be on ``[0; WORLD_SIZE - 1]``.
* ``LOCAL_RANK``: The local rank for the process, which should be on ``[0; LOCAL_WORLD_S... | initialize_dist | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def get_sampler(
dataset: torch.utils.data.Dataset,
*,
drop_last: bool = False,
shuffle: bool = False,
num_replicas: Optional[int] = None,
rank: Optional[int] = None,
seed: int = 0,
):
"""Constructs a :class:`~torch.utils.data.distributed.DistributedSampler` for a dataset.
The :clas... | Constructs a :class:`~torch.utils.data.distributed.DistributedSampler` for a dataset.
The :class:`~torch.utils.data.distributed.DistributedSampler` assumes that each rank has a complete copy of the
dataset. It ensures that each rank sees a unique shard for each epoch containing
``len(dataset) / get_world_s... | get_sampler | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def get_node_signal_file_name(rng: Optional[random.Random] = None) -> str:
"""Returns a file name to use for a file based wait within a node.
The file name will contain a randomly generated string to avoid conflicts.
Note: This file name will be the same on each node, so that it can be used for a file base... | Returns a file name to use for a file based wait within a node.
The file name will contain a randomly generated string to avoid conflicts.
Note: This file name will be the same on each node, so that it can be used for a file based wait.
Returns:
str: The name of the file that will be created to si... | get_node_signal_file_name | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def write_signal_file(signal_file_name: str, dir_path: Optional[str] = None) -> str:
"""Writes a signal file to the specified directory.
This function creates a signal file in the specified directory. If the directory does
Note: Only local rank zero writes the signal file. All other ranks are expected to w... | Writes a signal file to the specified directory.
This function creates a signal file in the specified directory. If the directory does
Note: Only local rank zero writes the signal file. All other ranks are expected to wait for the signal file.
Args:
signal_file_name (str): The name of the signal f... | write_signal_file | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def busy_wait_for_local_rank_zero(dir_path: Optional[str] = None):
"""Busy waits for the signal file to be created by local rank zero.
This function will wait for the signal file to be created by local rank zero. It will
check every 0.1 seconds for the existence of the file.
Args:
dir_path (st... | Busy waits for the signal file to be created by local rank zero.
This function will wait for the signal file to be created by local rank zero. It will
check every 0.1 seconds for the existence of the file.
Args:
dir_path (str, optional): The directory in which to look for the signal file. If ``Non... | busy_wait_for_local_rank_zero | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def local_rank_zero_download_and_wait(expected_file_path: str):
"""Context manager to wait for a file to exist on all ranks except local rank zero.
It is expected that the file will be created by local rank zero. This function is useful
as an alternative to ``run_local_rank_zero_first`` when downloading a ... | Context manager to wait for a file to exist on all ranks except local rank zero.
It is expected that the file will be created by local rank zero. This function is useful
as an alternative to ``run_local_rank_zero_first`` when downloading a file, because it does
not require dist to be initialized. It only r... | local_rank_zero_download_and_wait | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def run_local_rank_zero_first():
"""Context manager to hold all non-zero ranks until rank zero completes.
The below example will let the local rank zero download
the dataset, and hold all non-rank zeros until the
download is complete.
.. code-block: python
with run_local_rank_zero_first()... | Context manager to hold all non-zero ranks until rank zero completes.
The below example will let the local rank zero download
the dataset, and hold all non-rank zeros until the
download is complete.
.. code-block: python
with run_local_rank_zero_first():
dataset = CIFAR10(
... | run_local_rank_zero_first | python | mosaicml/composer | composer/utils/dist.py | https://github.com/mosaicml/composer/blob/master/composer/utils/dist.py | Apache-2.0 |
def extract_path_from_symlink(
source_path: str,
object_store: Optional[Union[LoggerDestination, ObjectStore]] = None,
) -> str:
"""Returns the checkpont path from symlink file.
Args:
source_path(str): The remote symlink path.
object_store(LoggerDestination | ObjectStore, optional): The... | Returns the checkpont path from symlink file.
Args:
source_path(str): The remote symlink path.
object_store(LoggerDestination | ObjectStore, optional): The object store
used to download the remote symlink file
Returns:
str: The content of the remote symlink file.
| extract_path_from_symlink | 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_dist_config(strict: bool = True) -> dict[str, Any]:
"""Returns a dict of distributed settings (rank, world_size, etc.).
If ``strict=True``, will error if a setting is not available (e.g. the
environment variable is not set). Otherwise, will only return settings
that are available.
"""
... | Returns a dict of distributed settings (rank, world_size, etc.).
If ``strict=True``, will error if a setting is not available (e.g. the
environment variable is not set). Otherwise, will only return settings
that are available.
| _get_dist_config | python | mosaicml/composer | composer/utils/file_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py | Apache-2.0 |
def is_tar(name: Union[str, pathlib.Path]) -> bool:
"""Returns whether ``name`` has a tar-like extension.
Args:
name (str | pathlib.Path): The name to check.
Returns:
bool: Whether ``name`` is a tarball.
"""
parts = str(name).split('.')
return len(parts) > 1 and ('tar' in parts... | Returns whether ``name`` has a tar-like extension.
Args:
name (str | pathlib.Path): The name to check.
Returns:
bool: Whether ``name`` is a tarball.
| is_tar | python | mosaicml/composer | composer/utils/file_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py | Apache-2.0 |
def ensure_folder_is_empty(folder_name: Union[str, pathlib.Path]):
"""Ensure that the given folder is empty.
Hidden files and folders (those beginning with ``.``) and ignored. Sub-folders are checked recursively.
Args:
folder_name (str | pathlib.Path): The folder to ensure is empty.
Raises:
... | Ensure that the given folder is empty.
Hidden files and folders (those beginning with ``.``) and ignored. Sub-folders are checked recursively.
Args:
folder_name (str | pathlib.Path): The folder to ensure is empty.
Raises:
FileExistsError: If ``folder_name`` contains any non-hidden files, ... | ensure_folder_is_empty | python | mosaicml/composer | composer/utils/file_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py | Apache-2.0 |
def ensure_folder_has_no_conflicting_files(folder_name: Union[str, pathlib.Path], filename: str, timestamp: Timestamp):
"""Ensure that the given folder does not have any files conflicting with the ``filename`` format string.
If any filename is formatted with a timestamp where the epoch, batch, sample, or token... | Ensure that the given folder does not have any files conflicting with the ``filename`` format string.
If any filename is formatted with a timestamp where the epoch, batch, sample, or token counts are after
``timestamp``, a ``FileExistsError`` will be raised.
If ``filename`` and occurs later than ``timestam... | ensure_folder_has_no_conflicting_files | python | mosaicml/composer | composer/utils/file_helpers.py | https://github.com/mosaicml/composer/blob/master/composer/utils/file_helpers.py | Apache-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.